我需要在不同的服务器上运行几个脚本,这些脚本将在许多其他服务器中停止/启动服务 .
我创建了一个脚本,将策略更改为“绕过”并运行脚本,然后使更改恢复正常 .
$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
但是,在下面的案例中,这似乎是一个多余的过程 .
-
如果执行策略已经是Bypass,那么我只是在最后一行重置它 .
-
我必须在同一台服务器上运行多个脚本,因此对于每个脚本我都会绕过'并将其设置回原始脚本 .
有没有其他方法可以在执行脚本之前运行此脚本一次(更改执行策略),然后在运行所有脚本后将其更改为原始值 .
1 回答
执行策略仅适用于脚本,因此它不适用于在主机上调用或作为命令传递的代码 . 有多种方法可以做到这一点,其中一些方法是:
Invoke-Command
来自远程计算机 .powershell.exe -Command
本地但是,通常在不更改配置的情况下运行脚本的最简单方法是