首页 > 解决方案 > 有没有办法在即时窗口中直接通过代码编写命令?

问题描述

我正在尝试将输出窗口中的所有行保存到日志文件中。当我将命令直接输入到即时窗口时,效果很好。但是,我需要一种通过代码输入命令行的方法。

我搜索了一种在即时窗口中输入命令的方法,以便创建我想要的日志文件并用数据填充。这没有发生,我不知道这是否可能。到目前为止,搜索 Google 并没有帮助。

我的命令行是:

> Tools.LogCommandWindowOutput C:\Users\user\AppData\test.log

我尝试通过

Debug.Print("> Tools.LogCommandWindowOutput C:\Users\user\AppData\test.log")

将命令行直接放入即时窗口时(通过键入或粘贴)可以正常工作。当我尝试通过代码执行此操作时,什么也没有发生。有没有办法做到这一点,或者我必须尝试另一种选择,如果是这样,它是什么选择?

编辑:我尝试了 RobertBaron 提供的解决方案,并进行了以下更改:

'Dim dummy = $"C:\\log\\outputfileAddOn_{Date.Now:yyyy_MM_dd_HH_mm_ss}.log"
'cmdWindow.SendInput($"Tools.LogCommandWindowOutput {dummy}", True)
cmdWindow.SendInput("Tools.LogCommandWindowOutput C:\log\outputfile_AddOn.log", True)

(我希望每次都写入一个新文件,所以我尝试在末尾添加日期以具有唯一的文件名)它创建文件但不记录任何内容。我做错了什么?

我发现的另一个解决方案是在 project-properties-debug-command 参数中添加一个命令参数:

> C:\log\outputfile.log

这将创建文件并插入输出窗口中的所有数据。我现在唯一的问题是每次启动程序时都会覆盖这个文件。有没有办法可以从文件末尾的第二个、第三个……开始设置日志记录?(在命令参数末尾添加 /on 没有帮助)或者我可以提供类似“outputfile_yyyy_MM_dd_HH_mm_ss.log”的内容(例如:outputfile_2019_07_23_15_47_45.log)?

谢谢您的帮助!

标签: vb.net

解决方案


您需要创建一个 Visual Studio 扩展项目。

在此处输入图像描述

将新的自定义命令项添加到 VSIX 项目。

在此处输入图像描述

这将创建Command1.vb. 这是您实现要在 Visual Studio 中执行的代码的地方。Invoke Command1每当您从Tools菜单中选择条目时,代码就会执行。

Command1.vb文件的底部,有Execute() Sub. 它显示一条消息只是为了表明该命令正在运行。您最终可以删除它。但是现在,只需运行该项目。Visual Studio 的另一个实例将启动。这是您可以测试和调试代码的地方。启动 Visual Studio 的第二个实例后,转到其Tools菜单,然后选择Invoke Command1条目。将显示一个消息框。停止执行。

现在我们要修改 ,Execute() Sub以便我们的代码在Invoke Command1被选中时执行。这是Sub将执行您想要的命令的。将其添加到Command1班级。

Public Sub ExecCommandWindow()
    Dim dte As EnvDTE.DTE = CType(Microsoft.VisualStudio.Shell.Package.GetGlobalService(GetType(Microsoft.VisualStudio.Shell.Interop.SDTE)), EnvDTE.DTE)
    Dim cmdWindow As CommandWindow = CType(dte.Windows.Item(EnvDTE.Constants.vsWindowKindCommandWindow).Object, CommandWindow)
    'Display some text in the command window
    cmdWindow.OutputString("Executing command from the automation OM...")
    'Send some command strings to the command window and execute them...
    'This command will start logging all input/output in the command window to the specified file
    cmdWindow.SendInput("Tools.LogCommandWindowOutput cmdwindow.log", True)

    ''Open a file in a code editor:
    ''  1. We use an alias, 'of', for the File.OpenFile command
    ''  2. This command takes quote-delimited parameters (in this case,
    ''     the name of the editor to load the file in)
    'Dim cmd As String = "of "
    'cmd = (cmd + """""C:\Contoso\ContosoCommonFramework\Integration.cs""""")
    'cmd = (cmd + "/e:""""CSharp Editor""""")
    'cmdWindow.SendInput(cmd, True)
    'cmdWindow.SendInput("Edit.Find MessageTrxId", True)

    'Turn off logging
    cmdWindow.SendInput("Tools.LogCommandWindowOutput /off", True)
End Sub

更改Execute() Sub为调用ExecCommandWindow()

您可以通过更改其在Command1类中的标题来更改命令的名称。

每个用户都需要安装 Visual Studio 扩展。只需分发.vsix文件。要安装,请双击它。


推荐阅读