问题描述
我需要在窗口计算机中使用应用程序名称跟踪前台应用程序。我正在使用给定的代码,但它提供的是ProcessName而不是应用程序名称示例ProcessName是“ chrome”,复制名称是“ Google Chrome”。我得到的应用程序名称不明确,或者我可以将应用程序名称与进程名称映射。请帮助我
[CmdletBinding()]
Param(
)
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class UserWindows {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"@
try{
$ActiveHandle = [UserWindows]::GetForegroundWindow()
$Process = Get-Process | ? {$_.MainWindowHandle -eq $activeHandle}
$Process | Select ProcessName,@{Name="AppTitle";Expression= {($_.MainWindowTitle)}}
}catch{
Write-Error "Failed to get active Window details. More info:$_"
}
解决方法
而不是给您答案(因为您可能还会有更多问题),我将教您自己钓鱼。
让我们说您有一个变量,并且想要查看可以从中获得的所有属性;运行$variable |get-member
现在,您看到有许多附加到变量的属性,并且看不到任何称为“应用程序名称”的属性。因此,让我们列出该变量的所有属性,看看是什么赋予我们我们所寻找的价值。
对于我的示例,我将抓取chrome放入我的变量中,因此我们位于同一页上。
这是我用来获取变量以匹配您要使用的变量的代码(如果您已经拥有要使用的变量,请忽略此操作)。
$variable= Get-Process|? name -ilike chrome|select -first 1
让我们列出所有属性
$variable|format-list *
现在,我们看到有2个属性,列出了要查找的名称,描述和产品(对于chrome来说都可以,但是我不知道哪个可以用于您的其他用例,可能没有)。让我们抓住Product并将其用于您的代码,在select语句(用于选择要在该变量中保留/显示哪些属性的语句)中将processname替换为Product属性...现在,您知道如何进行更改,可以根据需要进行更改=)
[CmdletBinding()]
Param(
)
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class UserWindows {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"@
try{
$ActiveHandle = [UserWindows]::GetForegroundWindow()
$Process = Get-Process | ? {$_.MainWindowHandle -eq $activeHandle}
$Process | Select Product,@{Name="AppTitle";Expression= {($_.MainWindowTitle)}}
}catch{
Write-Error "Failed to get active Window details. More info:$_"
}