当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 跟踪窗口的更多乐趣

作者:精品下载站 日期:2024-12-14 07:40:24 浏览:15 分类:玩电脑

PowerShell 跟踪窗口的更多乐趣


在我上周五的欢乐时光中,我发布了一篇有关使用 Internet Explorer 作为跟踪窗口的文章。这个想法是将调试或跟踪消息放在单独的应用程序中。我收到了对该帖子的评论,建议我可以使用 Sysinternals 的调试视图实用程序做类似的事情。这个应用程序用于捕获调试消息,所以我想尝试一下。

下载后,您将手动运行一次以接受许可条款并设置过滤器。我假设您不经常将此程序用于其他用途。根据您的计算机,您可能不需要过滤器,但这是使用我的调试消息功能的最佳方式。

#requires -version 2.0

<#
 Requires dbgview.exe from Sysinternals to be in your path or 
 modify the function. You should set up a filter in dbview.exe
 before using this to filter on the Category.
#>

Function Debug-Message {

[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a message")]
[string]$Message,
[string]$Category="PS Trace"
)

#only run if $TraceEnabled is True
if ($script:TraceEnabled) {
    #test if dbgview.exe is already running and start it if not.
    if (-NOT (Get-Process -Name Dbgview -ErrorAction SilentlyContinue)) {
      Try {
        #start with /f to skip filter confirmation prompt
        Start-Process G:\Sysinternals\Dbgview.exe /f
        #give the application to start
        Start-Sleep -Seconds 1
      }
      Catch {
        Write-Warning "Failed to find or start dbgview.exe"
        Return
      }
    } #if dbgview is not running

    #display the message in dbgview.exe
    [System.Diagnostics.Debug]::WriteLine($Message,$Category)

} #if $TraceEnabled

} #close Debug-Message

Set-Alias -Name Trace -Value Debug-Message

该函数的本质是 [System.Diagnostics.Debug]::WriteLine($Message,$Category) 行。类别将显示为调试视图窗口中消息的前缀。我在调试视图中对该类别设置了一个过滤器,即 PS Trace*。该函数与我的 IE 跟踪函数一样,依赖于将变量 $TraceEnabled 设置为 $True。如果 dbgview.exe 进程未运行,该函数将启动它。我已经硬编码了 dbgview.exe 的路径,您需要对其进行调整。最简单的方法是将 dbgview.exe 放入 Windows 文件夹或修改 %PATH% 变量以包含 Sysinternals 文件夹。

使用该功能和我的IE版本没有什么不同。事实上,在我的演示脚本中,我所需要做的就是更改哪个脚本获取点源。

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
# dot source the Trace function
#. C:\scripts\Trace.ps1
. C:\scripts\Debug-Message.ps1
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#>
if ($Trace) {
  #set the variable to turn tracing on
  $script:TraceEnabled = $True
}

我在新的调试视图函数中添加了“Trace”别名,因此无需更改任何其他内容。当我使用 -Trace 参数运行脚本时,我会得到一个像这样的方便的跟踪窗口。

[玩转系统] PowerShell 跟踪窗口的更多乐趣

该实用程序的便利之处在于可以轻松地将结果保存到文件中。我也不必处理混乱的 COM 对象。如果您没有提前设置过滤器,您可能很难从脚本中找到跟踪消息。但这是你的选择。

你怎么认为?

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯