如何在Powershell中的-Newname中包含变量

时间:2019-06-30 07:50:13

标签: powershell windows-10 rename-item-cmdlet

通过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++)}

之前:

  • 其他名称-1.mxf
  • 其他名称-4.mxf
  • 其他名称-6.mxf

当前

  • 01 $ Album.mxf
  • 02 $ Album.mxf
  • 03 $ Album.mxf

目标:

  • 01名称类型Loc Month 2019.mxf
  • 02名称类型Loc Month 2019.mxf
  • 03名称类型Loc Month 2019.mxf

3 个答案:

答案 0 :(得分:1)

或者这样(在交互式会话和脚本中都可以工作)。而且您想在$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 }  

答案 1 :(得分:1)

Your own answer是有效的,但在两个方面都很尴尬:

  • 它通过"..."运算符将可扩展字符串-f中的字符串插值)与基于模板的字符串格式混合在一起。 / p>

  • 它使用%ForEach-Object)为每个输入对象启动Rename-Item,这效率很低。

以下是一种可以提供补救措施的解决方案:始终使用-f并使用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 }

请注意使用([ref] $i).Value++来增加$i的值是必要的,因为传递给-NewName的延迟绑定脚本块在子作用域中运行< / em>-有关详细信息,请参见this answer

请注意,$script:i++是一种务实的选择,但不如上述解决方案灵活-请参阅链接的答案。

答案 2 :(得分:0)

在评论中得到@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++)}

之前:

  • 其他名称-1.mxf
  • 其他名称-4.mxf
  • 其他名称-6.mxf

之后:

  • 01名称类型Loc Month 2019.mxf
  • 02名称类型Loc Month 2019.mxf
  • 03名称类型Loc Month 2019.mxf