Hello PowerShell Experts –
I have a folder with the following files in it:
-a--- 12/22/2011 9:22 AM 595280896 Backup1.BAK
-a--- 9/8/2011 9:56 AM 52839424 Backup2.BAK
-a--- 9/8/2011 9:56 AM 52839424 Backup2.trn
-a--- 9/8/2011 9:56 AM 52839424 Backup2a.trn
-a--- 9/8/2011 10:03 AM 635913216 Backup3.BAK
-a--- 9/22/2011 10:51 AM 406340608 Backup4.BAK
-a--- 9/29/2011 10:02 AM 123945984 Backup5.BAK
-a--- 12/22/2011 5:59 AM 290538496 Backup6.BAK
-a--- 12/22/2011 5:59 AM 290538496 Backup6.trn
-a--- 12/22/2011 5:59 AM 290538496 Backup6a.trn
-a--- 12/22/2011 9:22 AM 595280896 Backup7.BAK
-a--- 11/4/2011 1:16 PM 75187200 Backup8.BAK
What I want to do is identify the newest .bak file and copy it to an alternate location. I then want to identify the oldest .bak file and delete it. In addition to deleting the oldest .bak file, I want the script to look at the date of the oldest .bak file and identify all .trn files with the same date and delete those as well.
Below I have provided my script code:
#################### VARIABLES ####################
#
#The following variable identifies the newest file
$NewestFile = Get-ChildItem c:\Source\*.bak | Sort-Object lastwritetime -Descending | Select-Object -First 1
#The following variable identifies the oldest file
$OldestFile = Get-ChildItem c:\Source\*.bak | Sort-Object lastwritetime | Select-Object -First 1
#The following variable identifies the purge date in a MM/DD/YYYY format.
$PurgeDate = Get-ChildItem c:\Source\*.bak | Sort-Object lastwritetime | Select-Object -First 1 `
| Select-object @{n="lastwritedate"; e={$_.lastwritetime.toshortdatestring()}}
#The following variable lists all of the *.trn files in the source folder
$TrnFiles = Get-ChildItem c:\Source\*.trn
#
#
#
#
#################### Script Code ####################
Copy-Item $NewestFile -Destination "c:\Target"
What I think needs to happen next is I need to go through each item in the $TrnFiles variable and change the lastwritetime property to a date with the mm/dd/yyyy format. Once that is done, I can compare the date for each item in the variable and if the item’s last write time is equal to the date in the $Purgedate variable, then the item is deleted. To do this, I tried the following:
ForEach($trnfile in $TrnFiles) {
Select-Object @{n="lastwritedate"; e={$_.lastwritetime.toshortdatestring()}} `
| If ($_.lastwritedate -eq $PurgeDate) {Remove-Item}
}
The results were the following error.
The term 'If' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At :line:15 char:5
+ | If <<<< ($_.lastwritedate -eq $PurgeDate) {Remove-Item}
Is my logic correct? If so, what am I doing wrong with the “if” statement.
Is there a better way of doing this?
My apologies for the remedial Powershell skills.
Nick