Reputation: 47
I have a problem reverting back powershell execution policy on remote computer using variable.
$RestrykcjaNowa = 'Bypass'
$RestrykcjaZastana = Invoke-Command -ComputerName $Komputer -ScriptBlock { Get-ExecutionPolicy }
$RestrykcjaZastana
Invoke-Command -ComputerName $Komputer -ScriptBlock { Set-ExecutionPolicy -ExecutionPolicy $RestrykcjaNowa -Scope LocalMachine -Force } | Out-Null
But I got an error
Cannot bind argument to parameter 'ExecutionPolicy' because it is null
When I replace variable $RestrykcjaNowa
with value Bypass in last command it goes smoothly.
I noticed that variable $RestrykcjaZastana
is not displayed on the screen when called in 2nd line of the code and is of type int but i can't assign value Bypass to integer variable manually.
What is wrong with my approach?
Upvotes: 1
Views: 2932
Reputation: 10809
You have two issues to address:
Execution policies are not strings; they are a separate enumerated type, [Microsoft.PowerShell.ExecutionPolicy]
. You will have to assign them as such to your variable:
$RestrykcjaNowa = [Microsoft.PowerShell.ExecutionPolicy]::Bypass
Variables outside of scriptblocks need to be referenced from within the script block with using:
:
Invoke-Command -ComputerName $Komputer -ScriptBlock { Set-ExecutionPolicy -ExecutionPolicy $using:RestrykcjaNowa -Scope LocalMachine -Force } | Out-Null
Upvotes: 2
Reputation: 246
Variables are not evaluated when Scriptblock is defined. However for your case, you may use below code with which you can pass variable to scriptblock as an argument:
$RestrykcjaNowa = 'Bypass'
$Komputer = '<Computername>'
$RestrykcjaZastana = Invoke-Command -ComputerName $Komputer -ScriptBlock { Get-ExecutionPolicy }
$RestrykcjaZastana
Invoke-Command -ComputerName $Komputer -ScriptBlock {param($RestrykcjaNowa) Set-ExecutionPolicy -ExecutionPolicy $RestrykcjaNowa -Scope LocalMachine -Force } -ArgumentList $RestrykcjaNowa | Out-Null
Upvotes: 0