Forum Discussion

D_Watson2185's avatar
D_Watson2185
Copper Contributor
Jan 01, 2020
Solved

newb question: why is a foreach Item different from a Get-Item Item?!?

Here's my simple function test script and two use case tests:         # test rig for new function function Test-FileNewerThanRefDate{ # return True if $vFile is new than $vRefDate, else re...
  • Joshua King's avatar
    Jan 20, 2020

    D_Watson2185 it looks like you're calling your function in two very different, but deceptively similar ways.

     

    First, let's take a closer look at the params on your function:

    param(
        $vFile,
        [datetime] $vRefDate
    )


    So we're looking for two parameters, the first of which takes anything and the second should be a datetime (and if it isn't... PowerShell will try to cast it to one for you)

     

    In the sample that is working, you're passing the the variables to each of those parameters:

    Test-FileNewerThanRefDate (Get-Item $vTestCase -Force) $TestRefDate

     

    Or seen another way, that's:

    Test-FileNewerThanRefDate $vFile $vRefDate

     

    The second, failing sample is different:

    Test-FileNewerThanRefDate($vItem, $TestRefDate)

     

    What this actually doing is bundling up the two parameters as one, so both $vItem & $TestRefDate are being past to the function's vFile parameter as one "Object"

     

    The "quick fix" is to change it to not use those parentheses and especially the comma:

    Test-FileNewerThanRefDate $vItem $TestRefDate

     

    This still doesn't sit well with me, as it relies on positioning and makes the function less maintainable later (e.g. adding a new parameter would break existing scripts that rely on it.) The better option is to specify the parameters by name:

    Test-FileNewerThanRefDate -vRefDate $TestRefDate -vFile $vItem

     

    Note, this allowed me to put the date first, and it still works.

Resources