PowerShell File rename

走远了吗. 提交于 2020-07-11 04:13:08

问题


How to ignore file rename if the filename already contains string during file rename process.

My example:

Get-ChildItem "D:\Shares\WinCAP Data\DAYPROT\OFS-222_2\*.csv" | Rename-Item -NewName { $_.Name -replace "\.csv", "TC.csv" }

I would like to rename just files without string "TC" in filename - for example:

abc.csv to rename
defTC.csv do not want to rename


回答1:


You could filter off the files which don't require the rename with a regex:

?{!($_.fullname -match "TC\.csv")}

So, for your example:

Get-ChildItem "D:\Shares\WinCAP Data\DAYPROT\OFS-222_2\*.csv" | 
?{!($_.fullname -match "TC\.csv")} |
Rename-Item -NewName { $_.Name -replace "\.csv", "TC.csv" }

Incorporate a date filter into this as follows:

Get-ChildItem "D:\Shares\WinCAP Data\DAYPROT\OFS-222_2\*.csv" | 
?{!($_.fullname -match "TC\.csv") -and $_.CreationTime -ge (get-date).AddDays(-1).Date} |
Rename-Item -NewName { $_.Name -replace "\.csv", "TC.csv" }



回答2:


As a simpler and more straightforward solution you could just filter into a ForEach loop and use an IF statement. Probably not quite as efficient but easier to maintain and adapt for other uses.

Get-ChildItem "D:\Shares\WinCAP Data\DAYPROT\OFS-222_2\*.csv" | Foreach-Object { 
    if ($_.Name -notlike "*TC*") { 
        Rename-Item $_ ($_.Name -Replace "\.csv", "TC.csv") 
    } 
}

Alternatively pass it to a Where filter and then to the rename (note this particular syntax requires PS v3):

Get-ChildItem "D:\Shares\WinCAP Data\DAYPROT\OFS-222_2\*.csv" | Where Name -notlike "*TC*" | Rename-Item $_ ($_.Name -Replace "\.csv", "TC.csv")


来源:https://stackoverflow.com/questions/32333890/powershell-file-rename

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