MrTCS
MrTCS

Reputation: 187

Ways to avoid this $null test

I'm working on a script that will delete old sql backups, but only if there are newer ones. I've written the below script but not sure if I should be handling the $d[0] -eq $null section that way. I tried doing a count but the logic kept failing because if $dir | Get-ChildItem | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays($days) -and $_.extension.ToString() -eq ".bak"} returned nothing $d still had a count of 1. So, is there another way or writing this?

Set-Location \\Server\Backups

$days = -2
$list = @()

$DBFolders = Get-ChildItem | Where-Object {$_.PSIsContainer -eq $true }

Foreach ($dir in $DBFolders)
{
    $d = @()
    $d += $dir | Get-ChildItem | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays($days) -and $_.extension.ToString() -eq ".bak"}

    if ($d[0] -ne $null)
        {
            $list += $dir | Get-ChildItem | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays($days) -and $_.extension.ToString() -eq ".bak" -or $_.extension.tostring() -eq ".trn"}
        }
}

$list | remote-item

Upvotes: 3

Views: 69

Answers (2)

n0rd
n0rd

Reputation: 12610

You can try the following:

$ts = (Get-Date).AddDays(-2); # so we don't call it dozens of times
$dirsToClean = Get-ChildItem -Directory | Where-Object { Get-ChildItem $_\*.bak | Where-Object {$_.LastWriteTime -gt $ts} };
$filesToDelete = $dirsToClean | ForEach-Object {Get-ChildItem (Join-Path $_ *) -Include *.bak,*.trn | Where-Object {$_.LastWriteTime -lt $ts}};

variable names should be self-explanatory.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Simply test if $d evaluates to $true or $false - an empty collection always evaluates to $false:

$d = @()
$d += $dir | Get-ChildItem | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays($days) -and $_.extension.ToString() -eq ".bak"}

if($d){
    # $d is not empty
}

Upvotes: 1

Related Questions