PowerShell icon indicating copy to clipboard operation
PowerShell copied to clipboard

How to pass this script block

Open sateeshmachineni opened this issue 4 years ago • 1 comments

This may be simple,but i tried many variations of below script...Any suggestions would be greatly helpfull

$scriptblock ={
get-service -ComputerName $parameter.computername | where {$_.name -eq $parameter.serviceName }
}

$pscustomobject = @()

$pscustomobject += [pscustomobject]@{
Computername ='server1'
Servicename ="service1"
}

$pscustomobject += [pscustomobject]@{
Computername ='server2'
Servicename ="service2"
}

Now i tried invoking it like below variations

Invoke-Parallel -ScriptBlock $scriptblock -Parameter $pscustomobject

"server1","server2" | Invoke-Parallel -ScriptBlock $scriptblock -Parameter $pscustomobject

Some services exist in some servers and some other servers ,they dont,so i created pscustom object which maps services to servers

sateeshmachineni avatar Mar 20 '21 12:03 sateeshmachineni

Hi @sateeshmachineni,

You are assigning 2 pscustomobjects to the variable $pscustomobject, then in the scriptblock attempting to match on each. I believe that it is failing because it is lacking an iteration method.

As I understand the Invoke-Parallel cmdlet, -Parameter allows passing a set of static values into the script block without iteration.

To iterate on a list coming into the scriptblock would require passing list into Invoke-Parallel by using either the pipeline or -InputObject.

Here is an untested example, but it should work:

$scriptblock ={
$ComputerName = $_.Computername
$ServiceName = $_.Servicename
get-service -ComputerName $ComputerName | where {$_.name -eq $ServiceName }
}

$pscustomobject = @()

$pscustomobject += [pscustomobject]@{
Computername ='server1'
Servicename ="service1"
}

$pscustomobject += [pscustomobject]@{
Computername ='server2'
Servicename ="service2"
}


Invoke-Parallel -ScriptBlock $scriptblock -InputObject $pscustomobject

$pscustomobject | Invoke-Parallel -ScriptBlock $scriptblock

Cheers, Alan

dieselVtwin avatar Jul 01 '21 03:07 dieselVtwin

Thank you @dieselVtwin and sorry for late reply...

sateeshmachineni avatar Oct 10 '23 06:10 sateeshmachineni