Reputation: 53
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.
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.
Upvotes: 1
Views: 82
Reputation: 3154
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
Upvotes: 4