gpt4 book ai didi

powershell - 测试函数空返回值

转载 作者:行者123 更新时间:2023-12-02 23:28:19 26 4
gpt4 key购买 nike

(编辑)一个空函数实际上确实返回了一个空值,这让我误入歧途,将问题留在这里作为提醒......

$null 没有削减它的地方。我的场景最简单地解释为一个片段,我有一个人写的函数

function PositiveInt([string]$value) { 
if ([int]($value) -ge 0) {[int]$value}
}

如果输入不是数字字符串,则在否定情况下不返回任何内容或抛出。在否定情况下如何测试返回?我试过这个
if ($null -eq (PositiveInt -1)) {
write-host "not positive :)"
}

但这显然行不通,因为没有返回值不等于 $null 。如何测试函数或表达式是否根本不返回任何内容?不要尝试修复我的人为函数,它缺少“$empty”(原文如此)我想对其进行测试,但不能因为 powershell 绑定(bind)不要求函数甚至表达式实际上返回任何东西?
# hacky unclear solution proposed
$temp = @(PositiveInt -1)
if ($temp.length -eq 0) {
write-host "not positive :)"
}

我从这篇 In Powershell what is the idiomatic way of converting a string to an int? 中获得了一些灵感张贴。但我想问一个不同的问题。
除了转换为数组的解决方法之外,还有更清洁的方法吗?

(编辑)必须承认某些环境或实际代码上下文在起作用,在 PS 5.1 中,函数调用返回 $null,正如@AnsgarWiechers 指出的那样。

最佳答案

您可以使用 -is or -isnot type operators检查结果是否成功转换为整数:

if( (PositiveInt '-1') -isnot [int] ) {
write-host 'negative'
}

关于powershell - 测试函数空返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26865164/

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