PowerShell Organizing Files
Organizing files means moving, copying, and deleting files into tidy folders. A folder is a container that holds files, and New-Item creates one.
Move a file into a folder
Create a folder and a file, then move the file inside. Test-Path checks both the new spot and the old spot.
$null = New-Item -ItemType Directory -Path "archive"
Set-Content -Path "old.txt" -Value "old"
Move-Item -Path "old.txt" -Destination "archive"
Test-Path "archive/old.txt"
Test-Path "old.txt"Copy a file into a folder
Copy-Item leaves the original in place. Both paths exist after the copy.
$null = New-Item -ItemType Directory -Path "archive"
Set-Content -Path "report.txt" -Value "report"
Copy-Item -Path "report.txt" -Destination "archive/report.txt"
Test-Path "report.txt"
Test-Path "archive/report.txt"Delete a file
Remove-Item deletes the file. Test-Path then answers False.
Set-Content -Path "temp.txt" -Value "temp"
Remove-Item -Path "temp.txt"
Test-Path "temp.txt"Example
$null = New-Item -ItemType Directory -Path "docs"
Set-Content -Path "plan.txt" -Value "plan"
Set-Content -Path "notes.txt" -Value "notes"
Set-Content -Path "draft.log" -Value "draft"
Move-Item -Path "plan.txt" -Destination "docs"
Move-Item -Path "notes.txt" -Destination "docs"
Get-ChildItem -Path "docs" -Filter "*.txt" | Sort-Object Name | Select-Object -ExpandProperty NameKey points
- New-Item: the cmdlet that creates a folder when used with -ItemType Directory.
- Move-Item: the cmdlet that moves a file into another folder.
- Copy-Item: the cmdlet that makes a copy of a file in another folder.
- Remove-Item: the cmdlet that deletes a file.
- Test-Path: the cmdlet that answers True when a path exists and False when it does not.
In this example, a docs folder is created and three files are made. The two .txt files are moved into docs, the .log file stays behind, and the last line lists the moved files in name order.
Note
creating the destination folder first avoids a move or copy failing on a missing folder.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
After Move-Item moves old.txt into the archive folder, what does Test-Path "old.txt" print?