[英]How to include variable in -Newname in powershell
通過power-shell腳本,嘗試將$ Album變量添加到命名序列。
嘗試寫入主機,變量正在工作。 嘗試過類似()[] {}“”“之類的東西。 等。
目標是使 $Album
在下面的這一行中工作: {0:D2}$Album.mxf
$i = 1
$Artist = " Name"
$Type = "Type"
$Location = "Loc"
$Month = "Month"
$Year = "2019"
$Album = "$Artist $Type $Location $Month $Year"
# Write-Host -ForegroundColor Green -Object $Album;
Get-ChildItem *.mxf | %{Rename-Item $_ -NewName ('{0:D2}$Album.mxf' -f $i++)}
之前:
當前:
目標:
或者像這樣(在交互式會話和腳本中都可以工作)。 並且您想要$album
之前的空間。
Get-ChildItem *.mxf | Rename-Item -NewName { "{0:D2} $Album.mxf" -f $script:i++ }
編輯:還有另一種方法。 鮮為人知的是foreach-object可以占用3個腳本塊(開始/過程/結束)。 -process可以采用記錄的腳本塊數組。 您始終可以使用-whatif測試這些東西。
Get-ChildItem *.mxf |
foreach { $i = 1 } { Rename-Item $_ -NewName ("{0:D2} $Album.mxf" -f $i++) -whatif }
您自己的答案是有效的,但在兩個方面都很尷尬:
它通過-f
運算符將可擴展字符串 ( "..."
內的字符串插值)與基於模板的字符串格式混合在一起。
它使用%
( ForEach-Object
)為每個輸入對象啟動Rename-Item
,這效率很低。
這是一個解決方案,可以通過始終使用-f
並使用delay-bind腳本塊來提供補救措施:
$Artist = " Name"
$Type = "Type"
$Location = "Loc"
$Month = "Month"
$Year = "2019"
$Album = "$Artist $Type $Location $Month $Year"
$i = 1
Get-ChildItem *.mxf |
Rename-Item -NewName { '{0:D2} {1}.mxf' -f ([ref] $i).Value++, $Album }
注意使用([ref] $i).Value++
來增加$i
的值是必要的,因為傳遞給-NewName
的delay-bind腳本塊在子作用 -NewName
運行-有關詳細信息,請參見此答案 。
請注意, $script:i++
是一種實用的選擇,但比上面的解決方案更不靈活-請參閱鏈接的答案。
回復@Theo的評論
"{0:D2}$Album.mxf"
以便擴展變量$ Album。 $i = 1
$Artist = " Name"
$Type = "Type"
$Location = "Loc"
$Month = "Month"
$Year = "2019"
$Album = "$Artist $Type $Location $Month $Year"
# Write-Host -ForegroundColor Green -Object $Album;
Get-ChildItem *.mxf | %{Rename-Item $_ -NewName ("{0:D2}$Album.mxf" -f $i++)}
之前:
后:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.