我编写了一个简单的powershell脚本来修改远程计算机上的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 值。
我做错了什么?
答案 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