【发布时间】:2013-10-10 10:25:06
【问题描述】:
背景
我正在编写一个以编程方式执行 PowerShell 脚本的应用程序。此应用程序有一个自定义的PSHost 实现,以允许脚本输出日志记录语句。目前,我看到的行为是 some 请求被正确转发到我的自定义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 会出现奇怪的行为?
【问题讨论】:
-
你在实现 RawUI 属性吗?我有一个 PSCustomHost 我为一个有效的 Make-PS1ExeWrapper 实用程序实现。你可以在这里查看:skydrive.live.com/…
-
对于
RawUI上的Microsoft's documentation,我不需要它:If you are also implementing a PSHostRawUserInterface class, return an instance of the class.
标签: c# powershell runspace