1

I am a programmer by no means and am brand new to using powershell, but have been tasked with setting up some batch export processes for daily files we FTP. I need to come up with a script that will take changing file names and change them within the same directory to new names;

Example: files will come in as below (YYYYMMDD will be the changing variable)

YYYYMMDD_Share_Support.txt
YYYYMMDD_Person_Support.txt

We need them to be stripped from the above to:

Share.txt
Person.txt

so on and so forth.

I have found ways to make this work, but only on an as needed basis for one file at a time with specific names, not names that will change daily.

So far I am using:

Get-ChildItem -Filter *.txt

Dir | %{Rename-Item $_ -NewName ("NEWFILENAME.txt" -f $nr++)}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
SpudmanChu
  • 11
  • 1

3 Answers3

3

You could use the regex -replace operator inside a pipeline-bound scriptblock:

$files = Get-ChildItem -filter *.txt 
$files |Rename-Item -NewName { $_.Name -replace '^\d{8}_(.*)_Support\.txt$', '$1.txt' }

As suggested by TheIncorrigible1, if you know the relative position of the word you need, you can also use -split:

$files |Rename-Item -NewName {'{0}.txt' -f ($_.Name -split '_')[-2]}  # grab 2nd last word
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

How about:

dir *.txt | 
  rename-item -newname { $null,$base,$null = $_.basename -split '_'; "$base.txt" } -whatif
js2010
  • 23,033
  • 6
  • 64
  • 66
0

Probably a longer version of the answer. An alternative mentioned by @TheIncorrigible1

$logDir = "D:\Satish\TestFolders"
cd $logDir

$files = ls

foreach ($file in $files){
$fileSplit=($file.ToString()).split("_")


ren $file "$($fileSplit[1]).txt"

}

And for Share.txt to YYYYMMDD_Share_Support.txt

$logDir = "D:\Satish\TestFolders"
cd $logDir

$files = ls

$date = Get-Date -Format "yyyyMMdd"

foreach ($file in $files){
$fileSplit=($file.ToString()).split(".")


ren $file "$($date)_$($fileSplit[0])_Support.txt"

}