나는 콘솔에서 powershell 스크립트를 호출 한 콘솔 응용 프로그램을 작성했습니다. PowerShell 스크립트에서 hello world를 반환 변수로 작성했으며 예상대로 실행하지만 다음 번에 hello world에서 문자열을 변경하면 어떻게 변경된 문자열이 표시되지 않습니까? 파이프 라인이나 캐시를 지우려면 어떻게해야하는지 스스로 알 수는 없습니다. 나는 기본 네임 스페이스에서 떨어져.Net 콘솔 응용 프로그램에서 powershell 호출
using System.Management;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
static void Main(string[] args)
{
string _str = string.Empty;
_str= RunScript(@"C:\Powershell_Scripts\Test.ps1");
Console.WriteLine("Input String is =" + str);
Console.Read();
}
private static string RunScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script
// output objects into nicely formatted strings
// remove this line to get the actual objects
// that the script returns. For example, the script
// "Get-Process" returns a collection
// of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
Collection <PSObject> results = pipeline.Invoke();
pipeline.Streams.ClearStreams();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
파워 쉘 스크립트, 즉 Test1.ps1
다음sleep 3
$a=""
$a = "Hello word"
return $a
그래서 ps1에서 "Hello world"문자열을 변경하고 C# 응용 프로그램을 다시 실행하십시오. – wp78de