我在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