PowerShell: Rename Files, Space to Lowline

By Xah Lee. Date: . Last updated: .

Functions to rename file from space to lowline _.

function xah-list-file-name-contain-space {
    # .DESCRIPTION
    # List file whose name contains space. Of current dir.
    # Version 2023-03-01
    # .EXAMPLE
    # xah-list-file-name-contain-space
    # .LINK
    # http://xahlee.info/powershell/powershell_rename_file_space_to_lowline.html
    Get-ChildItem -Recurse -File -Filter "* *"
}

function xah-rename-file-space-to-lowline {
    # .DESCRIPTION
    # pipe files to this function to rename it.
    # Version 2023-03-01 2023-03-02 2023-03-03
    # .EXAMPLE
    # dir -recurse -file -filter "* *" | xah-rename-file-space-to-lowline
    # .LINK
    # http://xahlee.info/powershell/powershell_rename_file_space_to_lowline.html
    Process {
        if ($null -eq $_) {
            Write-Host "Pipe is empty. Nothing is done."
            return
        }
        $fullpath = $_.fullname
        $fname = $_.name;
        if ($fname.contains(" ")) {
            $newName = $fname.replace(" ", "_")
            Write-Output ($fullpath + " → " + $newName)
            Rename-Item $fullpath $newName
        }
    }
}

PowerShell in Depth

Path

Pipe

Comment

Value Types

String

Variable

Boolean

Conditional

Data Structure

Loop and Iteration

Input/Output

Function

Profile and Script

Script Examples

Misc