====== File Operations ======
====== Path References ======
$env:userprofile\Desktop
$Home\Desktop
~\Desktop
=== User Split-Path to get folder name ===
cd $(Split-Path $PROFILE)
====== 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 of ''Get-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
Unzip zip archives contained in another zip archive.
Expand-Archive -DestinationPath .\zips '.\all_reports.zip'
ls .\zips\ | % {Expand-Archive -DestinationPath $env:temp $_.FullName}
=== Create a folder with name following scheme ===
$suffix = 1
while ((Test-Path "$env:temp\mg-$suffix") -ne $false) {
$suffix += 1
}
mkdir "$env:temp\mg-$suffix"
$names = @("alpha", "beta", "gamma")
$name = 0
while ($name -lt $names.Count) {
if ((Test-Path "$env:temp\$names[$name]") -eq $false) {
break
}
$name += 1
}
if ($name -eq $names.Count) {
$name = 0
}
mkdir "$env:temp\$($names[$name])"