【问题标题】:powershell rename-item replace with variables incrementingpowershell rename-item 替换为变量递增
【发布时间】:2017-01-12 07:50:14
【问题描述】:

我正在尝试使用 Get-Childitem | Where-Object 的输出来重命名一组文件,但我不想用常量名重命名我想用一组变量重命名,我正在使用运算符 -replace找到字符串中我想要更改的位置。示例:

nane_01 -> name_23
name_02 -> name_24  they are not with the same final digit

这是我用于测试的代码:

$a = 0
$b = 1
$Na= 2
$Nb= 3
Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname { $_.name  -replace "_{0}{1}","_{2}{3}" -f $a++,$b++,$Na++,$Nb++ } -Whatif

我找不到如何使用 -replace 运算符使增量变量工作

【问题讨论】:

  • 明确指定范围:$script:a 等等。
  • 这行得通,因为我现在没有得到错误,但增量的结果不起作用,比如变量 a=0 和 na = 0,所以它们不会更改名称。你能指出我有什么问题吗?抱歉,我是使用 Powershell 的新手

标签: powershell variables replace rename-item-cmdlet


【解决方案1】:
  1. 明确指定变量的范围,否则每次调用重命名脚本块时都会丢弃本地副本。

  2. -replace 运算符的搜索/替换字符串是单独的参数,因此请使用括号将它们分别格式化(否则 PowerShell 将尝试将 -f 应用于 $_.name)。

    李>

$script:a = 0
$script:b = 1
$script:Na= 2
$script:Nb= 3

Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname {
    $_.name -replace ("_{0}{1}" -f $script:a++,$script:b++),
                     ("_{0}{1}" -f $script:Na++,$script:Nb++)
} -Whatif

或者只使用一个变量:

$script:n = 0

Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname {
    $_.name -replace ("_{0}{1}" -f $script:n++,$script:n++),
                     ("_{0}{1}" -f $script:n++,$script:n++)
} -Whatif

【讨论】:

  • 感谢您的快速响应,但此代码仅适用于第一个文件名,其他代码继续为我输入相同的名称。
  • 嗯,当然。您需要反向枚举文件。或者将结果移动到另一个文件夹。
  • 非常感谢您的帮助,我刚刚在上一个问题上犯了一个新手错误,但是您的帮助解决了我的疑问。
猜你喜欢
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多