Change Execution Policy

I’ve a requirement to change remote server Execution policy during my Script execution, In order to do this I’ve apt below work flow.

  1. Collect Current Execution policy and assign it to Parameter
  2. Change Execution policy to Remotesigned
  3. Change Policy to old state.

I’ve tried with below code but its not allowing me to do so, Can anyone help me with your thoughts.

Step 1:
$global:ExecutionActual = Invoke-command -computername $Windows_Name -scriptblock {Get-ExecutionPolicy -Scope LocalMachine} | Select Value -expandproperty Value

Step 2:

Invoke-command -computername $Windows_Name -scriptblock {Set-ExecutionPolicy RemoteSigned -force}

Step 3:
Invoke-command -computername $Windows_Name -scriptblock {Set-ExecutionPolicy $global:ExecutionActual -force}

I’ve issue with step 3, Below one is the sample error.

Cannot bind argument to parameter ‘ExecutionPolicy’ because it is null.
+ CategoryInfo : InvalidData: (:slight_smile: [Set-ExecutionPolicy], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SetExecution
PolicyCommand

Hello Ganesh,

The error is telling you the argument for parameter ‘executionpolicy’ is null. The reason it’s null is because it is defined on the machine you are running the script on, not the remote machine. You may resolve your issue with either of the following.

Invoke-command -computername $Windows_Name -scriptblock {Set-ExecutionPolicy $args[0] -force} -ArgumentList $global:ExecutionActual

or

Invoke-command -computername $Windows_Name -scriptblock {Set-ExecutionPolicy $using:global:ExecutionActual -force}

Thanks a lot, It’s worked for me.

Fantastic. You are welcome.