KrzychG
KrzychG

Reputation: 47

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?

Upvotes: 1

Views: 2932

Answers (2)

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10809

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
    

Upvotes: 2

Mudit Bahedia
Mudit Bahedia

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

Related Questions