This guide covers the fundamental file system operations in PowerShell.
Viewing Objects in a Directory
To view the content of a directory on a Windows file server, use the Get-ChildItem cmdlet.
Basic Usage
Get-ChildItem -Force \\fs\Shared
The -Force parameter shows hidden files.
Recursive Listing
To also check all subfolders and their content:
Get-ChildItem -Force \\fs\Shared -Recurse
Filtering Output
Use Filter, Exclude, Include and Path parameters:
Get-ChildItem -Path \\fs\Shared\IT -Recurse -Include *.exe |
Where-Object -FilterScript {($_.LastWriteTime -gt '2018-04-01')}
This searches for all executable files modified after April 1, 2018.
Creating Files and Folders
Use the New-Item cmdlet and specify the type of item you want to create.
Create a Folder
New-Item -Path '\\fs\Shared\NewFolder' -ItemType Directory
Create an Empty File
New-Item -Path '\\fs\Shared\NewFolder\newfile.txt' -ItemType File
Create a File with Content
Using Out-File
$text = 'Hello World!' | Out-File $text -FilePath C:\data\text.txt
To overwrite an existing file, use the –Force switch parameter.
Using Export-Csv
Get-ADuser -Filter * | Export-Csv -Path C:\data\ADusers.csv
Deleting Files and Folders
To delete objects, use the Remove-Item cmdlet.
Delete with Confirmation
Remove-Item -Path '\\fs\shared\it\'
If the object is not empty, you’ll be prompted to confirm.
Delete Without Confirmation
Remove-Item -Path '\\fs\shared\it\' -Recurse
Delete Old Files
Clean up files older than 30 days:
$Folder = "C:\Backups"
#delete files older than 30 days
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-30)} |
ForEach-Object {
$_ | del -Force
$_.FullName | Out-File C:\log\deletedbackups.txt -Append
}
#delete empty folders and subfolders if any exist
Get-ChildItem $Folder -Recurse -Force -ea 0 |
? {$_.PsIsContainer -eq $True} |
? {$_.getfiles().count -eq 0} |
ForEach-Object {
$_ | del -Force
$_.FullName | Out-File C:\log\deletedbackups.txt -Append
}
Check if File Exists Before Deleting
$FileName = 'C:\data\log.txt'
If (Test-Path $FileName) {
Remove-Item $FileName
}
Delete Files from Remote PCs
$filelist = @("\c$\Temp", "\c$\Backups") #files and folders to delete
$computerlist = Get-Content C:\data\pc.txt #get list of remote pc's
foreach ($computer in $computerlist) {
foreach ($file in $filelist) {
$filepath = Join-Path "\\$computer\" "$filelist" #generate unc paths
if (Test-Path $filepath) {
Remove-Item $filepath -force -recurse -ErrorAction Continue
}
}
}
Copying Files and Folders
The Copy-Item cmdlet enables you to copy objects from one path to another.
Basic Copy
Copy-Item -Path \\fs\Shared\it\users.xlsx `
-Destination \\fs2\Backups\it\users.xlsx
Overwrite Existing Files
Copy-Item -Path \\fs\Shared\it\users.xlsx `
-Destination \\fs2\Backups\it\users.xlsx -Force
Copy from Remote to Local
Copy-Item \\fs\c$\temp -Recurse C:\data\
Copy from Local to Remote
Copy-Item C:\data\ -Recurse \\fs\c$\temp
Copy Between Remote Servers
Copy-Item \\fs\Shared\temp -Recurse \\fs\Shared\test
Copy Only Specific Files
Copy-Item -Filter *.txt -Path \\fs\Shared\it -Recurse `
-Destination \\fs2\Shared\text
Alternative Methods
# Using XCOPY or ROBOCOPY
xcopy C:\source\*.* D:\destination\ /E /H /C /I
# Using COM objects
(New-Object -ComObject Scripting.FileSystemObject).CopyFile('\\fs\Shared', 'fs2\Backup')
Moving Files and Directories
The Move-Item cmdlet moves an item, including its properties, contents, and child items.
Move a File
Move-Item -Path \\fs\Shared\Backups\1.bak `
-Destination \\fs2\Backups\archive\1.bak
Move a Folder
Move-Item -Path \\fs\Shared\Backups `
-Destination \\fs2\Backups\archive
The Backups directory and all its files and subfolders will appear in the archive directory.
Renaming Files
The Rename-Item cmdlet enables you to change the name of an object while leaving its content intact.
Important: You cannot move items with Rename-Item; use Move-Item for that.
Rename a Single File
Rename-Item -Path "\\fs\Shared\temp.txt" -NewName "new_temp.txt"
Rename Multiple Files
$files = Get-ChildItem -Path C:\Temp #create list of files
foreach ($file in $files) {
$newFileName = $file.Name.Replace("A","B") #replace "A" with "B"
Rename-Item $file $newFileName
}
Best Practices
- Test with
-WhatIfbefore executing - Use
-Forcecautiously - it overwrites without prompting - Check paths with
Test-Pathbefore operations - Use UNC paths for remote operations
- Handle errors with Try-Catch blocks
- Log operations for audit trails
Common Parameters
-Path- Specifies the path to the item-Destination- Specifies the destination path-Force- Forces the operation without prompting-Recurse- Performs operation on all child items-Filter- Specifies a filter in provider format-WhatIf- Shows what would happen if the cmdlet runs