首页 > 解决方案 > 无法从 C# 程序加载 PS 脚本,因为脚本在系统上被禁用,范围设置为绕过

问题描述

因此,我在这里和其他站点上查看了几篇文章但是即使将 Executionpolicy 更改为 RemoteSigened 我仍然收到错误,我什至尝试在 MachinePolicy 上使用 Bypass 并启用脚本以在组策略中运行。

在此处输入图像描述

我找到了这个使用 C# 传递 PowerShell 参数的示例,当我尝试调用时出现以下错误。

System.Management.Automation.PSSecurityException:'文件路径\TestADUser.ps1 无法加载,因为在此系统上禁用了运行脚本。有关详细信息,请参阅https://go.microsoft.com/fwlink/?LinkID=135170 上的 about_Execution_Policies。

    public string Test()
    {
        StringBuilder sb = new StringBuilder();
        string script = @"Path\TestADUser.ps1";
        var FirstName = "Test1234";
        PowerShell shell = PowerShell.Create();
        shell.AddCommand(script, false);
        shell.AddParameter("FirstName", FirstName);
        Collection<PSObject> results = shell.Invoke();
        Collection<ErrorRecord> errors = shell.Streams.Error.ReadAll();

        if (errors.Count > 0)
        {
            foreach (ErrorRecord error in errors)
            {
                sb.AppendLine(error.ToString());
            }
        }
        else
        {
            foreach (PSObject result in results)
            {
                sb.AppendLine(result.ToString());
            }
        }
        return sb.ToString();
    }

测试ADUser.ps1

param(
[parameter(position=0)]
[string]$FirstName)
##Output
Write-Output $FirstName

标签: c#powershell

解决方案


推荐阅读