我尝试从c#运行powershell
脚本。
首先,我将ExecutionPolicy
设置为Unrestricted
,脚本现在从PowerShell ISE
运行。
这是我的c#代码:
class Program
{
private static PowerShell ps;
static void Main(string[] args)
{
ps = PowerShell.Create();
string ps1File = Path.Combine(Environment.CurrentDirectory, "script.ps1");
ExecuteScript(ps1File);
Console.ReadLine();
}
static void ExecuteScript(string script)
{
try
{
ps.AddScript(script);
Collection<PSObject> results = ps.Invoke();
Console.WriteLine("Output:");
foreach (var psObject in results)
{
Console.WriteLine(psObject);
}
Console.WriteLine("Non-terminating errors:");
foreach (ErrorRecord err in ps.Streams.Error)
{
Console.WriteLine(err.ToString());
}
}
catch (RuntimeException ex)
{
Console.WriteLine("Terminating error:");
Console.WriteLine(ex.Message);
}
}
}
输出为:
ps1不能加载,因为运行脚本在此禁用 系统。要了解更多信息,请参阅about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170 . < / p >