我正在使用 Process.Start() 从 C# 调用 Powershell 脚本。如何捕获 C# 代码中 Powershell 脚本引发的异常?
最佳答案
在 C# 中托管 PowerShell 引擎非常简单。这段代码使用了有点过时的 API,但它仍然有效,并让您了解所涉及的内容:
string cmd = @"Get-ChildItem $home\Documents -recurse | " +
"Where {!$_.PSIsContainer -and ($_.LastWriteTime -gt (Get-Date).AddDays(-7))} | " +
"Sort Fullname | Foreach {$_.Fullname}";
Runspace runspace = null;
Pipeline pipeline = null;
try
{
runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmd);
Collection<PSObject> results = pipeline.Invoke();
foreach (PSObject obj in results)
{
// Consume the results
Debug.WriteLine(obj);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
if (pipeline != null) pipeline.Dispose();
if (runspace != null) runspace.Dispose();
}
关于c# - 从 C# 调用 Powershell 并处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7917873/