Invoke-Command with Foreach

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?

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

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.

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?