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.
    # .NOTES
    # 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.
    # .NOTES
    # Version: 2023-03-01 2024-01-06
    # .EXAMPLE
    # dir | xah-rename-file-space-to-lowline
    # .LINK
    # http://xahlee.info/powershell/powershell_rename_file_space_to_lowline.html

    Process {
        if (-not $MyInvocation.ExpectingInput) { Write-Host "No pipeline received."; return ; }
        if ($_.name.contains(" ")) {
            $fname = $_.name;
            $newName = $fname.replace(" ", "_")
            Write-Host ("$_ → $newName")
            Rename-Item $_ $newName
        }
    }
}