问题
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 renamedefTC.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