Powershell 脚本 : combine two array in execution command

标签 powershell

在 Powershell 方面仍然非常缺乏经验,但众所周知,每一次旅程都从第一步开始。

我在脚本中定义了两个数组:

$array1 = @("server1", "server2")
$array2 = @("SID1", "SID2")

SID1 和 server1 属于同一类。

然后我想使用循环组合两个数组: 示例:

foreach ($i in $array1) {
Write-Host "Server = ${i}"
}

如何合并这两个数组? 理想是: ...

Write-Host "Server=${i}" and SID=${?}"

...

是否可以将这两个数组构建到foreach中,以便在写入主机上执行时填充两个值?

感谢您的想法和帮助。

许多问候

卡洛斯

最佳答案

另一种方法是使用 [System.Linq.Enumerable]::Zip它提供了方便的 API(如 python zip 函数)。即,你可以做

$array1 = @("server1", "server2")
$array2 = @("SID1", "SID2")


$doSomethingWithPair = {
    param($a, $b)

    Write-Output "I have $a and $b"
}

[System.Linq.Enumerable]::Zip(
  $array1, 
  $array2, 
  [Func[Object, Object, Object]]$doSomethingWithPair
)

这将打印

I have server1 and SID1
I have server2 and SID2

关于Powershell 脚本 : combine two array in execution command,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73459906/

相关文章:

powershell - 使用 ConvertTo-HTML 将 URL 列表转换为可点击的 HTML 链接

powershell - 使用 "CON"作为文件名

azure - 用于列出 Azure 订阅下虚拟机上次重新启动的 Powershell 脚本

Powershell:导出 csv 文件中的 System.Object[]

powershell - Powershell将对象数组转换为PSCustomObject

xml - Powershell根据子节点值选择父xml节点并添加子元素

c# - PowerShell 与 MongoDB C# 驱动程序的方法不兼容?

powershell - 我正在尝试创建一个新文件,并根据输入参数send将内容添加到新文件中

powershell - 为什么这个函数返回 ''而不是连接字符串

powershell - 使用 PowerShell 从每组中选择前 5 个项目