Niestandardowy interfejs PSHostUserInterface jest ignorowany przez Runspace
Piszę aplikację, która programowo wykonuje skrypty PowerShell. Ta aplikacja ma niestandardowyPSHost
implementacja pozwalająca skryptom na wyprowadzanie instrukcji rejestrowania. Obecnie zachowuję się taktrochę wnioski są prawidłowo przekazywane do mojego zwyczajuPSHost
a inne są zignorowane.
Sprawy stają się jeszcze dziwniejsze, gdy zacząłem sprawdzać$Host
zmienna w moich skryptach, które zdają się sugerować mój zwyczajPSHost
nawet nie jest używany.
Mam kod wykonujący PowerShell w aplikacji .NET:
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);
}
}
Implementacja dlaCustomPsHost
jest bardzo minimalna, zawiera tylko to, co jest potrzebne do przekazaniaPSHostUserInterface
:
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 jest używany jako opakowanie do logowania:
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
}
W moim skrypcie PowerShell próbuję zapisać informacje na hoście:
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
Dlaczego mam dziwne zachowanie z moimCustomPSHostUI
?