Advertisement
joedigital

ps-read file and remove leading space from filenames

May 19th, 2025 (edited)
413
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 or file 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. **    .\rrspace.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. .EXAMPLE
  34.     Expected text file format of paths\files to be renamed (can also use mapped drive instead of \\<server>\<share>),
  35.         one path/file per line:
  36.     \\NJHYFS\depts\ENGIN\Doug R\Teterboro Airport Submittals\ Potential Spam   TEB - 914 205 United Water field meeting.msg
  37.     \\NJHYFS\depts\ScanDocuments\Direct_Debit\Daily Work\2016\JAN 2016\6\ 100_8957622222_01062016.pdf
  38.     b:\ENGIN\Doug R\Teterboro Airport Submittals\ Potential Spam   TEB - 914 205 United Water field meeting.msg
  39.     b:\ScanDocuments\Direct_Debit\Daily Work\2016\JAN 2016\6\ 100_8957622222_01062016.pdf
  40. .OUTPUTS
  41.     None by default, unless -Verbose or -WhatIf is used.
  42.     When -WhatIf is used, it outputs messages indicating what rename operations would occur.
  43. .NOTES
  44.     Author: Gemini
  45.     Date: 2025-05-19
  46.     It's highly recommended to run the script with -WhatIf first to ensure it targets the correct files
  47.     and the new names are as expected.
  48.     Files with names that are only one character long will be skipped.
  49.     If a file with the target new name already exists in the same directory, the rename
  50.       operation for that specific file will be skipped.
  51. #>
  52. [CmdletBinding(SupportsShouldProcess)] # Enables -WhatIf and -Confirm
  53. param (
  54.   [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
  55.     [string[]]$SourceFile, # Accepts an array of file paths, also supports FullName property from piped FileInfo objects
  56.   [Parameter(Mandatory)]
  57.     [string]$logFilePrefix # date will be calculated and added in the next section in addition the extension .log
  58. )
  59.  
  60. begin {
  61.   $begTime = Get-Date
  62.   $filesProcessedCount = 0
  63.   $filesRenamedCount = 0
  64.   $renameThese = Get-Content -Path $SourceFile
  65.   $warningFGcolor = "Yellow"
  66.   $warningBGcolor = "DarkRed"
  67.   $logupdateFGcolor = "White"
  68.   $logupdateBGcolor = "DarkBlue"
  69.   $logFilePrefix = $logFilePrefix + "-" + $((Get-Date).ToString('yyyy-MM-dd_HH-mm-ss')) + ".log"
  70.  
  71.   # Start-Transcript -Path $logFile
  72.  
  73.   #Write-Host "Script started, reading $SourceFile ($($renameThese.Count) files)." -ForegroundColor Green -BackgroundColor DarkGray
  74.   $logthis = "Script started $begtime, reading $SourceFile ($($renameThese.Count) files).`n"
  75.   $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Host -ForegroundColor Green -BackgroundColor DarkGray
  76. }
  77.  
  78. process {
  79.   foreach ($filePathInput in $renameThese) {
  80.     $filesProcessedCount++
  81.     #Write-Host "Processing input: '$filePathInput' `n($($filesProcessedCount) of $($renameThese.count))" -ForegroundColor Blue
  82.     $logthis = "Processing input: '$filePathInput' `n($($filesProcessedCount) of $($renameThese.count))"
  83.     $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Host -ForegroundColor Blue
  84.     # Resolve the path to ensure it's a valid file path and get FileInfo object
  85.     try {
  86.         $FileItem = Get-Item -LiteralPath $filePathInput -ErrorAction Stop
  87.     }
  88.     catch {
  89.         $logthis = "'$filePathInput' could not be found or accessed. Error: $($_.Exception.Message).`n...Skipping"
  90.         #Write-Warning $logthis
  91.         $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Host -ForegroundColor $warningFGcolor -BackgroundColor $warningBGcolor
  92.         continue
  93.     }
  94.  
  95.     # Ensure it's a file, not a directory
  96.     if ($FileItem.GetType().Name -ne "FileInfo") {
  97.         $logthis = "'$($FileItem.Name)' is not a file, skipping..."
  98.         #Write-Warning "'$($FileItem.Name)' is not a file, skipping..."
  99.         $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Host -ForegroundColor $warningFGcolor -BackgroundColor $warningBGcolor
  100.         continue
  101.     }
  102.  
  103.     $OriginalFullName = $FileItem.FullName
  104.     $OriginalName = $FileItem.Name
  105.     $DirectoryPath = $FileItem.DirectoryName
  106.  
  107.     # Check if the filename has enough characters to remove the first one
  108.     if ($OriginalName.Length -lt 2) {
  109.         $logthis = "File '$OriginalFullName' has a name '$OriginalName' which is too short (less than 2 characters) to remove the first character.`n...Skipping"
  110.         #Write-Warning $logthis
  111.         $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Host -ForegroundColor $warningFGcolor -BackgroundColor $warningBGcolor
  112.         continue
  113.     }
  114.  
  115.     # Generate the new name by removing the first character
  116.     $NewName = $OriginalName.TrimStart()
  117.  
  118.     # This check is technically covered by the Length -lt 2, but good for clarity
  119.     #if ([string]::IsNullOrWhiteSpace($NewName)) {
  120.     #    Write-Warning "Skipping file '$OriginalFullName' as removing the first character would result in an empty filename."
  121.     #    continue
  122.     #}
  123.  
  124.     # Construct the new full path
  125.     $NewFileFullName = Join-Path -Path $DirectoryPath -ChildPath $NewName
  126.  
  127.     # Check if a file with the new name already exists
  128.     if (Test-Path -LiteralPath $NewFileFullName) {
  129.         $logthis = "Skipping rename of '$OriginalFullName': A file named '$NewName' already exists at '$DirectoryPath'"
  130.         #Write-Warning $logthis
  131.         $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Host -ForegroundColor $warningFGcolor -BackgroundColor $warningBGcolor
  132.         continue
  133.     }
  134.  
  135.     Write-Host "Preparing to rename '$OriginalName'`n to '$NewName' `nin directory '$DirectoryPath'" -ForegroundColor White
  136.  
  137.     # Perform the rename operation, respecting -WhatIf
  138.     if ($PSCmdlet.ShouldProcess($OriginalFullName, "Rename to '$NewFileFullName' (removing first character)")) {
  139.         try {
  140.           Rename-Item -LiteralPath $OriginalFullName -NewName $NewName -ErrorAction Stop
  141.           $logthis = "Successfully renamed: '$OriginalFullName' to '$NewFileFullName'"
  142.           $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Host  -ForegroundColor $logupdateFGcolor -BackgroundColor $logupdateBGcolor
  143.           $filesRenamedCount++
  144.         }
  145.         catch {
  146.           #Write-Error "Failed to rename '$OriginalFullName' to '$NewName'.`n Error: $($_.Exception.Message)"
  147.           $logthis = "Failed to rename '$OriginalFullName' to '$NewName'. Error: $($_.Exception.Message)"
  148.           $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Error
  149.         }
  150.     }
  151.   }
  152. }
  153.  
  154. end {
  155.   Write-Host "Total files processed: $filesProcessedCount"
  156.  
  157.   if ($PSCmdlet.WhatIfPreference) {
  158.       Write-Host "--- WhatIf Mode: No changes were made. ---"
  159.   } elseif ($filesRenamedCount -eq 0 -and $filesProcessedCount -gt 0) {
  160.       Write-Host "No files were renamed. Check warnings or verbose output for details."
  161.   } elseif ($filesProcessedCount -eq 0) {
  162.       Write-Host "No file paths were provided or found to process."
  163.   }
  164.  
  165. #  Stop-Transcript
  166.   $endTime = Get-Date
  167.   #$endTime
  168.   $totalTime = New-TimeSpan -Start $begTime -End $endTime | Select-Object -Property TotalSeconds, TotalMinutes  
  169.  
  170.   #Write-Host "end of script; Total files successfully renamed: $filesRenamedCount" -ForegroundColor Green -backgroundColor DarkGray
  171.   $logthis = "`nend of script: $endTime `n$totalTime`nTotal files successfully renamed: $filesRenamedCount"
  172.   $logthis | Tee-Object -FilePath $logFilePrefix -Append | Write-Host -ForegroundColor Green -backgroundColor DarkGray
  173. }
  174.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement