So as the title says, I want to check the LastWriteTime of a specific file (always have same name), and if that file is older than 50 days, i want to delete the content of a folder (which is next to it).
There can be 2 type of paths, here is the structure :
D:\Server\Azerty\BAL\*\CE
D:\Server\WARRIOR\*\Azerty\BAL\*\CE
The "*" is here because there are several folders with different name. The file name I want to check LastWriteTime is "Olympe". The folder which I want to delete the content is named "CE" (see paths above).
I tried a lot of things and I ran out of idea so here I am asking for helps.
Here is my code :
$Folder1 = "D:\Server\Azerty\BAL\*\CE"
$Folder2 = "D:\Server\WARRIOR\*\Azerty\BAL\*\CE"
$pathlogs = "D:\Server\Script\Purge\logs"
$Date = (get-date).ToString("yyyyMMdd-HHmmss")
If((Test-Path $Folder1))
{
$olympe1 = Get-ChildItem -Path "D:\Server\Azerty\BAL\*\Olympe"
$age1 = (Get-Date) - ($olympe1.LastWriteTime)
if($age1.Days -gt 50)
{
#Logs
Get-ChildItem -Path $flagcomm1 |
Where-Object {!$_.PSIsContainer} | Select-Object -Property FullName | Out-File $pathlogs\$Date-Purge.txt -Append
#Suppression
Get-ChildItem -Path $Bal1 |
Where-Object {!$_.PSIsContainer} |
ForEach-Object {
Remove-Item -Force -Recurse
}
}
}
elseif((Test-Path $Folder2))
{
$olympe2 = Get-ChildItem -Path "D:\Server\WARRIOR\*\Azerty\BAL\*\Olympe"
#$age2 = [datetime](Get-Date).ToUniversalTime() - [datetime]($flagcomm2.LastWriteTime | Select-Object -First 1 | ForEach-Object {$_.ToUniversalTime()})
if($olympe2.LastWriteTime | Select-Object -First 1 |
ForEach-Object {$_.ToUniversalTime()} -lt (Get-Date).AddDays(-50).ToUniversalTime())
{
Get-ChildItem -Path $Folder2 -Recurse |
Where-Object {$_.LastWriteTime.ToUniversalTime() -lt (Get-Date).AddDays(-50).ToUniversalTime()} |
ForEach-Object {
Remove-Item -Force -Recurse
}
}
else {
}
}
My last tries were on the elseif
, since this was my testing case.
With this, I got this error :
ForEach-Object : Cannot bind parameter 'RemainingScripts'. Cannot convert the "-lt" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
At D:\Server\ScriptPurge_ALL - Copy.ps1:34 char:5
+ ForEach-Object {$_.ToUniversalTime()} -lt (Get-Date).AddDays(-50) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [ForEach-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ForEachObjectCommand
I would be glad to get some help :)
PS : Lines and row indicated in the error might be a bit wrong since I changed names for the post.