简体   繁体   中英

PowerShell - Loop through files and rename

newbie here. I am trying to write a PowerShell script to:

  1. loop through all files in directory
  2. List item
  3. Get all .pdf files ONLY

    Rename them-the file names are long - over 30 chars -They contain 2 numbers which I need to extract -Example:

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

I tried examples from bunch of sites and I can't seem to even loop successfully. Either get an error - that path doesn't exist or that can't rename files as somehow loop gets a filepath and that I can't rename

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
}

That's just latest attempt, but any other ways of doing it will be fine - as long as it does the job.

Check the Help for Rename-Item . The Parameter -NewName requires the name of the file only, not the full path.

Try out this:

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
}

请尝试这个

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

Try this logic:

[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 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM