如何在 PowerShell 中使用陣列展平?


展平是一種將引數集合作為一個單元傳遞的方式,這樣命令更容易讀取。陣列展平使用不需要引數名稱的展開值。這些值在陣列中必須按位置編號順序排列。

我們有一個下面的複製示例,其中我們正在將一個檔案從源複製到目標。現在我們在這裡不指定引數,因為我們將對源路徑和目標路徑使用位置引數。

如果我們檢視這些引數的幫助,我們將瞭解它們的位置。

對於源路徑。

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

如果你檢視路徑引數的位置是 0,因此我們可以提供值而不首先指定。類似地,目標引數的位置是第二個,如下所示。

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 個編號的位置有引數,則可以在逗號後新增它,依此類推。

更新時間: 18 年 1 月 2021 日

579 次檢視

開始你的 職業

完成課程以獲得認證

開始
廣告