Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 370
Andrew Ducker Avatar asked Apr 14 '17 15:04

Andrew Ducker


2 Answers

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.

like image 60
Andrew Ducker Avatar answered Nov 13 '22 01:11

Andrew Ducker


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
like image 1
Frode F. Avatar answered Nov 13 '22 02:11

Frode F.