如何将param值传递给Invoke-Command cmdlet?

时间:2016-11-22 07:52:52

标签: powershell parameters invoke-command

我编写了一个简单的脚本来修改远程计算机上的hosts文件,但出现了问题。

脚本:

param(
   [string]$value
)

$username = 'username'
$password = 'password'
$hosts = "172.28.30.45","172.28.30.46"
$pass = ConvertTo-SecureString -AsPlainText $password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$pass

ForEach ($x in $hosts){
   echo "Write in $x , value: $value"
   Invoke-Command -ComputerName $x -ScriptBlock {Add-Content -Path "C:\Windows\system32\drivers\etc\hosts" -Value $value} -Credential $cred
   echo "Finish writing."
}

echo "End of PS script."

运行时,会为每个主机文件写入一个新的空行。此行echo "Write in $x , value: $value"显示 $ value 值。 我做错了什么?

1 个答案:

答案 0 :(得分:2)

您必须通过在scriptblock中定义param部分并使用-ArgumentList传递参数来将参数传递给scriptblock

Invoke-Command -ComputerName $x -ScriptBlock {
    param
    (
        [string]$value
    )
    Add-Content -Path "C:\Windows\system32\drivers\etc\hosts" -Value $value
    } -Credential $cred -ArgumentList $value

或者您利用using:变量前缀:

Invoke-Command -ComputerName $x -ScriptBlock {
    Add-Content -Path "C:\Windows\system32\drivers\etc\hosts" -Value $using:value
    } -Credential $cred
相关问题