A question on variables

Hello All,

I have learned alot of great things in the last few weeks on my powershell journey. Now one challenge I face right now is understanding how to use variables with the invoke-command. Now from my knowledge I understand invoke-command executes commands on the remote machines.

Therefore any variables that have been defined in a script on a local machine will not be picked up.

 

So for example

$ServerName = StarShip

Invoke-Command -ComputerName $ServerName { get-process -ComputerName}

 

So as you can see I am passing variables that can be mapped locally. So my question is how does one map variables inside the bubble of invoke-command. So invoke-command will see the variables and execute accordingly.

 

Many thanks

 

FishandChips.

 

 

 

 

$ServerName = 'StarShip'

Invoke-Command -ComputerName $ServerName { get-process -ComputerName $Using:ServerName }

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables

As a side note, you should not be using -ComputerName in the scriptblock.

$ServerName = 'StarShip'

Invoke-Command -ComputerName $ServerName { get-process }

Another frequent beginner issue is a double-hop. Basically, you can only authenticate to the first server, so this will not work:

$ServerName = 'StarShip'
$AnotherServerName = 'EscapePod'

Invoke-Command -ComputerName $ServerName { get-process -ComputerName $using:$AnotherServerName}

Take a look at this eBook: Secrets of PowerShell Remoting

Thanks Rob