PowerShell: Working on Files

By Xah Lee. Date: . Last updated: .

Open File by Default App

# open a jpg file
Invoke-Item ~/mycat.jpg
# open current dir
Invoke-Item .

Create New File

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

Delete a File

# delete a file in current dir
rm .\photo.jpg
# delete a file by path
rm "~/travel photo.jpg"

Copy File

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

Create a Symbolic Link

New-Item -ItemType SymbolicLink -Path "name" -Value "destinationPath"

Create a hardlink:

New-Item -ItemType HardLink -Path "name" -Value "destinationPath"

Create a junction:

New-Item -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

<# join all files in a dir into single file #>

Get-Content ~/manual/* -Filter *html -Raw | Set-Content -NoNewline new.html

Compare Files

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