Search code examples
powershellpowershell-remoting

function parameter not getting assigned


Calling a function that wraps stopping an IIS app pool. Why would the 'Name' parameter for Stop-WebAppPool have an issue? The only thing I can see is since its inside a script block?

error:

Cannot validate argument on parameter 'Name'. The argument is null. Provide a valid value for the argument, and then try running the command again.

function StopAppPool() {
    param( 
        [string] $siteName = "",
        [string] $serverName = ""
    );


    $session = New-PSSession -ComputerName $serverName
    Invoke-Command -ComputerName $serverName -ScriptBlock { Stop-WebAppPool -Name $siteName }   

}

# -- entry here
StopAppPool -siteName "my.test-server.web" -serverName "DEV-MYTEST1"

Solution

  • Name is empty because you can't reference variables directly inside of the Script Block. Using Invoke-Command, you must pass in your $siteName into the Script Block as an argument, and receive it as a parameter inside the Script Block. Something like this:

    ...
    
    Invoke-Command -ComputerName $serverName -ArgumentList $siteName -ScriptBlock {
        Param($siteName)
        Stop-WebAppPool -Name $siteName
        }   
    
    ...