如何在PowerShell函数中传递值的多个数组

时间:2019-02-22 10:38:21

标签: powershell powershell-v3.0

下面的功能,我想在数组中传递多个值。当我传递多个值时,我得到一个错误。

function CheckProcess([String[]]$sEnterComputerNameHere, [String[]]$sEnterProccessNameHere) {
    #Write-Host " $sEnterComputerNameHere hello"

    @($sEnterComputerNameHere) | ForEach-Object {
        # Calling Aarray
        @($sEnterProccessNameHere) | ForEach-Object {
            if (Get-Process -ComputerName $sEnterComputerNameHere | where {$_.ProcessName -eq $sEnterProccessNameHere}) {
                Write-Output "$_ is running"
            } else {
                Write-Output "$_ is not running"
            }
        }
    }
}

$script:sEnterProccessNameHere = @("VPNUI")     # Pass the process agreement here
$script:sEnterComputerNameHere = @("hostname")  # Pass the process agreement here

CheckProcess $sEnterComputerNameHere $sEnterProccessNameHere

1 个答案:

答案 0 :(得分:0)

尝试一下:

Function CheckProcess([String[]]$sEnterComputerNameHere,[String[]]$sEnterProccessNameHere) 
{ #Write-host " $sEnterComputerNameHere"

    @($sEnterComputerNameHere) | Foreach-Object {
        $computer = $_
        Write-Host $computer        
        @($sEnterProccessNameHere) | Foreach-Object {
            $process = $_
            Write-Host $process
            try{
                $x = get-process -computername $computer #Save all processes in a variable
                If ($x.ProcessName -contains $process) #use contains instead of equals
                {
                    Write-Output "$process is running"
                }
                else
                {
                    Write-Output "$process is not running"
                }
            }
            catch
            {
                Write-Host "Computer $computer not found" -ForegroundColor Yellow
            }
        }
    }
}

$script:sEnterProccessNameHere = @("VPNUI","Notepad++","SMSS") 
$script:sEnterComputerNameHere = @("remotecomputer1","remotecomputer2") 

CheckProcess -sEnterComputerNameHere $sEnterComputerNameHere -sEnterProccessNameHere $sEnterProccessNameHere

通常,如果您写下问题中的错误,那就太好了。那可以帮助其他人帮助您。

如果我使用数组和| Foreach,我总是将$_写入新变量。如果我还有另一个| Foreach(和您一样)知道要与哪个对象一起使用,那将很有帮助。

编辑:我更改了脚本,因此它使用“ -contains”而不是“ -eq”,并且添加了一个try / catch块,因此,如果未找到另一台计算机,它将给您消息。在我的网络上
EDIT2:您可以访问其他计算机吗?如果您运行get-process -computername "name of remote computer",您是否得到了这些程序?