简体   繁体   English

C# PowerShell 脚本不适用于 ExecutionPolicy

[英]C# PowerShell Script not working with ExecutionPolicy

I´m trying to run a PowerShell script with C# on .netCore.我正在尝试在 .netCore 上使用 C# 运行 PowerShell 脚本。

I have tried many different solutions for now, but none of them seem to work.我现在尝试了许多不同的解决方案,但似乎没有一个有效。 I just want to execute a PowerShell script and set ExecutionPolicies and Scope to make it work.我只想执行一个 PowerShell 脚本并设置 ExecutionPolicies 和 Scope 以使其工作。 But I always got the exception that the ExecutionPolicies don´t allow me to run the script that way.但我总是有一个例外,即 ExecutionPolicies 不允许我以这种方式运行脚本。

Despite that with the actual configuration and code, you find below, I don´t get any feedback from the Debugger after reaching the point where .Invoke();尽管有实际的配置和代码,你会在下面找到,在到达.Invoke();之后,我没有从调试器那里得到任何反馈 is executed.被执行。 And waiting for response and letting the software doing its stuff in background leads always to a stackoverflow exception.等待响应并让软件在后台执行其操作总是会导致 stackoverflow 异常。

commandParameters is a simple Dictionary<string, string> commandParameters 是一个简单的 Dictionary<string, string>

Any thoughts on this?对此有何想法?

Cheers.干杯。


var iss = InitialSessionState.CreateDefault2();
        // Set its script-file execution policy.
        iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
        iss.ExecutionPolicy = (ExecutionPolicy)Microsoft.PowerShell.ExecutionPolicyScope.CurrentUser;

        // Create a PowerShell instance with a runspace based on the 
        // initial session state.
        PowerShell ps = PowerShell.Create(iss);

 ps.AddCommand(path + "\\" + fileName);
        ps.AddParameters(commandParameters);
        var results = ps.InvokeAsync().GetAwaiter().GetResult();
  • Assigning to iss.ExecutionPolicy only ever controls the execution policy for the current process .分配给iss.ExecutionPolicy只控制当前进程的执行策略

  • Do not assign a Microsoft.PowerShell.ExecutionPolicyScope value, as it is an unrelated enumeration that defines the execution-policy scope , relevant only to the Set-ExecutionPolicy and Get-ExecutionPolicy cmdlets.不要指派Microsoft.PowerShell.ExecutionPolicyScope价值,因为它是一个无关的枚举定义执行政策范围,只与该Set-ExecutionPolicyGet-ExecutionPolicy cmdlet的。 The numeric values of this unrelated enumeration just so happen to overlap with the appropriate [Microsoft.PowerShell.ExecutionPolicy] enumeration values, so that policy scope CurrentUser maps onto policy RemoteSigned (value 0x1 ).此无关枚举的数值恰好与适当的[Microsoft.PowerShell.ExecutionPolicy]枚举值重叠,因此策略范围CurrentUser映射到策略RemoteSigned (值0x1 )。

    • In effect, your second iss.ExecutionPolicy = ... assignment overrides the first one and sets the process-scope execution policy to RemoteSigned .实际上,您的第二个iss.ExecutionPolicy = ...分配覆盖了第一个并将流程范围执行策略设置为RemoteSigned
    • The process-scope execution policy, ie for the current process only , is the only one you can set via an initial session state;进程范围执行策略,即针对当前进程,是唯一可以通过初始会话状态设置的策略; see the next section for how to change policies for persistent scopes.有关如何更改持久作用域的策略,请参阅下一节。

Therefore, iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;因此, iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted; alone is enough to invoke *.ps1 files in the session at hand - remove the second iss.ExecutionPolicy = ... assignment.单独调用当前会话中的*.ps1文件就足够了-删除第二个iss.ExecutionPolicy = ...赋值。


If you want to modify the execution policy persistently , you must use .AddCommand('Set-ExecutionPolicy') with the appropriate arguments and invoke that command.如果要持久修改执行策略,则必须使用.AddCommand('Set-ExecutionPolicy')和适当的参数并调用该命令。 Caveat :警告

  • Changing the persistent current-user configuration also takes effect for regular PowerShell sessions (interactive ones / CLI calls) in the respective PowerShell edition.更改持久当前用户配置也会对相应 PowerShell 版本中的常规PowerShell 会话(交互式会话/CLI 调用)生效。

  • By contrast, if you change the persistent machine configuration - which requires running with elevation (as admin):相比之下,如果您更改持久机器配置 - 这需要以提升运行(以管理员身份):

    • With the Windows PowerShell SDK, the change also takes effect for regular PowerShell sessions.对于Windows PowerShell SDK,此更改也会对常规 PowerShell 会话生效。
    • With the PowerShell (Core) SDK, it only takes effect for the SDK project at hand .使用PowerShell (Core) SDK,只对手头的 SDK 项目生效。 [1] [1]
  • See this answer for sample code.有关示例代码,请参阅此答案

Caveat :警告

  • If the current user's / machine's execution policy is controlled via GPOs (Group Policy Objects), you fundamentally cannot override it programmatically (except via GPO changes).如果当前用户/机器的执行策略是通过GPO (组策略对象)控制的,则您基本上无法以编程方式覆盖它(通过 GPO 更改除外)。

  • To check if a GPO-based policy is in effect :要检查基于 GPO 的策略是否有效

    • Run Get-ExecutionPolicy -List to list policies defined for each available scope, in descending order of precedence.运行Get-ExecutionPolicy -List以按优先级降序Get-ExecutionPolicy -List为每个可用范围定义的策略。
    • If either the MachinePolicy or the UserPolicy scope have a value other than Undefined , then a GPO policy is in effect (run Get-ExecutionPolicy without arguments to see the effective policy for the current session).如果两个MachinePolicyUserPolicy范围比其它的值Undefined ,那么GPO策略生效(运行Get-ExecutionPolicy不带参数来查看当前会话的有效的政策)。

[1] Windows PowerShell stores the execution policies in the registry , which both regular sessions and the SDK consult. [1] Windows PowerShell将执行策略存储在注册表中,常规会话和 SDK 都会咨询。 By contrast, PowerShell (Core) stores them in powershell.config.json files, and in the case of the machine policy alongside the PowerShell executable (DLL) .相比之下, PowerShell (Core)将它们存储在powershell.config.json文件中,并且在机器策略的情况下与 PowerShell 可执行文件 (DLL) 一起存储 Since SDK projects have their own executable, its attendant JSON file is not seen by the executable of a regular PowerShell (Core) installation.由于SDK的项目有自己的可执行文件,随之而来的JSON文件不是由一个普通的PowerShell(核心)安装可执行看到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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