gpt4 book ai didi

powershell - 传入空集会引发错误

转载 作者:行者123 更新时间:2023-12-02 15:28:43 25 4
gpt4 key购买 nike

我正在尝试根据 this 在我的 powershell 脚本中使用 HashSet回答。

Add-Type -AssemblyName System.Core
$set= new-object 'System.Collections.Generic.HashSet[string]'

但是如果我创建一个需要这样一个集合的函数

function foo([Parameter(Mandatory=$true)][Collections.Generic.HashSet[string]]$set){

并传入集合

foo($set)

如果 $set 为空,我会得到一个错误:

Cannot bind argument to parameter '$set' because it is an empty collection.
+ CategoryInfo : InvalidData: (:) [script.ps1], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyCollectionNotAllowed,script.ps1

但如果我事先向 $set 添加一些内容,我就不会遇到问题。

为什么参数不能绑定(bind)到一个空集,我怎样才能让它绑定(bind)到这样一个集?

最佳答案

您可以使用 AllowEmptyCollection 属性将函数标记为允许空 HashTable:

function foo([Parameter(Mandatory=$true)][AllowEmptyCollection()][Collections.Generic.HashSet[string]]$set)

关于powershell - 传入空集会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28973524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com