Powershell 参数 block 接受 [PSTypeName ("MyType")] 数组

标签 powershell types

如果我用 pstypename 创建一个对象然后我可以将参数强制为该类型的函数,如下所示:

function New-NugetDependency{
    Param(
        [string]$Id,
        [string]$Version
    )
    [PSCustomObject]@{
        PSTypeName = "NuGetDependency"
        ID = $ID
        Version = $Version
    }
}


function Show-NugGetDependency{
    Param(
        [PSTypeName("NuGetDependency")]$Dependency
    )
    Write-Host ("Dependency is " + $Dependency.id + " - " + $Dependency.Version)
}

然而!似乎没有任何方式可以说 $DependencyNuGetDependency 的数组.因此,如果我希望该函数接受多个依赖项,那么我就被卡住了。

我错过了什么?

最佳答案

到了那里,我想。

用这个工程替换第二个函数:

function Show-NugGetDependency{
    Param(
        [PSTypeName("NuGetDependency")][object[]]$Dependency
    )
    foreach($DependencyItem in $Dependency){
        Write-Host ("Dependency is " + $DependencyItem.id + " - " + $DependencyItem.Version)
    }
}

并且将允许只包含 NuGetDependency 类型的数组。它不允许包含一些 NuGetDependency 类型和一些其他类型的数组。这正是我想要的。

关于Powershell 参数 block 接受 [PSTypeName ("MyType")] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43414359/

相关文章:

powershell - 如何为要从提示符调用的 PowerShell 脚本设置别名?

powershell - 通过动态重定向到文件从另一个Powershell脚本内部运行Powershell脚本

powershell - 调试 Powershell 启动进程行

c++ - C++11 是否支持模板中的类型递归?

swift - 如何在 Swift 中从 Mirror 对象的子对象创建类的实例

c++ - vector 类型值不匹配错误

powershell - powershell 中的 vNext TFS 2015 QueryBuildDefinition 函数找不到我的构建定义

SQL Server十进制变量分配?

c++ - QVector 和 std::vector 的大小方法

powershell - 我的 DirectorySecurity 对象上的这个 "access"属性来自哪里?