A question on variables

Welcome Forums General PowerShell Q&A A question on variables

Viewing 3 reply threads
  • Author
    Posts
    • #211464
      Participant
      Topics: 12
      Replies: 11
      Points: 156
      Rank: Participant

      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.

       

       

       

       

    • #211473
      Participant
      Topics: 12
      Replies: 519
      Points: 1,194
      Helping Hand
      Rank: Community Hero
      $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

    • #211527
      Participant
      Topics: 12
      Replies: 1610
      Points: 2,508
      Helping Hand
      Rank: Community Hero

      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

      • This reply was modified 2 months, 1 week ago by Rob Simmers.
    • #211995
      Participant
      Topics: 12
      Replies: 11
      Points: 156
      Rank: Participant

      Thanks Rob

Viewing 3 reply threads
  • You must be logged in to reply to this topic.