首页 > 解决方案 > 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"

标签: powershellsendkeysshowwindowsetforegroundwindow

解决方案


问题是,如果它有多个进程,则该行将$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"

}

推荐阅读