1

I have the following powershell script:

$BizTalkHosts = "BTSSvc*"
    Foreach($svc in Invoke-Command -Computer d-vasbiz01 -ScriptBlock{ get-service -Name $BizTalkHosts})
    {
        Write-Host $svc.name
    }

I want this to return a list of services on the remote computer that begin with "BTSSVC*". Problem is, I won't actually know the service name until runtime, it will be passed into the script as a param.

When I run the above script I get a list of ALL services - not what I want! However, if I provide a string literal to the get-service cmdlet (i.e. get-service -Name "BTSSvc*) it works fine, providing a filtered list.

Can anyone please explain what I'm doing wrong?

1 Answer 1

3

There's no need to use Invoke-Command in this case, you can get the services with Get-Service :

Get-Service -Name $BizTalkHosts -ComputerName d-vasbiz01

To be able to do that with Invoke-Command (which is an overkill), you need to create a parameter inside the script block and pass $BizTalkHosts to the script block via the -ArgumentList parameter

$BizTalkHosts = "BTSSvc*"
    Foreach($svc in Invoke-Command -Computer d-vasbiz01 -ScriptBlock{ param($name) get-service -Name $name}) -Argument $ArgumentList 
    {
        Write-Host $svc.name
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks Shay, you certainly pointed me in the right direction. In the end I had to use (I think!) an invoke-command because I needed to restart the hosts that I found: #ok now restart the hosts Foreach($svc in get-service -Name $BizTalkHosts -Computer $TargetServer) { Invoke-Command -session $Session -ScriptBlock{param($name) restart-service -name $name} -Argument $svc.name write-host "The host [{0}] has been restarted" -f $svc.name }
You can also restart hosts with the Restart-Computer cmdlet :)
Wow - there's a cmdlet for everything! Good thing you know them all Shay - thanks again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.