Search code examples
powershellexecution

Set-Execution policy on remote computer using Variable


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?


Solution

  • You have two issues to address:

    1. 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
      
    2. 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