PowerShell Equivalency

When writing PowerShell scripts I find it hard to remember how certain patterns I’m used to in Bash/ZSH are implemented. Here is a list of common commands that there are equivalents for in PowerShell.

Stop on Exit

By default, PowerShell continues on failed commands (I think). I find myself adding this to the top of scripts to cause PowerShell to stop when a non-zero exit code is returned:

$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true

I’m not sure if this applies equally to PowerShell commands as it does to sub-commands.

Creating Directories

The equivalent to mkdir -p is:

New-Item -ItemType Directory -Force $Path

By default, the New-Item command prints out the new item details to the console. To hide these details:

New-Item ... | Out-Null

See if a Directory Exists

To do something if a directory exists:

if (Test-Path $Path) {
    # Actions if directory does exist...
}

And, to do something if a directory does not exist:

if (-not $(Test-Path $Path)) {
    # Actions if directory does NOT exist...
}

Get File Name, Extension, …etc.

To go from a path to the file name, use the Get-ChildItem command:

$(Get-ChildItem $Path).Name

The Name includes the file extension, the BaseName does not. If you used Get-ChildItem to get the path in the first place, the result is already an object with these properties.

Creating Links

To create a symbolic link:

New-Item -ItemType SymbolicLink -Path $LinkPath -Value $RealPath