powershell - PowerShell 中的复杂变量字符串

标签 powershell variables split substring

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

文件始终是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
太棒了。但它需要是“最后,第一个”。

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

最佳答案

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

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

关于powershell - PowerShell 中的复杂变量字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43915911/

相关文章:

powershell - 如何在Powershell中比较包含问号(?)的字符串

c++ - 如果我获取它的地址,是否保证静态变量是有序的?

java - 不使用正则表达式将字符串转换为映射

Python:按分隔符列表拆分字符串

azure - Get-AzApiManagementSubscription 命令返回订阅列表,但键值为空

windows - 使用 cd 命令浏览程序 x86 和一些路径问题

powershell - 如果您知道为什么 : is assigned but never,如何使警告静音甚至更好

PHP 提交变量 'passkey' 时会停止更新数据库

c++ - 模板参数作为变量

python - 拆分,将数据映射到 Pandas 数据框中的两列中