Пользовательский PSHostUserInterface игнорируется Runspace
Я пишу приложение, которое программно выполняет сценарии PowerShell. Это приложение имеет кастомPSHost
реализация, позволяющая сценариям выводить операторы журналирования. В настоящее время я наблюдаю такое поведениенесколько запросы правильно перенаправлены на мой заказPSHost
и другие категорически игнорируются.
Все стало еще страннее, когда я начал осматривать$Host
переменная в моих сценариях, которые, кажется, предполагают, что мой обычайPSHost
даже не используется.
У меня есть код, который выполняет PowerShell в приложении .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);
}
}
Реализация для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
?