Forum Discussion
newb question: why is a foreach Item different from a Get-Item Item?!?
- 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.
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.