1

I'm writing a powershell script to get the status of some IIS sites and it works perfectly using a string as the name:

$service = (Invoke-Command -ComputerName $ComputerName  {Import-Module WebAdministration; Get-WebsiteState -Name "DefaultWebsite"}).value

However when I try to pass a variable in the name it no longer works and instead now returns the statuses of all IIS sites on my server

$service = (Invoke-Command -ComputerName $ComputerName  {Import-Module WebAdministration; Get-WebsiteState -Name "$serv"}).value

Nothing I seem to try resolves this issue - any advice would be appreciated!

mklement0
  • 382,024
  • 64
  • 607
  • 775
JW1990
  • 35
  • 2
  • The accepted answer works, but in PSv3+ there is a simpler solution via the `$using:` scope - see https://stackoverflow.com/a/35492616/45375 – mklement0 Dec 23 '19 at 16:31

1 Answers1

1

You need to pass the $serv argument to the script block:

$service = (
    Invoke-Command -ComputerName $ComputerName {
       param ($serv)
       Import-Module WebAdministration
       Get-WebsiteState -Name $serv
    } -ArgumentList $serv
).value

As mklement0 commented, you could also use the using scope in PS3+:

$service = (
    Invoke-Command -ComputerName $ComputerName {
       Import-Module WebAdministration
       Get-WebsiteState -Name $using:serv
    }
).value
mhu
  • 17,720
  • 10
  • 62
  • 93