VB.NET PowerShell Cmdlet Start-Transcript

时间:2014-01-14 07:29:16

标签: vb.net powershell

我正在编写一个VB.NET PowerShell Cmdlet,需要启动并稍后停止Transcript文件(Start-Transcript)。 那么如何从cmdlet中运行命令 Start-Transcript ?我试过这个:

Dim myRunSpace As Runspace = RunspaceFactory.CreateRunspace()
myRunSpace.Open()
Dim MyPipeline As Pipeline = myRunSpace.CreatePipeline()
MyPipeline.Commands.AddScript("Start-Transcript -Path $pwd\session.txt")
Dim results As Collection(Of PSObject) = MyPipeline.Invoke()
myRunSpace.Close()

产生错误“Start-transcript:此主机不支持transription”。然而,当我手动输入命令时 没有错误产生并且转录开始。

3 个答案:

答案 0 :(得分:0)

Start-Transcript方法是特定于主机的,由主机实现。我猜测,其原因在于不清楚不同主机上可用的输入和输出是什么,因此不容易创建适用于所有情况的通用实现。

PowerShell控制台主机支持Start-Transcript功能(您可以看到,因为它在您调用时可以正常工作),但其他主机需要先实现它才能在该主机中使用。例如,如果您尝试在PowerShell ISE主机中编写Start-Transcript,则会出现如下错误:

Start-Transcript : This host does not support transcription.
At line:1 char:1
+ Start-Transcript
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotImplemented: (:) [Start-Transcript], PSNotSupportedExce 
   ption
    + FullyQualifiedErrorId : NotSupported,Microsoft.PowerShell.Commands.StartTranscript 
   Command

为了使用自定义主机(例如您在VB中创建的主机)使其工作,您必须找到实现转录支持的方法。

答案 1 :(得分:0)

这是cmdlet的限制。 MSFT之所以如此,那么Start-Transcript仅在从powershell.exe控制台调用时才有效,它甚至不能从它们的ISE中运行。解决方法是使用add-content / out-file / tee-object来创建自己的日志文件。

这项工作要多得多,但可以做到。也许这些cmdlet可以提供帮助。

http://www.powertheshell.com/transcript/

答案 2 :(得分:0)

我已经关注了您之前的一个链接,并在那里修补了 PowerShell 脚本中的VB.NET代码:

 Dim thisType As Object = MyBase.Host.GetType().GetProperty("ExternalHost",Reflection.BindingFlags.NonPublic Or BindingFlags.Instance).GetValue(MyBase.Host, New Object() {})
 Dim abc As Object = thisType.GetType().GetProperty("IsTranscribing", Reflection.BindingFlags.NonPublic Or BindingFlags.Instance).GetValue(thisType, New Object() {})
 WriteObject(abc.ToString)

这会正确返回 True False 。那么我可以在这里做更多的事情,比如 Stop-Transcript 吗?对上面的评论表示歉意,但这个链接很慢,文本变得乱码。