Post

PowerShell

PowerShell

Basics

Set Output

Out-File (bash >)

1
dir | Out-File -FilePath .\output.txt

Copy file

Copy-Item (bash cp)

  • Path - specify source
  • Destination - specify target
  • Include - specify file filter
  • Recurse - invoke recursively (bash -r)
  • Force - always overwrite (bash -f)
  • Confirm - prompts before running the cmdlet
  • PassThru - return an object (and by the way e.g. its path)
1
2
3
4
5
6
7
Copy-Item `
  -Path "./source/directory/*" `
  -Destination "./target/directory" `
  -Include "*.jar" `
  -Recurse `
  -Confirm `
  -PassThru

Remove file

Remove-Item (bash rm)

1
Remove-Item ./file.txt

String interpolation

1
2
$VERSION = "2.1.1-SNAPSHOT"
$jarFile = "myapp-$VERSION.jar"

Download File

Invoke-WebRequest (bash curl)

  • $ProgressPreference = 'SilentlyContinue' - Disable progress bar
1
Invoke-WebRequest localhost:8080/archive.zip -OutFile ./logs.zip

Alternative

1
iwr localhost:8080/archive.zip -o logs.zip

Various

Check if file exists

1
2
3
4
if (Test-Path -Path $TARGET_FILE -PathType Leaf)
{
    # ...
}

Shell behavior config

Enable debugging

Set-PSDebug -Trace 1 (bash set -x)

Stop execution on first error

$ErrorActionPreference (bash set -e)

1
$ErrorActionPreference = "Stop"

PowerShell Profile

Get location of PowerShell Profile

  • Note that this location actually may not contain any file - in such case it will be needed to create it manually
1
$PROFILE

Create PowerShell Profile if not exist

  • Creates Microsoft.PowerShell_profile.ps1 file
1
New-Item -path $PROFILE -type File -force