0

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

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
Urh Lednik
  • 47
  • 2
  • 5

2 Answers2

0

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" }
nimizen
  • 3,345
  • 2
  • 23
  • 34
  • @Mathias - Thanks, fixed. – nimizen Sep 01 '15 at 15:07
  • How to prepare condition to copy just files with current and one day before current day in filename? My current code is: Copy-Item -Path "D:\Shares\WinCAP Data\DAYPROT\OFS-222_2\*.csv" -Destination \\Oracle\MP – Urh Lednik Sep 02 '15 at 04:30
  • It could also be condition for current file creation day and one creation day before. My files look like: abc27.11.2014TC.csv for example. – Urh Lednik Sep 02 '15 at 04:47
  • I've incorporated a date filter into the answer for the current question, the logic would be the same for a file copy. You could ask another question specifically for how to do this for a file copy but I suspect it would be closed as a duplicate. – nimizen Sep 02 '15 at 07:26
0

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")
Deadly-Bagel
  • 1,612
  • 1
  • 9
  • 21