![](/img/trans.png)
[英]How to call a Scriptblock as a function parameter in Powershell
[英]Powershell conditionally add switch & parameter to function call
我正在使用具有可选开关的 function,但是在循环中,可能需要或不需要开关和相关值,具体取决于分页机制。
# basic function call
myFunction $someParam
# function call with pagination switch
myFunction $someParam -NextPageToken $theToken
理想情况下,这应该在循环中以更优雅的方式使用:
$theToken = ""
do{
$result = myFunction $someParam -NextPageToken $theToken # pagination switch should not be used on first call
$theToken = $result.next_page_token
}while($theToken -ne "")
但是如果使用没有值的开关,function 会抛出错误....
Powershell 是否仅在需要时才支持动态/有条件地添加开关和值,以便 function 调用仅在代码中使用一次?
使用哈希表来分解令牌:
$params = @{}
do{
$result = myFunction $someParam @params
$params = @{ NextPageToken = $result.next_page_token }
}while("" -ne $params['NextPageToken'])
在第一次迭代中,splatting table 将为空(即不会传递NextPageToken
参数),但后续运行会。
请参阅about_Splatting
帮助文件以了解有关对条件参数 arguments 使用 splatting 的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.