【发布时间】:2019-11-15 21:17:47
【问题描述】:
我正在尝试使用C# 运行PowerShell 脚本,并使用this link 作为参考。
到目前为止,我得到了:
try
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddCommand(scriptPath);
var PSOutput = PowerShellInstance.Invoke();
if (PowerShellInstance.Streams.Error.Count > 0)
{
foreach (var line in PowerShellInstance.Streams.Error)
{
Console.WriteLine(line);
}
return false;
}
else
{
return true;
}
}
}
catch (Exception ex)
{
return false;
}
不断抛出异常:
“AuthorizationManager 检查失败。”
内部异常:提示用户失败的命令,因为 宿主程序或命令 type 不支持用户交互。主机试图 使用以下消息请求确认:仅运行符合以下条件的脚本 你信任。虽然来自 Internet 的脚本很有用,但此脚本 可能会损害您的计算机。如果您信任此脚本,请使用 Unblock-File cmdlet 以允许脚本在没有此警告的情况下运行 信息。是否要运行 C:\PowerShellScripts\MyScript.ps1?
所以查看Exception 我可以看到它要求我确认脚本,但没有供用户交互的窗口,因此出现了异常。
于是我开始研究如何停止确认文本,发现Powershell New-Item: How to Accept Confirmation Automatically
但即使添加:
PowerShellInstance.AddScript("$ConfirmPreference = \"None\"");
PowerShellInstance.Invoke();
在执行我的脚本之前没有工作。那么有没有办法使用C#为我的PowerShell实例设置$ConfirmPreference = "None"?
【问题讨论】:
标签: c# powershell