好奇如何循环遍历每个值都是数组的哈希表。例:

 $test = @{
 a = "a","1";
 b = "b","2";
 c = "c","3";
 }

然后我想做些类似的事情:
foreach ($T in $test) {
write-output $T
}

预期结果将是这样的:
name value
a    a
b    b
c    c
a    1
b    2
c    3

这不是当前发生的情况,我的用例是基本上在循环中将参数的哈希传递给函数。我的方法可能全都错了,但是我想问一问,看看是否有人试图这样做?

编辑**
多一点澄清。我基本上想做的是将大量数组值传递给函数,并在传递给嵌套函数之前遍历哈希表中的值。例:

首先是这样的:
$parameters = import-csv .\NewComputers.csv

然后像
 $parameters | New-LabVM

实验室虚拟机代码如下:
function New-LabVM
{

[CmdletBinding()]
Param (
    # Param1 help description
    [Parameter(Mandatory=$true,
               Position=0,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true)]
    [Alias("p1")]
    [string[]]$ServerName,

    # Param2 help description
    [Parameter(Position = 1)]
    [int[]]$RAM = 2GB,

    # Param3 help description
    [Parameter(Position=2)]
    [int[]]$ServerHardDriveSize = 40gb,

    # Parameter help description
    [Parameter(Position=3)]
    [int[]]$VMRootPath = "D:\VirtualMachines",
    [Parameter(Position=4)]
    [int[]]$NetworkSwitch = "VM Switch 1",
    [Parameter(Position=4)]
    [int[]]$ISO = "D:\ISO\Win2k12.ISO"
  )

 process
 {
 New-Item -Path $VMRootPath\$ServerName -ItemType Directory
 $Arguments = @{
 Name = $ServerName;
 MemoryStartupBytes = $RAM;
 NewVHDPath = "$VMRootPath\$ServerName\$ServerName.vhdx";
 NewVHDSizeBytes = $ServerHardDriveSize
 SwitchName = $NetworkSwitch;}

foreach ($Argument in $Arguments){
    # Create Virtual Machines
New-VM @Arguments

# Configure Virtual Machines
Set-VMDvdDrive -VMName $ServerName -Path $ISO
Start-VM $ServerName
}
# Create Virtual Machines
New-VM @Arguments
 }
}

最佳答案

您正在寻找的是parameter splatting

最强大的方法是通过哈希表,因此必须将Import-Csv输出的自定义对象实例转换为哈希表:

Import-Csv .\NewComputers.csv | ForEach-Object {
   # Convert the custom object at hand to a hashtable.
   $htParams = @{}
   $_.psobject.properties | ForEach-Object { $htParams[$_.Name] = $_.Value }

   # Pass the hashtable via splatting (@) to the target function.
   New-LabVM @htParams
}

请注意,由于通过splatting进行的参数绑定(bind)是基于键的(哈希表键与参数名称匹配),因此可以使用具有不可预测键顺序的常规哈希表(在这种情况下,无需有序哈希表([ordered] @{ ... })) 。

关于powershell - 如何遍历哈希表中的数组-基于从CSV文件读取的值传递参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45364204/

10-11 22:54
查看更多