Scripting. Powershell, VMware, Windows, Active Directory & Exchange. All that kind of stuff…..
RSS icon Email icon Home icon
  • PowerShell 2.0: One Cmdlet at a Time #34 Invoke-Commmand

    Posted on January 8th, 2010 Jonathan Medd 2 comments

    Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Invoke-Command cmdlet.

    What can I do with it?

    Run commands on local or remote computers and return the results.

    Examples:

    Establish a persistent remote PowerShell connection to Test01 using New-PSSession and store it in the variable $session. Then return the results for which services begin with T.

    $session = New-PSSession -ComputerName Test01
    Invoke-Command -Session $session -ScriptBlock
     {Get-Service | Where-Object {$_.name -like 'T*'}}

    You can see that the results contain a property PSComputerName that shows which server the results came from.

    Invoke-Command1

    You don’t need to stretch your imagination too far to see how this could quickly become extremely powerful. Imagine instead that you used New-PSSession to make sessions to 100 servers stored in a csv file and run the same command to all of those servers. The change in the code would be very small.

    $sessions = New-PSSession -ComputerName (Get-Content servers.csv)
    Invoke-Command -Session $sessions -ScriptBlock
     {Get-Service | Where-Object {$_.name -like 'T*'}}

    How could I have done this in PowerShell 1.0?

    Remoting did not exist in PowerShell 1.0, you would have needed to use Remote Desktop to run an interactive session on a remote server.

    1000 things 1% better!

     

    2 responses to “PowerShell 2.0: One Cmdlet at a Time #34 Invoke-Commmand” RSS icon

    • Arnoud Jansveld

      Hi Jonathan, great series. I noticed you used the following in a few of your examples:

      -ComputerName (Import-Csv servers.csv)

      Does this actually work? The parameter accepts an array of strings which Import-Csv does not return.

      Regards,
      Arnoud

    • Thanks for the feedback it’s good to know someone is keeping tabs on me!

      You are absolutely correct and I have to admit to being slightly lazy with that example and not actually testing it, I think that is the only example I did not test in this series! My excuse was that it was in the help file for New-PSSession, see example 9.

      http://technet.microsoft.com/en-us/library/dd347668.aspx

      I have updated the series to use (Get-Content servers.csv) instead and also filed a documentation bug which I would be more than happy if you voted for:

      https://connect.microsoft.com/PowerShell/feedback/ViewFeedback.aspx?FeedbackID=525002

      Thanks again and make sure you keep checking for other mistakes!


    Leave a reply