I get a "path is not valid", even though it's valid. I run it with my own user, and i can browse the folders and delete files in the folders. But when I run my code, I get "path is not valid". I have also tried running it in the administrative console. Am I doing something wrong? Powershell version: 4
param (
$rootPath = "$env:ProgramFiles\NetApp\SnapManager for Exchange\Report\",
$paths = ("Debug [11EXS05]\","Backup [11EXS05]\"),
$wildCard = "*.txt",
$daysToKeep = "14"
)
#define LastWriteTime parameter based on $daysToKeep
$now = Get-Date
$lastWrite = $now.AddDays(-$daysToKeep)
#Loop through each path in paths
foreach($path in $paths)
{
$currentPath = Join-Path -Path $rootPath $path
if(Test-Path $currentPath)
{
#get all the files that has LastWriteTime less than today minus $daysToKeep, then delete those files, pipe output to screen
Get-ChildItem $currentPath `
-Include $wildCard -Recurse | `
Where {$_.LastWriteTime -le "$lastWrite"} | foreach{ "Removing file $($_.FullName)"; Remove-Item $_}
}
else
{
Write-Host ($currentPath + " is not valid") -ForegroundColor Red
}
}
Edit, the solution:
Had to fix the []
like the answers below. And also, I had to add $currentPath
to the Remove-Item
command, the full script:
param (
$rootPath = "$env:ProgramFiles\NetApp\SnapManager for Exchange\Report\",
$paths = ('Debug `[11EXS05`]\','Backup `[11EXS05`]\'),
$wildCard = "*.txt",
$daysToKeep = "17"
)
#define LastWriteTime parameter based on $daysToKeep
$lastWrite = (Get-Date).Date.AddDays(-$daysToKeep)
#Loop through each path in paths
foreach($path in $paths)
{
$currentPath = Join-Path -path $rootPath $path
if(Test-Path $currentPath)
{
#get all the files that has LastWriteTime less than today minus $daysToKeep, then delete those files, pipe output to screen
Get-ChildItem $currentPath `
-Filter $wildCard -Recurse | `
Where {$_.LastWriteTime -le "$lastWrite"} | foreach{ "Removing file $($_.FullName)"; Remove-Item ($currentPath + "\" + $_) -Force}
}
else
{
Write-Host ($currentPath + " is not valid") -ForegroundColor Red
}
}