背景
PowerShell スクリプトをプログラムで実行するアプリケーションを作成しています。PSHost
このアプリケーションには、スクリプトがログ ステートメントを出力できるようにするためのカスタム実装があります。現在、私が見ている動作は、一部のリクエストがカスタムに適切に転送され、PSHost
他のリクエストは完全に無視されるというものです。
スクリプトで変数を調べ始めたとき、状況はさらに奇妙になりました$Host
。これは、私のカスタムが使用されていないことを示唆しているようですPSHost
。
コード
.NET アプリケーション内で PowerShell を実行するコードがいくつかあります。
var state = InitialSessionState.CreateDefault();
state.AuthorizationManager = new AuthorizationManager("dummy"); // Disable execution policy
var host = new CustomPsHost(new CustomPsHostUI());
using (var runspace = RunspaceFactory.CreateRunspace(host, state))
{
runspace.Open();
using (var powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
var command = new Command(filepath);
powershell.Invoke(command);
}
}
の実装CustomPsHost
は非常に最小限で、転送に必要なものだけが含まれていPSHostUserInterface
ます。
public class CustomPsHost : PSHost
{
private readonly PSHostUserInterface _hostUserInterface;
public CustomPsHost(PSHostUserInterface hostUserInterface)
{
_hostUserInterface = hostUserInterface;
}
public override PSHostUserInterface UI
{
get { return _hostUserInterface; }
}
// Methods omitted for brevity
}
CustomPsHostUI は、ロギングのラッパーとして使用されます。
public class CustomPsHostUI : PSHostUserInterface
{
public override void Write(string value) { Debug.WriteLine(value); }
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value){ Debug.WriteLine(value); }
public override void WriteLine(string value) { Debug.WriteLine(value); }
public override void WriteErrorLine(string value) { Debug.WriteLinevalue); }
public override void WriteDebugLine(string message) { Debug.WriteLine(message); }
public override void WriteProgress(long sourceId, ProgressRecord record) {}
public override void WriteVerboseLine(string message) { Debug.WriteLine(message); }
// Other methods omitted for brevity
}
私の PowerShell スクリプトでは、ホストに情報を書き込もうとしています。
Write-Warning "This gets outputted to my CustomPSHostUI"
Write-Host "This does not get outputted to the CustomPSHostUI"
Write-Warning $Host.GetType().FullName # Says System.Management.Automation.Internal.Host.InternalHost
Write-Warning $Host.UI.GetType().FullName # Says System.Management.Automation.Internal.Host.InternalHostUserInterface
で奇妙な動作が発生するのはなぜCustomPSHostUI
ですか?