This is an old revision of the document!
File Operations
Path References
$env:userprofile\Desktop $Home\Desktop ~\Desktop
Common Commands By Example
List Items with Filter/Search for files with matching string in name
Example of finding a file somewhere in the filesystem and outputting the full path and filename.
Get-ChildItem -Recurse -Filter "csc.exe" | foreach {$_.Fullname}
Use a regex with -Match
operator for more advanced filtering.
gci -Recurse | where {$_.Name -Match "^csc.*"} | foreach {$_.Fullname}
List Items
$exclude = @("*.log", "*.tmp", "log*.txt") $files = ls -Recurse -Exclude $exclude Compress-Archive -Path $files -DestinationPath $home\desktop\webagent.zip
$base_path = "$home\downloads" $exclude_dir_files = @("$base_path\tmp\*", "$base_path\log\*", "*.tmp", "*.log" ) ls -Recurse -Exclude $exclude_dir
Example of using -Exclude
and additional regex filtering with -notmatch
operator. This is useful for excluding folders.
$exclude = @("*.log", "*.tmp", "log*.txt*") $files = ls -Recurse -Exclude $exclude $files = $files | where {$_.FullName -notmatch ".*\\logs"} Compress-Archive -Path $files -DestinationPath $home\desktop\webagent.zip
- Use the
-File
or-Directory
option ofGet-ChildItem
to list on those items.
$exclude = @("*.log", "*.tmp", "log*.txt*") $files = ls -File -Recurse -Exclude $exclude Compress-Archive -Path $files -DestinationPath $home\desktop\webagent.zip
Search through files for string/grep
Example
Get-ChildItem -Recurse *.config | Select-String "foo" -List | Select Path
Create File
New-Item -force $env:temp\foo\foo.txt
Zip Files
Example
Compress-Archive -Path .\* -DestinationPath $env:userprofile\desktop\webapp1.zip
Example
$files = ls -Path .\* -Exclude @("*.tmp", "*.log") Compress-Archive -Path $files -DestinationPath $env:userprofile\desktop\webapp1.zip
$files = ls -Recurse | Where-Object {$_.FullName -notlike "*log*"} Compress-Archive -Path $file -DestinationPath $env:userprofile\desktop\webapp1.zip
List contents of archive
$archive = [System.IO.Compression.ZipFile]::OpenRead("$env:userprofile\downloads\archive.zip") $archive.Entries | Select-Object -Property FullName