Invoke-Command inside of a process block

OK. This is something that’s bothered me for a long time and I just want to make sure that I’m doing this correctly. Because to me, it’s sort of kludgy. This is how I create a function with a process block and run invoke-command on multiple computers. This function is just for example purposes; I don’t actually care to have a function that queries the spooler.

Function Get-SpoolerService { Param( # Param1 help description [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, Position=0)] [String[]]$ComputerName ) Begin { $Computers = @() } Process { foreach ($computer in $ComputerName) { $Computers += $computer } } End { $ScriptBlock = { Get-Service Spooler } Invoke-Command -ComputerName $Computers -ScriptBlock $ScriptBlock } } 

The reason I do it this way is because of the way a process block processes objects. You’d think that this would work:

Function Get-SpoolerService { Param( # Param1 help description [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, Position=0)] [String[]]$ComputerName ) Begin { $Computers = @() } Process { foreach ($computer in $ComputerName) { $Computers += $computer } $ScriptBlock = { Get-Service Spooler } Invoke-Command -ComputerName $Computers -ScriptBlock $ScriptBlock } End { } } 

However, when I use a command like this "Server01","Server02","Server03" | Get-SpoolerService, I find that it queries the same server multiple times.

I’ve got several functions that use the top method and it works great. I just have a hard time thinking it’s right.

submitted by /u/LinleyMike
[link] [comments]

Leave a Reply