2016-11-22 41 views
3

我編寫了一個簡單的腳本來修改遠程計算機上的hosts文件,但出了問題。如何將param值傳遞給Invoke-Command cmdlet?

腳本:

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"顯示$值值。 我做錯了什麼?

回答

2

你必須通過定義腳本塊內的param部分的參數傳遞給腳本塊和使用-ArgumentList傳遞的參數:

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 
+0

謝謝Martin。 – GVArt