PowerShell-遍历文件并重命名

时间:2018-11-13 08:34:27

标签: powershell scripting

新手在这里。我正在尝试将PowerShell脚本编写为:

  1. 循环浏览目录中的所有文件
  2. 列表项
  3. 仅获取所有.pdf文件

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

    Microsoft Dynamics导航2018年累积更新11(内部版本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
}

这只是最近的尝试,但是其他任何可行的方法也可以-只要能做到即可。

3 个答案:

答案 0 :(得分:3)

查看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
}

答案 1 :(得分:0)

请尝试

Get-ChildItem -Path "C:\Users\******\Desktop\PowerShell Practice-Filter" -Filter *.pdf | Rename-Item -NewName $newname

答案 2 :(得分:0)

尝试以下逻辑:

[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 
}
相关问题