[英]Set window title when running "start powershell" in powershell not working?
[英]Powershell - Get current Active Window title and set it as a string
我想獲取我的活動窗口的 processName 和 MainWindowTitle,然后將其設置為字符串變量,以便我以后可以使用它,例如在文件命名中。
我的代碼確實有效,但是
(1) 無法顯示$screenTitle
(2) 有一些 MainWindowTitle 為空的實例,但即使我刪除了 $processNaming 也不會繼續執行 If 條件。
我在這里錯過了什么?
$code = @'
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern Int32 GetWindowThreadProcessId(IntPtr hWnd,out
Int32 lpdwProcessId);
'@
Add-Type $code -Name Utils -Namespace Win32
$myPid = [IntPtr]::Zero;
Do{
$hwnd = [Win32.Utils]::GetForegroundWindow()
$null = [Win32.Utils]::GetWindowThreadProcessId($hwnd, [ref] $myPid)
$processNaming = Get-Process | Where-Object ID -eq $myPid | Select-Object processName
#$processNaming
$screenTitle = Get-Process | Where-Object ID -eq $myPid | Select-Object MainWindowTitle
If($screenTitle -ne $Null){
$processNaming
$screenTitle
}
Else {
Write-Host "No Screen Title"
}
Start-Sleep -Milliseconds 3000
}While($True)
您的代碼未顯示$screenTitle
的問題是由於 PowerShell 如何在控制台中顯示對象,目前您正在嘗試輸出2 個具有不同屬性ProcessName
和MainWindowTitle
的對象,但只顯示一個(第一個)。 請參閱這些答案以了解發生這些情況的原因:
為了克服這個問題,您應該做的是返回一個具有 2 個屬性的對象,這樣您應該會看到它們正確顯示。
$myPid = [IntPtr]::Zero;
Do {
$hwnd = [Win32.Utils]::GetForegroundWindow()
$null = [Win32.Utils]::GetWindowThreadProcessId($hwnd, [ref] $myPid)
$process = Get-Process -Id $myPid
If($process.MainWindowTitle) {
$process | Select-Object ProcessName, MainWindowTitle
}
else {
Write-Host ("No Screen Title for '{0}'" -f $process.ProcessName)
}
Start-Sleep -Seconds 1
} While($True)
如果你想從你的循環中輸出字符串而不是一個對象,你可以這樣做:
'ProcessName: {0} - MainWindowTitle: {1}' -f $process.ProcessName, $process.MainWindowTitle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.