Search code examples
powershellscoperemoting

Powershell Get-WebsiteState using variable as Name input


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!


Solution

  • 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