madknacker
madknacker

Reputation: 81

PowerShell Get-ChildItem with variable and string

Back at it again trying to delete files using PowerShell.

What I am attempting now is deleting files that begin with "Export_" and then a two-digit year followed by the Julian date. For example, today would be Export_18309. There are additional numbers after 18309, but they are not relevant. With my current code "Export_" is a string and my date has been converted to an Int so that I can do math and increment it.

I set $dval to 18302 as a test case for files I was working with. I know it isn't currently deleting anything as I am outputting to a text file for manual verification before continuing. However, if the output of the text file isn't correct then there is no sense attempting the deletion.

My issue currenly is within the function WriteArch block of code. I am trying to combine a string and int to get PowerShell to display results that only begin with "Export_" and $dval as Export_$dval. I made that specific line of code the way it is to better portray what I am attempting.

Edit: The for loop within WriteArch is to increment 18302, to 18303, then 18304, etc as I am deleting files for the week prior to when the script is ran.

$path0 = 'U:\PShell\Testing\IBM3 Cleanup\logfiles'
$archLog = 'U:\PShell\Testing\IBM3 Cleanup\LogArchive.txt'

$day = (Get-Date).DayOfWeek
$date = (Get-Date).ToString("yy") + ((Get- 
Date).DayOfYear).ToString("D3") 
$dval = $date -as [Int]

$dval = Switch ($day) {
"Monday" { ($dval - 7); break }
"Tuesday" { ($dval - 8); break }
"Wednesday" { ($dval - 9); break }
"Thursday" { ($dval - 10); break }
"Friday" { ($dval - 11) }
}

Clear-Content $archLog

$dval = 18302

function WriteArch {
    param( $dval, $path0)
        for ($i = 0; $i -le 4; $i++) {
            Get-ChildItem -Path $path0|
            Where { $_.FullName -Match "Export_" + "$dval"}|
            Add-Content $archLog
            $dval++ 
        }
}

WriteArch $dval $path0

Invoke-Item $archLog

Upvotes: 2

Views: 1544

Answers (1)

G42
G42

Reputation: 10019

The Match operator supports regex. I think that's a bit overkill for the scenario you describe - I suggest using Like. The * is essential as it tells PowerShell there's more to the name after what you have specified.

Fullname contains the full path, including parent directories etc - it sounds like you want to base the match on BaseName, which the the file name excluding extension.

Where { $_.BaseName -like "Export_$dval*"}

Putting the $dval variable in quotes forces PowerShell to implicitly convert the int to string.

Comparison operators documentation, a good reference.

Upvotes: 2

Related Questions