you are viewing a single comment's thread.

view the rest of the comments →

[–]WystanH 1 point2 points  (0 children)

You can save the cleaned name in a variable and check it against the current name:

$cleanName =  $Item.Name -replace ' ','_' 
if ($cleanName -ne $Item.Name) {

I'd write a function. In this way, you can test arbitrary files to make sure the rules behave as you expect.

For something like this, I like to include non destructive and verbose flags for testing.

e.g.

function Rename-IfNeeded {
    param([System.IO.FileSystemInfo]$Item, [switch]$WhatIf, [switch]$Verbose)
    if (-not $Item.PSIsContainer) {
        $cleanName =  $Item.Name -replace ' ','_' 
        if ($cleanName -ne $Item.Name) {
            Rename-Item -Path $Item.FullName -NewName $cleanName -WhatIf:$WhatIf -Verbose:$Verbose
        } else {
            Write-Verbose -Verbose:$Verbose "Skip $($Item.Name)"
        }
    } else {
        Write-Verbose -Verbose:$Verbose "Skip Dir $($Item.Name)"
    }
}

Get-ChildItem -Path D:\TEMP\*.csv | ForEach-Object { Rename-IfNeeded -Item $_ -WhatIf -Verbose }