Find Replace Text in a File Name - Powershell

2019-08-04 11:15发布

i have a need to replace different string in file names. Is there a way to modify a file name using a find replace function in Powershell?

I have done this in a .bat file but would for this to be done in PS instead.

1条回答
\"骚年 ilove
2楼-- · 2019-08-04 11:46

You didn't provide any details so here's a generic example:

$pattern = "foo"

# Getting all files that match $pattern in a folder.
# Add '-Recurse' switch to include files in subfolders.
$search_results = Get-ChildItem -Path "C:\folder" `
    | Where-Object { ((! $_.PSIsContainer) -and ($_.Name -match $pattern)) } 

foreach ($file in $search_results) {
    $new_name = $file.Name -replace $pattern, "bar"

    # Remove '-WhatIf' switch to commit changes.
    Rename-Item -WhatIf -Path $file.FullName -NewName $new_name
}

Note that $pattern will be treated as a regular expression so escape special characters if you need to catch them.

查看更多
登录 后发表回答