How do I pass variables with the Invoke-Command cmdlet? How do I pass variables with the Invoke-Command cmdlet? powershell powershell

How do I pass variables with the Invoke-Command cmdlet?


Alternatively you can use the $Using:scope. See Example 5 under this link.

Example:

$servicesToSearchFor = "*"Invoke-Command -ComputerName $computer -Credential (Get-Credential) -ScriptBlock { Get-Service $Using:servicesToSearchFor }

With $Using: you don't need the -ArgumentList parameter and the param block in the scriptblock.


Either you declare the parameters at the beginning of your scriptblock:

   {          param($user,$unsecurepassword)        net use P: \\Server\dir1\dir2 /persistent:no /user:$User $UnsecurePassword        Get-EventLog -LogName System -After (Get-Date).AddHours(-12) -EntryType Error, Warning | format-list |         out-file P:\EventLog_$env:COMPUTERNAME.log        net use P: /delete /yes    }

Or you acces your arguments using the $args variable:

#first passed parameter$args[0]#second passed parameter$args[1]....

Documentation: MSDN