我使用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();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6279 次 |
最近记录: |