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

在树下

通过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
mklement0

您自己的答案是有效的,但在两个方面都很尴尬:

  • 它将可扩展字符串(内部的字符串插值"...")与通过操作符的基于模板的字符串格式混合在一起-f

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

这是一种解决方案,可以通过-f一致地使用延迟绑定脚本块来提供补救措施

$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,这是必要的,因为传递给delay-bind脚本块-NewName子作用域中运行-有关详细信息,请参见此答案

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章