Advertisement
joedigital

ps-read file and remove leading space in filenames

May 19th, 2025 (edited)
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .SYNOPSIS
  3.     Renames specified files by removing the first character of their filenames.
  4. .DESCRIPTION
  5.     This script processes a list of provided file paths. For each file, it removes the
  6.     first character of its name (filename + extension) and renames the file.
  7.     It includes a -WhatIf parameter to preview changes without applying them.
  8.     The script will skip renaming if the original filename has only one character (as removing it would result in an empty name)
  9.     or if a file with the new name already exists.
  10. .PARAMETER FullName
  11.     An array of full paths to the files that need to be renamed. This parameter is mandatory
  12.     and can accept input from the pipeline (e.g., from Get-ChildItem or Get-Content).
  13. .EXAMPLE
  14.     .\Rename-RemoveFirstChar.ps1 -FullName "C:\temp\1example.txt", "C:\data\2another.log"
  15.     Description: Attempts to rename "C:\temp\1example.txt" to "example.txt" and
  16.                  "C:\data\2another.log" to "another.log".
  17.  
  18. .EXAMPLE
  19.     Get-ChildItem "C:\reports\*.tmp" | .\Rename-RemoveFirstChar.ps1
  20.     Description: Finds all .tmp files in "C:\reports\" and pipes them to the script
  21.                  to have their first character removed from their names.
  22.  
  23. .EXAMPLE
  24.     Get-Content "C:\ListOfFilesToRename.txt" | .\Rename-RemoveFirstChar.ps1 -WhatIf
  25.     Description: Reads a list of file paths from "C:\ListOfFilesToRename.txt",
  26.                  and shows what renames would occur without actually performing them.
  27.                  Each line in the text file should be a full path to a file.
  28.  
  29. .EXAMPLE
  30.     $fileList = @("C:\docs\Xfile1.docx", "C:\docs\_file2.pdf")
  31.     .\Rename-RemoveFirstChar.ps1 -FullName $fileList -Verbose
  32.     Description: Renames files specified in the $fileList array and provides verbose output.
  33.  
  34. .OUTPUTS
  35.     None by default, unless -Verbose or -WhatIf is used.
  36.     When -WhatIf is used, it outputs messages indicating what rename operations would occur.
  37. .NOTES
  38.     Author: Gemini
  39.     Date: 2025-05-19
  40.     It's highly recommended to run the script with -WhatIf first to ensure it targets the correct files
  41.     and the new names are as expected.
  42.     Files with names that are only one character long will be skipped.
  43.     If a file with the target new name already exists in the same directory, the rename operation for that specific file will be skipped.
  44. #>
  45. [CmdletBinding(SupportsShouldProcess = $true)] # Enables -WhatIf and -Confirm
  46. param (
  47.     [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
  48.     [string[]]$FullName # Accepts an array of file paths, also supports FullName property from piped FileInfo objects
  49. )
  50.  
  51. begin {
  52.     Write-Verbose "Script started: Rename-RemoveFirstChar."
  53.     $filesProcessedCount = 0
  54.     $filesRenamedCount = 0
  55. }
  56.  
  57. process {
  58.     foreach ($filePathInput in $FullName) {
  59.         $filesProcessedCount++
  60.         Write-Verbose "Processing input: '$filePathInput'"
  61.  
  62.         # Resolve the path to ensure it's a valid file path and get FileInfo object
  63.         try {
  64.             $FileItem = Get-Item -LiteralPath $filePathInput -ErrorAction Stop
  65.         }
  66.         catch {
  67.             Write-Warning "Path '$filePathInput' could not be found or accessed. Error: $($_.Exception.Message). Skipping."
  68.             continue
  69.         }
  70.  
  71.         # Ensure it's a file, not a directory
  72.         if ($FileItem -isnot [System.IO.FileInfo]) {
  73.             Write-Warning "Path '$($FileItem.FullName)' is a directory, not a file. Skipping."
  74.             continue
  75.         }
  76.  
  77.         $OriginalFullName = $FileItem.FullName
  78.         $OriginalName = $FileItem.Name
  79.         $DirectoryPath = $FileItem.DirectoryName
  80.  
  81.         # Check if the filename has enough characters to remove the first one
  82.         if ($OriginalName.Length -lt 2) {
  83.             Write-Warning "File '$OriginalFullName' has a name '$OriginalName' which is too short (less than 2 characters) to remove the first character. Skipping."
  84.             continue
  85.         }
  86.  
  87.         # Generate the new name by removing the first character
  88.         $NewName = $OriginalName.Substring(1)
  89.  
  90.         # This check is technically covered by the Length -lt 2, but good for clarity
  91.         if ([string]::IsNullOrWhiteSpace($NewName)) {
  92.             Write-Warning "Skipping file '$OriginalFullName' as removing the first character would result in an empty filename."
  93.             continue
  94.         }
  95.  
  96.         # Construct the new full path
  97.         $NewFileFullName = Join-Path -Path $DirectoryPath -ChildPath $NewName
  98.  
  99.         # Check if a file with the new name already exists
  100.         if (Test-Path -LiteralPath $NewFileFullName) {
  101.             Write-Warning "Skipping rename of '$OriginalFullName': A file named '$NewName' already exists at '$NewFileFullName'."
  102.             continue
  103.         }
  104.  
  105.         Write-Host "Preparing to rename '$OriginalName' to '$NewName' in directory '$DirectoryPath'"
  106.  
  107.         # Perform the rename operation, respecting -WhatIf
  108.         if ($PSCmdlet.ShouldProcess($OriginalFullName, "Rename to '$NewFileFullName' (removing first character)")) {
  109.             try {
  110.                 Rename-Item -LiteralPath $OriginalFullName -NewName $NewName -ErrorAction Stop
  111.                 Write-Host "Successfully renamed '$OriginalFullName' to '$NewFileFullName'" -ForegroundColor Green
  112.                 $filesRenamedCount++
  113.             }
  114.             catch {
  115.                 Write-Error "Failed to rename '$OriginalFullName' to '$NewName'. Error: $($_.Exception.Message)"
  116.             }
  117.         }
  118.     }
  119. }
  120.  
  121. end {
  122.     Write-Verbose "Script finished."
  123.     Write-Host "Total file paths processed: $filesProcessedCount"
  124.     Write-Host "Total files successfully renamed: $filesRenamedCount"
  125.  
  126.     if ($PSCmdlet.WhatIfPreference) {
  127.          Write-Host "--- WhatIf Mode: No changes were made. ---"
  128.     } elseif ($filesRenamedCount -eq 0 -and $filesProcessedCount -gt 0) {
  129.         Write-Host "No files were renamed. Check warnings or verbose output for details."
  130.     } elseif ($filesProcessedCount -eq 0) {
  131.         Write-Host "No file paths were provided or found to process."
  132.     }
  133. }
  134.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement