即使禁止Set-ExecutionPolicy,如何运行PowerShell脚本?

时间:2012-02-14 04:24:02

标签: java powershell

PowerShell的Set-ExecutionPolicy命令被禁止,所以我不能这样运行:

PS> .\script.ps1 (enter)

除了“Windows PowerShell ISE”之外,还有其他方法可以运行PowerShell脚本吗?

PS:我能够使用Java的ProccessBuilder来运行单个PowerShell命令,但不知道如何运行整个脚本。

4 个答案:

答案 0 :(得分:62)

这是我们用来从Java运行PowerShell脚本的方法(无论执行策略如何都有效):

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -File <script_name>

答案 1 :(得分:7)

最简单最简单的方法就是:

gc .\script.ps1 | iex

这适用于PowerShell,并不关心ExecutionPolicy。只要确保你对新行很小心。将{} s和类似内容放在同一行,在需要的地方使用;

答案 2 :(得分:6)

Oisin Grehan has an interesting post on his blog提供了绕过执行策略的另一种方法。打开一个shell并运行它:

function Disable-ExecutionPolicy {
    ($ctx = $executioncontext.gettype().getfield(
        "_context", "nonpublic,instance").getvalue(
            $executioncontext)).gettype().getfield(
                "_authorizationManager", "nonpublic,instance").setvalue(
        $ctx, (new-object System.Management.Automation.AuthorizationManager
                  "Microsoft.PowerShell"))
}
Disable-ExecutionPolicy

这将删除默认的主机授权管理器,允许您从该shell调用脚本。您必须为打开的每个shell运行此操作,因为执行策略仅在运行它的shell中被覆盖。

答案 3 :(得分:0)

这是对Andy对这个问题的回答的略微增强。如果管理员在GPO中设置了限制性的PowerShell脚本执行策略(可能是错误地认为PowerShell执行策略是安全边界),则可以使用以下命令行获取禁用了执行策略的PowerShell交互式会话:

services.AddDbContext<IMyDbContext, MyDbContext>(options => options.UseLazyLoadingProxies()
        .UseNpgsql("MyConnectionString", opt => opt.UseNodaTime()));

此处的powershell.exe -EncodedCommand ZgB1AG4AYwB0AGkAbwBuACAARABpAHMAYQBiAGwAZQAtAEUAeABlAGMAdQB0AGkAbwBuAFAAbwBsAGkAYwB5AHsAKAAkAGMAdAB4AD0AJABFAHgAZQBjAHUAdABpAG8AbgBDAG8AbgB0AGUAeAB0AC4ARwBlAHQAVAB5AHAAZQAoACkALgBHAGUAdABGAGkAZQBsAGQAKAAiAF8AYwBvAG4AdABlAHgAdAAiACwAIgBuAG8AbgBwAHUAYgBsAGkAYwAsAGkAbgBzAHQAYQBuAGMAZQAiACkALgBHAGUAdABWAGEAbAB1AGUAKAAkAEUAeABlAGMAdQB0AGkAbwBuAEMAbwBuAHQAZQB4AHQAKQApAC4ARwBlAHQAVAB5AHAAZQAoACkALgBHAGUAdABGAGkAZQBsAGQAKAAiAF8AYQB1AHQAaABvAHIAaQB6AGEAdABpAG8AbgBNAGEAbgBhAGcAZQByACIALAAiAG4AbwBuAHAAdQBiAGwAaQBjACwAaQBuAHMAdABhAG4AYwBlACIAKQAuAFMAZQB0AFYAYQBsAHUAZQAoACQAYwB0AHgALAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AHQAbwBtAGEAdABpAG8AbgAuAEEAdQB0AGgAbwByAGkAegBhAHQAaQBvAG4ATQBhAG4AYQBnAGUAcgAgACIATQBpAGMAcgBvAHMAbwBmAHQALgBQAG8AdwBlAHIAUwBoAGUAbABsACIAKQApAH0AOwBEAGkAcwBhAGIAbABlAC0ARQB4AGUAYwB1AHQAaQBvAG4AUABvAGwAaQBjAHkAOwBpAGYAKABUAGUAcwB0AC0AUABhAHQAaAAgACQAUABSAE8ARgBJAEwARQApAHsALgAgACQAUABSAE8ARgBJAEwARQB9AA== -NoExit 是以下代码:

-EncodedCommand

也就是说,通过运行Andy的答案中描述的功能来禁用执行策略,然后对当前用户配置文件脚本(如果存在)进行点源化。