PowerShell: Working on Files

By Xah Lee. Date: . Last updated: .

Open File by Default App

# open a jpg file
ii c:/Users/xah/mycat.jpg
# open current dir
ii .

Create New File

# create a empty new file xyz.txt in current dir
ni xyz.txt
# create a file xyz.txt with content abc
ni xyz.txt -value "abc"

Delete a File

# delete a file in current dir
rm .\cat.jpg
# delete a file by full path
rm "c:/Users/xah/cat photo.jpg"

Copy File

# copy a file in current dir to parent dir
cp my_cat.jpg ../
# copy file by full path
cp "c:/Users/john/my_cat.jpg" -Destination "f:/backup/"

Create a Symbolic Link

ni -ItemType SymbolicLink -Path "name" -Value "destinationPath"

Create a hardlink:

ni -ItemType HardLink -Path "name" -Value "destinationPath"

Create a junction:

ni -ItemType Junction -Path "name" -Value "destinationPath"

Print File Content

gc filename
#print first 50 lines of file
gc filename | select -first 50
# print last 50 lines of file
gc filename | select -Last 50

Join Files

gc filename1, filename2 > newFileName

Compare Files

# compare if file f1 f2 are the same
diff (gc f1) (gc f2)


Practical How-To

PowerShell in Depth

Programing PowerShell

Script Examples