PowerShell: Working on Files

By Xah Lee. Date: . Last updated: .

Open File by Default App

Invoke-Item c:/Users/xah/mycat.jpg

Create New File

# create new file in current dir
ni myName

# full syntax
New-Item myName -ItemType file

Delete a File

# delete a file in current dir
Remove-Item .\fileName

# full syntax
Remove-Item -path .\fileName

# using full path
Remove-Item "c:/Users/xah/badphoto.jpg"

Copy File

# copy a file in current dir to parent dir
Copy-Item my_cat.jpg ../

# full syntax variation
Copy-Item  -Path "c:/Users/john/my_cat.jpg" -Destination "f:/backup/"

Print File Content

Get-Content filename
#print first 50 lines of file
Get-Content filename | Select-Object -first 50
# print last 50 lines of file
Get-Content filename | Select-Object -Last 50

Join Files

Get-Content filename1, filename2 > newFileName

Compare Files

# compare if 2 files are the same and or show their differences.
diff (cat f1) (cat f2)

# full syntax
Compare-Object (Get-Content f1) (Get-Content f2)

PowerShell

How-to

Advanced

Script Examples