Search code examples
powershellparametersinvoke-command

How to pass param value to the Invoke-Command cmdlet?


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?


Solution

  • 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