functions/Rename-LargeFile.ps1
function Rename-LargeFile { <# .SYNOPSIS Renames files provided by adding a prefix. .DESCRIPTION Renames files provided by adding a prefix. .PARAMETER Path The Path to the file to rename. .PARAMETER Prefix The Prefix to apply (if it has not already been applied) .PARAMETER WhatIf Do a trial run without actually changing anything .PARAMETER Confirm Ask for confirmation before renaming files .EXAMPLE PS C:\> Rename-LargeFile -Path $file.FullName -Prefix 'TOO_LARGE_' Renames the file specified in $file, adding the 'TOO_LARGE_' prefix #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateScript({ if (Test-Path -LiteralPath $_) { return $true } throw "Path not found: $_" })] [Alias('FullName')] [string[]] $Path, [Parameter(Mandatory = $true)] [string] $Prefix ) process { foreach ($fileObject in Get-Item -LiteralPath $Path) { if ($fileObject.PSIsContainer) { Write-PSFMessage -Level Warning -Message "Not a file: $($fileObject.FullName)" continue } $object = [PSCUstomObject]@{ FullName = $fileObject.FullName Name = $fileObject.Name NewName = $fileObject.Name Size = $fileObject.Length Extension = $fileObject.Extension Success = $false Renamed = $false Error = $null } if ($object.NewName -notlike "$Prefix*") { $object.NewName = $Prefix, $object.NewName -join "" if ($object.NewName.Length -gt 250) { $object.NewName = $object.NewName.SubString(0,250) } } if ($object.Name -eq $object.NewName) { $object.Success = $true $object continue } if (-not $PSCmdlet.ShouldProcess($object.FullName, "Rename to $($object.NewName)")) { $object continue } Write-PSFMessage -Message "Renaming $($object.FullName) to $($object.NewName)" try { Rename-Item -LiteralPath $object.FullName -NewName $object.NewName -ErrorAction Stop } catch { $object.Error = $_ $object continue } $object.Renamed = $true $object.Success = $true $object } } } |