如何在 PowerShell 中使用 Array Splatting?

Splatting 是将参数集合作为单个单元传递的方法,因此命令更易于阅读。数组 splatting 使用不需要参数名称的 splat 值。这些值必须按数组中的位置编号顺序排列。

我们有一个下面的复制示例,其中我们将一个文件从源复制到目标。现在我们不在这里指定参数,因为我们将使用源路径和目标路径的位置参数。

如果我们查看这些参数的帮助,我们就会知道它们的位置。

对于源路径。

help Copy-Item -Parameter path
输出结果
-Path <System.String[]>
Specifies, as a string array, the path to the items to copy. Wildcard characters are permitted.
Required?                      true
Position?                      0
Default value                  None
Accept pipeline input?         True(ByPropertyName, ByValue)
Accept wildcard characters?    true

如果您检查 Path 参数位置为 0,则我们可以提供值而无需首先指定参数。同样,Destination 参数位置是第二个,如下所示。

PS C:\> help Copy-Item -Parameter
Destination -Destination <System.String>
Specifies the path to the new location. The default is the current directory.
To rename the item being copied, specify a new name in the value of the Destination parameter.
Required?                       false
Position?                       1
Default value Current directory Accept pipeline input?       True (ByPropertyName)
Accept wildcard characters?     false

所以我们可以直接使用命令,

Copy-Item C:\Temp\10vms.csv 11vms.csv -Verbose

现在要生成数组值,我们可以将这些值组合到数组中,然后传递给 Copy-Item 命令。

PS C:\> $items = "C:\Temp\10vms.csv","11vms.csv"
PS C:\> Copy-Item @items -Verbose

同样,如果参数位置在 2 号,则可以在逗号后添加它,依此类推。