My Technical Notes

Wednesday, 16 December 2015

PowerShell: Pass arguments to a script

This can be easily done. In our `.ps1` script, we must list our parameters just like in a command, but at the top of the file:


Param([string]$Message, [int]$NumTimes)

for ($i = 0; $i -lt $NumTimes; ++$i) {
    Write-Host $Message
}

Thereafter, to call it within PowerShell:


# full path:
C:\path\to\script.ps1 -Message "Hello World" -NumTimes 5

# local (or relative path)
.\script.ps1 -Message "Hello World" -NumTimes 5

# using full path with ampersand operator
& "C:\path\to\script.ps1" -Message 'Hello world' -NumTimes 5

# using local path with ampersand operator
& ".\script.ps1" -Message 'Hello world' -NumTimes 5

To call it within cmd:


powershell.exe script.ps1 -Message "Hello World" -NumTimes 5

No comments: