PowerShell Pass Named parameters to ArgumentList

Parveen Kumar picture Parveen Kumar · Jan 6, 2015 · Viewed 20.6k times · Source

I have a PowerShell script that accepts 3 named parameters. Please let me know how to pass the same from command line. I tried below code but same is not working. It assigns the entire value to P3 only. My requirement is that P1 should contain 1, P2 should 2 and P3 should be assigned 3.

Invoke-Command -ComputerName server -FilePath "D:\test.ps1" -ArgumentList  {-P1 1 -P2 2 -P3 3}

Ihe below is script file code.

Param (
    [string]$P3,
    [string]$P2,
    [string]$P1
)
Write-Output "P1 Value :" $P1
Write-Output "P2 Value:" $P2
Write-Output "P3 Value :" $P3

Answer

mjolinor picture mjolinor · Jan 6, 2015

One option:

$params = @{
P1 = 1
P2 = 2 
P3 = 3
}

$ScriptPath = 'D:\Test.ps1'

$sb = [scriptblock]::create(".{$(get-content $ScriptPath -Raw)} $(&{$args} @params)")

Invoke-Command -ComputerName server -ScriptBlock $sb