6

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?

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note: for anyone getting error The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input, ensure you've cast your hashtable to a pscustomobject when constructing your input value.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.