Windows Power Shell

Updated 13/04/2021

Basic Functions

1
2
3
4
5
6
7
8
9
10
11
12
--- debug
Set-PSDebug -Off;
#Set-PSDebug -Trace 1;
write-host "Do the thing";

--- Internet Information Services
Restart-IIS
Start-IIS

-- Allow scripts to run
Get-ExecutionPolicy
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

PowerShell Core is portable as pwsh

invoke-expression

This will open a new ps window, Read-Host keeps it open.

1
2
invoke-expression 'cmd /c start powershell -Command { write-host "Running stubs!"; set-location ".\stubs\foo\"; docker-compose up ; Read-Host}';
invoke-expression 'cmd /c start powershell -Command { write-host "Running Run_Api!"; set-location ".\api\"; ./Run_Api.ps1 ; Read-Host}';

You can also pass set-location an absolute path, this is generally trash but will work in a pinch!

1
set-location "C:\Dev\foo-app\api\";

Argument

foo.ps1 foo bar baz

1
2
3
4
write-host "There are a total of $($args.count) arguments"
for ( $i = 0; $i -lt $args.count; $i++ ) {
write-host "Argument $i is $($args[$i])"
}

Named Parameters

foo.ps1 -Reset true -BuildSource true

1
2
3
4
Param(
[switch]$Reset,
[switch]$BuildSource
)

Parameter attribute

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.1#parameter-attribute

Title

1
$host.ui.RawUI.WindowTitle = ''Sweet Title''

Operators

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.1#equality-operators

Approved Verbs for PowerShell Commands

https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands?view=powershell-7.3

Set-Variable

1
2
3
4
5
6
// set
Set-Variable -Name "BearerToken" -Value $(GetBearerToken) -Scope global // accessible by other scripts running
Set-Variable -Name "BearerToken" -Value $(GetBearerToken) -Scope script // only accessible in this scripts scope

// get
"Authorization" = "Bearer $(Get-Variable -Name "BearerToken" -ValueOnly)"