代码之家  ›  专栏  ›  技术社区  ›  Syntax Error ine

powershell重命名文件不起作用-无错误

  •  1
  • Syntax Error ine  · 技术社区  · 6 年前

    我正在尝试将文件从一个目录复制到另一个目录并重命名它们。目标文件夹的文件将被删除,文件将被复制,但不幸的是,脚本的重命名部分没有执行任何操作。没有显示错误。

    #Set variables
    [string]$source = "C:\temp\Photos\Original\*"
    [string]$destination = "C:\temp\Photos\Moved\"
    #Delete original files to avoid conflicts
    Get-ChildItem -Path $destination -Include *.* -Recurse | foreach { $_.Delete()}
    #Copy from source to destination
    Copy-item -Force -Recurse -Verbose $source -Destination $destination
    
    Get-ChildItem -Path $destination -Include *.jpg | rename-item -NewName { $_.Name -replace '-', ' ' }
    

    目前,我只是试图用空格替换连字符,但我还需要删除 W 从文件名的末尾,当我能让它工作的时候。

    原始文件名示例: First-Last-W.jpg

    所需文件名示例: First Last.jpg

    3 回复  |  直到 6 年前
        1
  •  1
  •   codewario    6 年前

    你想用 $PSItem (也称为 $_ )在适当的环境之外。你应该加一个 Foreach-Object 到您的管道:

    # This can be a one-liner, but made it multiline for clarity
    Get-ChildItem -Path $destination -Filter *.jpg | Foreach-Object {
      $_ | Rename-Item -NewName ( ( $_.Name -Replace '-w\.jpg$', '.jpg' ) -Replace '-', ' ' )
    }
    

    我在上面的代码块中添加了另外两项内容:

    1. 你用了大括号,你应该用括号,正如@jacob的答案所证明的那样。我在这里也解决了这个问题。

    2. 我加了一秒钟 -Replace 这将删除 -W 从新名称的末尾开始(同时保持 .jpg 分机)。有关powershell正则表达式匹配的详细信息,请参阅下面的源代码。

    资料来源:

        2
  •  3
  •   FlowOverStack    6 年前

    改变 -include 参数 -filter

    Get-ChildItem -Path $destination -Include *.jpg
    

    包含基于IS的Cmdlet

    Get-ChildItem -Path $destination -filter *.jpg
    

    筛选器基于提供程序

    for more info

        3
  •  0
  •   Jacob    6 年前

    我没有测试过这个,但是看起来那些花括号看起来不对,如果您尝试以下操作会发生什么情况:

    #Set variables
    [string]$source = "C:\temp\Photos\Original\*"
    [string]$destination = "C:\temp\Photos\Moved\"
    #Delete original files to avoid conflicts
    Get-ChildItem -Path $destination -Include *.* -Recurse | foreach { $_.Delete()}
    #Copy from source to destination
    Copy-item -Force -Recurse -Verbose $source -Destination $destination
    
    Get-ChildItem -Path $destination -Include *.jpg | rename-item -NewName ($_.Name -replace '-', ' ')