简体   繁体   English

替换部分文件名 Powershell

[英]Replace Part of File Name Powershell

I have files that are generated every morning:我有每天早上生成的文件:

  • Default_20140227_05.00.29.csv Default_20140227_05.00.29.csv
  • Default_20140226_05.00.29.csv Default_20140226_05.00.29.csv

I would like to rename the files:我想重命名文件:

  • VOD_20140227_05.00.29.csv VOD_20140227_05.00.29.csv
  • VOD_20140226_05.00.29.csv VOD_20140226_05.00.29.csv

I would basically be replacing Default with VOD .我基本上会用VOD替换Default

I am using Powershell 1.0.我正在使用 Powershell 1.0。 Any help would be greatly appreciated.任何帮助将不胜感激。

简化:

ls *.csv | Rename-Item -NewName {$_.name -replace "Default","VOD"}

我没有要测试的 PowerShell 1.0,但假设您在文件所在的文件夹中运行它,您可以尝试:

Get-ChildItem Default_*.csv  |Rename-Item -NewName {$_.name -replace '^Default','VOD'}

gci | ?{$_.Name -like "Default*"} | % {$newname = ([String]$_).Replace("Default","VOD"); Rename-item $_ $newname}

A more explanatory version:一个更解释的版本:

$DefaultFiles =  Get-ChildItem | Where-Object {$_.Name -like "Default*"}
ForEach($File in $DefaultFiles) 
{
    $newname = ([String]$File).Replace("Default","VOD")
    Rename-item -Path $File $newname
}

If you're looking for a generic version that will take your find and replace as parameters and log out what you've renamed (handy, imo), here's one building from Cole9350's answer :如果您正在寻找一个通用版本,它将您的查找和替换作为参数并注销您重命名的内容(方便,imo),这是来自 Cole9350 的答案的一栋建筑:

$Find = $args[0]
$Replace = $args[1]
$TargetFiles =  Get-ChildItem | Where-Object {$_.Name -like "*$Find*"}
ForEach($File in $TargetFiles) 
{
    $newname = ([String]$File).Replace($Find,$Replace)
    write-host "Renaming $File to $newname"
    Rename-item -Path $File.PSPath $newname
}

And if you want it recursive, just add -Recurse after Get-ChildItem如果你想要它递归,只需在Get-ChildItem之后添加-Recurse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM