Invoke-Command with Foreach

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Chris Chris 2 months ago.

  • Author
    Posts
  • #71081
    Profile photo of Chris
    Chris
    Participant

    Hey Guys,

    I'm really enjoying getting stuck into powershell at the moment, im creating a tool (little project) to show login info for a particular PC. It works when i get the user to input the PC's Name, but what i ideally want, is all of the PC's to list in a gridview, then they can filter themselves,

    I have the code working, but my loop is giving me "one or more computer names are not valid. IF you are trying to pass a URI use the -ConnectionURI parameter...

    Here is the loop im using currently:

     import-module ActiveDirectory
    
    $credpath = 'C:\safe\secretfile.txt'
    $c = Import-Clixml -Path $credpath
    
    $comp = Get-ADComputer -searchbase "dc=***,dc=internal" -Properties Name -Filter * | Select-Object Name 
    
    foreach ($computer in $comp) {
    
    Invoke-Command -ComputerName $computer -ScriptBlock {-File 'N:\PSScripts\Get-LogonHistory.ps1' | Select-Object UserName,Action,TimeStamp | Out-GridView}
    }
    

    the GetLogonHistory is just a file with the functions in it.

    Any ideas?

  • #71119
    Profile photo of Perry Harris
    Perry Harris
    Participant

    Invoke-Command will take a list of computernames and iterate through them itself, so you do not need to use the foreach. Also, With the Select, you don't get a clean list of computernames. Try

     import-module ActiveDirectory
    
    $credpath = 'C:\safe\secretfile.txt'
    $c = Import-Clixml -Path $credpath
    
    $comp = (Get-ADComputer -searchbase "dc=***,dc=internal" -Properties Name -Filter * ).Name
    
    Invoke-Command -ComputerName $comp -ScriptBlock -FilePath 'N:\PSScripts\Get-LogonHistory.ps1' | Select-Object UserName,Action,TimeStamp | Out-GridView
    
    
  • #71122

    Hi Chris,
    You have to expand Name property like this

    $comp = Get-ADComputer -searchbase "dc=***,dc=internal" -Properties Name -Filter * | Select-Object -Expand Name 
    

    Or specify name property in invoke-command like this

    Invoke-Command -ComputerName $computer.name
    

    Do you really want to output invoke-command result to gridview? If you have 100 computers, you will get 100 gridview windows.

  • #71311
    Profile photo of Chris
    Chris
    Participant

    Hi guys,

    Thank you for looking at this, Aleksandras, what i ideally wanted, was all of the computers to be in one GridView, with the ability to filter / search etc, rather than have to put in the specific computer name into a variable before the search. I imagine i would need to almost insert them as rows into the existing gridview?

You must be logged in to reply to this topic.