【问题标题】:Powershell, Rename a directory after parsing and switching strings of its namePowershell,在解析和切换其名称的字符串后重命名目录
【发布时间】:2018-10-21 06:00:08
【问题描述】:

所以我试图将几个 level1 子文件夹从“xy_1234”重命名为“1234_xy”。到目前为止,我已经将字符串拆分为变量,构建新的目录名并重命名目录,但是在尝试在 for 循环中自动化该过程时,我完全失败了。请帮忙。

Get-Item $Path | ForEach ( $a, $b = $Path.split('_') | Rename-Item -NewName { $b + ('_') + $a})

【问题讨论】:

标签: powershell foreach split get-childitem rename-item-cmdlet


【解决方案1】:
Get-Item $Path | Rename-Item -NewName { 
  $tokens = $_.Name -split '_'         # split the name into tokens
  '{0}_{1}' -f $tokens[1], $tokens[0]  # output with tokens swapped
} -WhatIf

-WhatIf 预览操作。

如您所见,您可以将解析作为传递给Rename-Item-NewName 参数的脚本块的一部分进行。

由于-NewName 只需要项目的文件或目录新的名称(而不是完整路径),$_.Name 被解析并且它的转换是(隐式)输出。

这是一个更简洁的公式,灵感来自LotPings 的提示:

Get-Item $Path | Rename-Item -NewName { -join ($_.Name -split '(_)')[-1, 1, 0] }

这依赖于 PowerShell 通过指定索引的数组(列表) 对数组进行切片的能力:-1, 1, 0 有效地反转了$_.Name -split '(_)' 返回的数组元素 - 请注意(...)围绕_,确保_ 的实例包含在返回的令牌数组中; -join 运算符的一元形式然后连接反转数组的元素。


注意:我假设$Path 包含一个仅匹配感兴趣目录的通配符表达式。

如果您只需要明确匹配目录,请将Get-ChildItem
-Directory 开关一起使用:

Get-ChildItem $Path -Directory

使用通配符模式专门匹配您问题中的示例名称:

Get-ChildItem [a-z][a-z]_[0-9][0-9][0-9][0-9] -Directory

【讨论】:

    【解决方案2】:

    我认为应该使用 GCI 捕获多个子文件夹
    将 "xy_1234" 转换为 "1234_xy" 文字:

    Get-ChildItem $Path -Dir | Where-Object Name -match '^([a-z]+)_(\d+)$' |
        Rename-Item -NewName {$_.Name.Split('_')[1,0] -join ('_')} -WhatIf
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多