Friday, 5 July 2024

Replace spaces

Have you ever found yourself staring at a folder full of files with spaces in their names, wishing for a quick way to tidy things up? As a fellow software engineer, I've been there too. While spaces in filenames are common in Windows, they can sometimes cause headaches, especially when working with scripts or command-line tools.


Today, I'm excited to share a nifty Microsoft PowerShell 7 solution that can help streamline your file organization by replacing those pesky spaces with underscores.


Let's dive into some code that will make your file management a breeze and potentially save you from future headaches. Whether you're a seasoned PowerShell pro or just getting started, this simple yet powerful piece of code is sure to become a valuable addition to your toolkit.


# Get all files in the current directory with spaces in their names and rename them, replacing spaces with underscores

Get-ChildItem -File |

    Where-Object { $_.Name -match '\s' } |
    Rename-Item -NewName { $_.Name -replace '\s+', '_' } -WhatIf

Renaming files that are in use by running processes can cause issues. Ensure that the items you're renaming are not actively being used by other applications. Remember to remove the -WhatIf parameter when you're ready to actually perform the rename operation.


No comments:

Post a Comment