If I create an object with a pstypename
then I can enforce parameters to a function as being of that type, like so:
function New-NugetDependency{
Param(
[string]$Id,
[string]$Version
)
[PSCustomObject]@{
PSTypeName = "NuGetDependency"
ID = $ID
Version = $Version
}
}
and
function Show-NugGetDependency{
Param(
[PSTypeName("NuGetDependency")]$Dependency
)
Write-Host ("Dependency is " + $Dependency.id + " - " + $Dependency.Version)
}
However! There doesn't seem to be any way of saying that $Dependency
is an array of NuGetDependency
. So if I wanted the function to take in multiple dependencies then I'm stuck.
What am I missing?
Got there, I think.
Replacing the second function with this works:
function Show-NugGetDependency{
Param(
[PSTypeName("NuGetDependency")][object[]]$Dependency
)
foreach($DependencyItem in $Dependency){
Write-Host ("Dependency is " + $DependencyItem.id + " - " + $DependencyItem.Version)
}
}
And will allow an array that consists solely of NuGetDependency types. It won't allow an array that consists of some NuGetDependency types and some other types. Which is exactly what I wanted.
Right now the ID and Version-values are merged because you insert an array in the string, ex:
$dep = New-NugetDependency -Id ID1 -Version 1.0
$dep2 = New-NugetDependency -Id ID2 -Version 1.2
Show-NugGetDependency -Dependency $dep,$dep2
Dependency is ID1 ID2 - 1.0 1.2
You need to add a foreach-loop to separate the dependency-objects. Try:
function Show-NugGetDependency{
Param(
[PSTypeName("NuGetDependency")]$Dependency
)
foreach($d in $Dependency){
Write-Host ("Dependency is " + $d.id + " - " + $d.Version)
}
}
$dep = New-NugetDependency -Id ID1 -Version 1.0
$dep2 = New-NugetDependency -Id ID2 -Version 1.2
Show-NugGetDependency -Dependency $dep,$dep2
Dependency is ID1 - 1.0
Dependency is ID2 - 1.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With