Powershell parameter block accepting an array from [PSTypeName ("MyType")]

If I create an object with pstypename

, then I can apply parameters to the function as having this type, for example:

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 seems to be no way to tell what $Dependency

an array is NuGetDependency

. So if I want a function to execute multiple dependencies, I'm stuck.

What am I missing?

+3


source to share


2 answers


Looks like 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 will not allow an array composed of some NuGetDependency types and some other types. This is exactly what I wanted.

+5


source


Currently the ID and Version values ​​are concatenated because you are inserting an array into a string, for example:

$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

      

+1


source







All Articles