對于我經常使用的少數程式,我試圖為我撰寫一些函式或別名,以檢查該程式是否已經在運行并將其視窗置于前臺,否則啟動該程式。
使用示例np, 句柄notepad.exe:
PS> np
檢查是否notepad.exe正在運行 ( Get-Process -Name "notepad.exe") 如果沒有,它將啟動它。當記事本已經在運行但我最大化的控制臺在前臺時,我想再次執行相同的命令,但這次我希望它將已經運行的記事本行程帶到前臺,而不是啟動一個新的行程。
為了實作這一點,我創建了一個名為的類Program,我將為我想像這樣處理的每個程式實體化它。然后我有一個$knownprograms這個類的實體的HashTable ,最后我嘗試為每個程式定義函式,這樣我就可以在控制臺中輸入兩三個字母來啟動程式或將其運行程序帶回前臺。
class Program {
[string]$Name
[string]$Path
[string]$Executable
[string[]]$Arguments
Program(
[string]$n,
[string]$p,
[string]$e,
[string[]]$a
){
$this.Name = $n
$this.Path = $p
$this.Executable = $e
$this.Arguments = $a
}
[string]FullPath(){
return ("{0}\{1}" -f $this.Path, $this.Executable)
}
[void]ShowOrStart(){
try {
# Adapted from https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/bringing-window-in-the-foreground
$Process = Get-Process -Name $this.Name -ErrorAction Stop
Write-Host "Found at least one process called $this.Name"
$sig = '
[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] public static extern int SetForegroundWindow(IntPtr hwnd);
'
$Mode = 4 # Will restore the window, not maximize it
$type = Add-Type -MemberDefinition $sig -Name WindowAPI -PassThru
$hwnd = $process.MainWindowHandle
$null = $type::ShowWindowAsync($hwnd, $Mode)
$null = $type::SetForegroundWindow($hwnd)
} catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
Write-Host "Did not find any process called $this.Name"
Invoke-Command -ScriptBlock { & $this.FullPath() $this.Arguments }
}
}
}
$knownprograms = @{}
$knownprograms.Add("np", [Program]::new(
"np",
"$Env:SystemRoot\System32",
"notepad.exe",
@())
)
$knownprograms.Add("pt", [Program]::new(
"pt",
"$Env:SystemRoot\System32",
"mspaint.exe",
@())
)
Function np {
[cmdletbinding()]
Param()
$knownprograms.np.ShowOrStart()
}
Function pt {
[cmdletbinding()]
Param()
$knownprograms.pt.ShowOrStart()
}
這個想法是我將在我的源代碼中獲取這個腳本profile.ps1,然后只使用預先分解的函式。然而,似乎這段代碼總是打開一個新的程式實體,而不是使用它的運行行程。也許我需要某種延遲的評價,從而使ShowOrStart()在呼叫時方法檢查np或pt是否相關的行程存在。任何想法如何實作這一點?
uj5u.com熱心網友回復:
的行程名稱notepad.exe是notepad。更新
$knownprograms.Add("np", [Program]::new(
"notepad",
"$Env:SystemRoot\System32",
"notepad.exe",
@())
)
這按預期作業。
$sig一次性注冊而不是每次呼叫都可能會很有趣(這可能會引發錯誤)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388245.html
標籤:电源外壳
