コンソールから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();
}
PowerShellのスクリプトすなわちTest1.ps1
ここsleep 3
$a=""
$a = "Hello word"
return $a
ps1の文字列 "Hello world"を変更してC#アプリケーションを再実行しますか? – wp78de