This is a collection of some PowerShell tricks, especially if you come from Unix bash.
In bash I often want to abort the script if an exit code of a program is not zero or another error occurs. The bash equivalent to set -e
$ErrorActionPreference = 'Stop'The set +e equivalent is
$ErrorActionPreference = 'Continue'You can use this in a multi line RUN command in Dockerfiles for Windows to abort on the first error:
- Windows:
RUN powershell -Command $ErrorActionPreference = 'Stop'; fail; success - Linux:
RUN fail && success
In bash I sometimes want to debug the script while it is running. The bash set -x flag shows all lines as well as the @echo on in cmd shell, the Powershell equivalent is
Set-PSDebug -Trace 1This one is easy.
wget -Uri $url -OutFile $localfileTo download a file with BasicAuth use this
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($user, $pass)
$WebClient.DownloadFile( $url, $localfile )To extract a ZIP file use this
Expand-Archive -Path $zip -DestinationPath $dest -ForceTo calculate a SHA256 sum of a file use this
((Get-FileHash $filename -Algorithm sha256).HashTo list all environment variables use
ls env:List files sorted by date, oldest files at the end
ls | sort LastWriteTime -Desor with the full option: ls | sort LastWriteTime -Descending
List files sorted by date, newest files at the end
ls | sort LastWriteTimeFrom time to time playing with containers you might want to just delete all containers. This one is really easy and exactly the way as on Linux/Mac:
docker rm -vf $(docker ps -qa)Surprise!