Find Replace Text in a File Name - Powershell

元气小坏坏 提交于 2019-12-11 09:58:59

问题


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:


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.



来源:https://stackoverflow.com/questions/25411056/find-replace-text-in-a-file-name-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!