简体   繁体   中英

Execution policy modification

I need to run few scripts in different servers which will in turn stop/start the services in many other servers.

I have created a script to change the policy to "Bypass" and run the scripts and then made the changes back to normal.

$LOGPATH = "output.txt"
$system_default_policy = Get-ExecutionPolicy
"Current execution policy $system_default_policy" | Out-File -FilePath $LOGPATH
if ($syste_default_policy -ne 'Bypass') {
    "Changing the execution policy from $system_default_policy to Bypass" | Out-File -FilePath $LOGPATH -Append
    Set-ExecutionPolicy Bypass -Force
    "Successfully changed the execution policy to Bypass" | Out-File -FilePath $LOGPATH -Append
}

### executing the commands to stop/start the services

"Re-writing the changes to default policy" | Out-File -FilePath $LOGPATH -Append
Set-ExecutionPolicy $system_default_policy -Force
"Changed the policy to " + $(Get-ExecutionPolicy) | Out-File -FilePath $LOGPATH -Append

However, this seems to be a redundant process in the below case.

  1. If the execution policy is already Bypass, then I'm simply resetting it in the last line.
  2. I have to run multiple scripts in the same server, so for each script I'm changing it to 'Bypass' and setting it back to original.

Is there any other way where I will run this script only once (to change the execution policy) before executing the scripts and then changing it to original value at the end after running all the scripts.

The execution policy does only apply to scripts, hence it does not apply to code that is being invoked on the host or passed as an command. There are various ways to do that, some of which are:

Invoke-Command from a remote computer.

Invoke-Command -ComputerName $Computer -ScriptBlock { 
    # Code 
}

powershell.exe -Command locally

powershell.exe -Command "#code"

However, usually the easiest way to run scripts without changing the configuration is

powershell.exe -ExecutionPolicy Bypass -File C:\yourscript.ps1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM