powershell - Powershell新人
问题描述
我是powershell的新手,所以如果我的问题听起来很愚蠢,请原谅我。我从 Yuri Posidelov 那里找到了下面的脚本,我对其进行了调整以激活进程并显示窗口并发送击键以关闭运行良好的进程。但是,如果有两个同名的进程,它会失败任何人都可以帮助我解决这个问题。
Yuriy Posidelov 的原始密码
param([string] $proc="SBDDesktop", [string]$adm)
cls
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WinAp {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
}
"@
$p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}
if (($p -eq $null) -and ($adm -ne ""))
{
Start-Process "$proc" -Verb runAs
}
elseif (($p -eq $null) -and ($adm -eq ""))
{
Start-Process "$proc" #-Verb runAs
}
else
{
$h = $p.MainWindowHandle
[void] [WinAp]::SetForegroundWindow($h)
[void] [WinAp]::ShowWindow($h,3);
$wshell = New-Object -ComObject wscript.shell;
#$wshell.SendKeys('~')
$wshell.SendKeys('%fx')
sleep 1
$wshell.SendKeys('N')
}
#|format-table id,name,mainwindowtitle –AutoSize
# static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
# powershell.exe -windowstyle hidden -file *.ps1 -adm "a"
解决方案
问题是,如果它有多个进程,则该行将$p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}
创建一个类型的对象。array
否则它将创建一个类型为 的对象System.ComponentModel.Component
。您可以使用以下方法进行测试:
$p.GetType()
为了弥补这一点,foreach
即使该数组中只有一个元素,您也可以在数组中执行代码过程:
...
[array]$array = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}
foreach ($p in $array){
if (($p -eq $null) -and ($adm -ne ""))
{
Start-Process "$proc" -Verb runAs
}
elseif (($p -eq $null) -and ($adm -eq ""))
{
Start-Process "$proc" #-Verb runAs
}
else
{
$h = $p.MainWindowHandle
[void] [WinAp]::SetForegroundWindow($h)
[void] [WinAp]::ShowWindow($h,3);
$wshell = New-Object -ComObject wscript.shell;
#$wshell.SendKeys('~')
$wshell.SendKeys('%fx')
sleep 1
$wshell.SendKeys('N')
}
#|format-table id,name,mainwindowtitle –AutoSize
# static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
# powershell.exe -windowstyle hidden -file *.ps1 -adm "a"
}
推荐阅读
- excel - Sub 在 VBA 中终止后,无模式的用户窗体会发生什么?
- excel - Excel vba删除Word中的空行
- xml - XSD:如何正确使用从抽象类型派生的类型的元素?
- java - Spring 返回 401 而不是 200 状态
- opengl - 如何运行两个opengl渲染并渲染到一个屏幕
- php - PHP/CodeIgniter 2 - 仅为特定对象调用对象的 __get() 方法
- mysql - 是否有允许我在 MySql 查询中使用星期数的功能?
- html - Kendo-Grid-Column 标题字体大小
- php - Codeigniter 文件没有在我的本地上传。因为它在实时服务器中工作正常
- excel - Excel VBA 代码在组中无法正常工作