Search code examples
powershellinvoke-commandscriptblock

Invoke-Command -ScriptBlock bringing variable with LIST


I am trying to execute a script remotely to get the list of service with exclusion of certain service currently in stopped state. I am not able to pass the exclusion variable as list.

If i just use it locally it works but within remote invoke command it doesn't.

$exclusionList = 'DoSvc', 'gupdate', 'sppsvc', 'dmwappushservice', 'edgeupdate', 'Intel(R) TPM Provisioning Service', 'wscsvc', 'LPlatSvc', 'Net Driver HPZ12', 'gpsvc', 'Pml Driver HPZ12', 'RstMwService'

$so = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck 

Invoke-Command -ComputerName $IP -UseSSL -ScriptBlock { param([string]$eList) get-service -Exclude $eList| where {$_.StartType -eq "Automatic" -and $_.Status -eq "Stopped"} -ArgumentList $exclusionList  } -SessionOption $so -Credential Computer\User01

Removing $elist from ScriptBlock works. But I do want to pass the value of exclusion of certain service within the sriptblock


Solution

  • you try to access a variable ($exclusionList) from a remote computer. You can do so, as you did, by specifying the variable with the parameter "-ArgumentList" or by using $using.

    Access Variable with the parameter "-ArgumentList"

    Invoke-Command -ComputerName $IP -UseSSL -ScriptBlock {get-service -Exclude $args[0] | where {$_.StartType -eq "Automatic" -and $_.Status -eq "Stopped"} -ArgumentList $exclusionList  } -SessionOption $so -Credential Computer\User01
    

    The variable provided by the parameter "-Argumentlist" can be accessed from the ScriptBlock by the variable $args, which is an array. To access the first element provided by the parameter "-Argumentlist" you can do "$args[0]".

    MS Docu

    Alternatively you can use $using to access a variable from the remote computer:

    Invoke-Command -ComputerName $IP -UseSSL -ScriptBlock {get-service -Exclude $using:exclusionlist | where {$_.StartType -eq "Automatic" -and $_.Status -eq "Stopped"}} -SessionOption $so -Credential Computer\User01
    

    By doing so you do not have to specify the parameter "-Argumentlist". See $using in the Docu.