Post

PowerShell (and cmd by the way)

PowerShell (and cmd by the way)

Knowledge, commands, configurations, guides and everything helpful when working with PowerShell in Windows.

Basics

Comments

  • #
    • Use hashtag for comments in PowerShell

Get-Item

Primarily used to retrieve a specific item at a given location like: file, folder, registry key (or other objects supported by PowerShell providers).

  • Get-Item .
    • Get object of current directory
  • gi .
    • Shortcut for Get-Item

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)
{
    # ...
}

Environmental Variables (envs)

Show Env

1
2
3
4
5
# Short way
$env:EnvName

# Full way
[System.Environment]::GetEnvironmentVariable("VariableName", "User")

Show Envs

1
2
# Available scopes: User, Machine, Process
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)

Show Envs by name

1
2
3
4
5
# Normal way
Get-Item env:EnvName*

# Shortcut way
gi env:EnvName*

Set Env (temporarily)

1
2
3
4
5
6
7
8
# Replace variable
$env:VariableName = "VariableValue"

# Append variable
$env:VariableName += ";VariableValue"

# Add to the beginning
$env:VariableName = 'VariableValue;' + $env:VariableName 

Set Env (permanently)

1
[Environment]::SetEnvironmentVariable('VariableName','VariableValue')

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

Command Prompt (cmd)

Set variable

1
set VariableName = VariableValue

Set env

1
setx VariableName VariableValue /m