1

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?

1
  • 2
    The variable defined outside your script block is by default not available inside your script block. Use $USING:RestrykcjaNowa instead. Commented Feb 15, 2019 at 14:07

2 Answers 2

2

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

Comments

0

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

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.