3

I wrote a simple script to modify hosts file on remote machines but something goes wrong.

Script:

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."

When run, it writes a new empty line for each hosts file. This line echo "Write in $x , value: $value" displays $value value. What I'm doing wrong?

4c74356b41
  • 69,186
  • 6
  • 100
  • 141
Vladlen Gladis
  • 1,699
  • 5
  • 19
  • 41

1 Answers1

2

You have to pass the parameter to the scriptblock by defining a param section within your scriptblock and pass the parameters using -ArgumentList :

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

Or you leverage the using: variable prefix:

Invoke-Command -ComputerName $x -ScriptBlock {
    Add-Content -Path "C:\Windows\system32\drivers\etc\hosts" -Value $using:value
    } -Credential $cred
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172