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

How I can pass multiple array in value in PowerShell function

下面的函数我想传递数组中的多个值。当我传递多个值时出现错误。

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

试试这个:

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" 你得到流程了吗?