Via power-shell script, trying to add $Album variable to naming sequence.
Tried write host, variable is working. Have tried things like () [] {} "" '' . ect.
The goal is to get $Album
to work in this line below: {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++)}
Before:
Current:
Goal:
Your own answer is effective, but it is awkward in two respects:
It mixes expandable strings (string interpolation inside "..."
) with template-based string formatting via the -f
operator.
It uses %
(ForEach-Object
) to launch Rename-Item
for every input object, which is quite inefficient.
Here's a solution that provides a remedy, by using -f
consistently and by using a delay-bind script block:
$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 }
Note the use of ([ref] $i).Value++
to increment the value of $i
, which is necessary, because the delay-bind script block passed to -NewName
runs in a child scope - see this answer for details.
Note that $script:i++
is a pragmatic alternative, but less flexible than the solution above - see the linked answer.