3

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 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.