2
votes

I wrote a script to restart a few ASP.NET websites on a remote server:

$computerName = #...
$password = #...
$secureStringPassword = ConvertTo-SecureString -AsPlainText -Force -String $password
$userName = #...
$credential= New-Object System.Management.Automation.PSCredential ($userName, $secureStringPassword)
$websiteNames = #..., #..., #...

Get-PSSession -ComputerName $computerName -Credential $credential | Remove-PSSession 

$psSession = New-PSSession -ComputerName $computerName -Credential $credential

Invoke-Command -Session $psSession -ScriptBlock { $websiteNames | foreach{ Stop-Website -Name $_ } }
Invoke-Command -Session $psSession -ScriptBlock { $websiteNames | foreach{ Start-Website -Name $_ } }

$psSession | Remove-PSSession 

For some reasons my Invoke-Command do not run properly, I have the following error message:

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

When the commands are run after an Enter-PSSession it works fine within a -ScriptBlock it kinda mess up the -Name parameter, any idea how to fix that up?

2

2 Answers

4
votes

The remote session cannot access the variables you have defined locally. They can be referenced with $using:variable

Invoke-Command -Session $psSession -ScriptBlock { $using:websiteNames | foreach{ Stop-Website -Name $_ } }
Invoke-Command -Session $psSession -ScriptBlock { $using:websiteNames | foreach{ Start-Website -Name $_ } }

More information in the about_remote_variables help:

get-help about_remote_variables -Full
0
votes

Actually just needed to pass the arguments to the -ArgumentList of the -ScriptBlock and use $args to reference to it within the function block:

Invoke-Command -Session $psSession -ScriptBlock { $args | foreach{ Stop-Website -Name $_ } } -ArgumentList $websiteNames
Invoke-Command -Session $psSession -ScriptBlock { $args | foreach{ Start-Website -Name $_ } } -ArgumentList $websiteNames