PowerShell - 循环遍历文件并重命名

6

新手上路。我正在尝试编写一个PowerShell脚本来:

  1. 循环遍历目录中的所有文件
  2. 列出项目
  3. 仅获取所有.pdf文件

    重命名它们-文件名很长-超过30个字符 -它们包含我需要提取的2个数字 -例如:

    Cumulative Update 11 for Microsoft Dynamics NAV 2018 (Build 25480).pdf -> 结果:= 18CU11.pdf

我尝试了许多网站的示例,但似乎甚至无法成功循环。 要么会出现错误-该路径不存在或无法重命名文件,因为某种方式循环获取了文件路径并且我不能重命名。

Get-ChildItem "C:\Users\******\Desktop\PowerShell Practice" -Filter *.pdf |  #create list of files

ForEach-Object{
    $oldname = $_.FullName;
    $newname = $_.FullName.Remove(0,17); 
    #$newname = $_.FullName.Insert(0,"CU")

    Rename-Item $oldname $newname;

    $oldname;
    $newname;  #for testing
}

这只是最新尝试,但其他任何实现方式都可以 - 只要它能完成工作。


2
你的原始文件名是什么样子的? - TobyU
4
如果显示路径不存在,那很可能是路径确实不存在?你应该包含你的尝试中的实际输出! - marsze
3个回答

4

请参考Rename-Item的帮助文档。参数-NewName只需要文件名,不需要完整路径。

可以尝试使用以下命令:

Get-ChildItem "C:\Users\******\Desktop\PowerShell Practice-Filter" -Filter *.pdf |  #create list of files

ForEach-Object{
    $oldname = $_.FullName
    $newname = $_.Name.Remove(0,17)

    Rename-Item -Path $oldname -NewName $newname

    $oldname
    $newname  #for testing
}

仍然会抛出错误 - Rename-Item 无法重命名指定的目标,因为它代表一个路径或设备名称。 - Arthur

3

尝试使用这个逻辑:

[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'Desktop\PowerShell Practice'
[string[]]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*.PDF' | Select-Object -ExpandProperty FullName
$listOfFilesToRename | ForEach-Object {
    #get the filename wihtout the directory
    [string]$newName = Split-Path -Path $_ -Leaf 
    #use regex replace to apply the new format
    $newName = $newName -replace '^Cumulative Update (\d+) .*NAV 20(\d+).*$', '$2CU$1.pdf' # Assumes a certain format; if the update doesn't match this expectation the original filename is maintained
    #Perform the rename
    Write-Verbose "Renaming '$_' to '$newName'" -Verbose #added the verbose switch here so you'll see the output without worrying about the verbose preference
    Rename-Item -Path $_ -NewName $newName 
}

-1
请尝试这个。
Get-ChildItem -Path "C:\Users\******\Desktop\PowerShell Practice-Filter" -Filter *.pdf | Rename-Item -NewName $newname

4
"$newname" 对于所有文件都相同吗? - derloopkat
不,但是重命名的逻辑对于所有文件都是相同的。 - Arthur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接