【问题标题】:Complex variable string in PowerShellPowerShell 中的复杂变量字符串
【发布时间】:2017-10-10 11:39:14
【问题描述】:

所以我在一个文件夹中有数百个文件:

文件总是First_Last (MMM yyyy):

C:\Test\Bob_Johnson (May 2017).pdf
C:\Test\James_Smith (Apr 2017).pdf

它们会根据文件名移动到各个文件夹(我想我知道如何移动文件)。这些文件夹被命名为Last, First 00-0000,其中零是案例编号。

以下脚本将从文件名中删除(MMM yyyy)

Get-ChildItem -Path C:\Test | ?{ ($_.PsIsContainer)} | %{
    $File = ($_.name.substring(0,$_.basename.length-11))
    Write-Host $File
}

输出:

Bob_Johnson
James_Smith

太好了。但它必须是“Last, First”。

Get-ChildItem -Path C:\Test | ?{!($_.PsIsContainer)} | %{
    $File = ($_.BaseName -split '_')[1] + ", " + ($_.BaseName -split '_')[0]
    Write-Host $File
}

输出:

Johnson (May 2017), Bob
Smith (Apr 2017), James

所以这是我的问题:我如何组合子字符串和拆分,以便修剪最后 11 个字符用“,”重新排列名字和姓氏“介于两者之间?

所需的输出:

Johnson, Bob
Smith, James

【问题讨论】:

    标签: powershell variables split substring


    【解决方案1】:

    这里是使用 regex 的解决方案:

    Get-ChildItem -Path C:\Test | ?{!($_.PsIsContainer)} | %{
        $regexMatch = [regex]::Match($_.BaseName, '(\w+)_(\w+)\s+\((\w+)\s+(\d+)')
        $File = '{0}, {1} {2}-{3}' -f $regexMatch.Groups[1].Value, $regexMatch.Groups[2].Value, $regexMatch.Groups[3].Value, $regexMatch.Groups[4].Value
        Write-Host $File
    }
    

    输出:

    Bob, Johnson May-2017
    

    【讨论】:

      【解决方案2】:

      这不是最优雅的解决方案,但我认为你可以这样做:

      Get-ChildItem -Path C:\Test | ?{ ($_.PsIsContainer)} | %{
          $File = ($_.name.substring(0,$_.basename.length-11))
          $File = ($File -split '_')[1] + ", " + ($File -split '_')[0]
          Write-Host $File
      }
      

      【讨论】:

      • 哇。如此简单,却又如此难以捉摸。我尝试了很多变体,包括与此类似的变体。但我认为不是在它拆分的第二个变量声明中,我放了“$_.BaseName -split”而不是“$File -split”。这似乎与我的代码完美配合,一切都被移到了正确的文件夹中。谢谢!
      猜你喜欢
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 2021-12-11
      • 2022-10-07
      • 2013-05-27
      相关资源
      最近更新 更多