我在C#中执行PowerShell脚本代码的地方有一些PowerShell主机。下面的代码来自于AddOIn for Visual Studio中的主机。问题是,如果在PowerShell脚本代码中发生错误,我不知道发生错误的PowerShell脚本文件的文件和行号。从运行空间中的c#调用PowerShell脚本,并获取错误发生的行号
我的托管代码如下所示:
public Exception Execute(string scriptcode, Hashtable variables)
{
Runspace runspace = null;
Pipeline pipeline = null;
PipelineStateInfo info = null;
try
{
// Make our output window active
Logger.ShowOutputWindow();
// Create the runspace and stuff.
runspace = RunspaceFactory.CreateRunspace(host);
pipeline = runspace.CreatePipeline();
runspace.Open();
// Add our scriptcode to the pipeline
pipeline.Commands.Add(new Command(scriptcode, true));
// We don't want to get PSObjects out of the pipeline, output result as string in default way
pipeline.Commands.Add(new Command("Out-Default", true));
// Set up global variables
FillVariables(runspace, variables);
SetUpOutputStreams(pipeline);
// Run the scriptcode
Collection<PSObject> psOutput = pipeline.Invoke();
// Did it complete ok?
info = pipeline.PipelineStateInfo;
if (info.State != PipelineState.Completed)
{
return info.Reason;
}
else
{
return null; // succesful!
}
}
catch (Exception ex)
{
return ex;
}
}
首先,我有我的剧本在脚本代码变量,我现在先写代码到一个临时文件名为.psl这样我就可以在该文件linenumbers报告。但我找不到如何在文件中执行代码,以便在发生错误时可以检索文件名和行号。
任何想法?
关于它的任何解决方案和完整的源代码? – Kiquenet 2012-05-25 08:19:17