gpt4 book ai didi

Powershell 陷阱

转载 作者:行者123 更新时间:2023-12-02 22:55:37 30 4
gpt4 key购买 nike

您陷入过哪些 Powershell 陷阱? :-)

我的是:

# -----------------------------------
function foo()
{
@("text")
}

# Expected 1, actually 4.
(foo).length

# -----------------------------------
if(@($null, $null))
{
Write-Host "Expected to be here, and I am here."
}

if(@($null))
{
Write-Host "Expected to be here, BUT NEVER EVER."
}

# -----------------------------------

function foo($a)
{
# I thought this is right.
#if($a -eq $null)
#{
# throw "You can't pass $null as argument."
#}

# But actually it should be:
if($null -eq $a)
{
throw "You can't pass $null as argument."
}
}

foo @($null, $null)

# -----------------------------------

# There is try/catch, but no callstack reported.
function foo()
{
bar
}

function bar()
{
throw "test"
}

# Expected:
# At bar() line:XX
# At foo() line:XX
#
# Actually some like this:
# At bar() line:XX
foo

想知道你的,以便带他们到处走走:-)

最佳答案

我个人最喜欢的是

function foo() {
param ( $param1, $param2 = $(throw "Need a second parameter"))
...
}

foo (1,2)

对于那些不熟悉 powershell 的人来说,该行会抛出异常,因为它实际上创建了一个数组并传递一个参数,而不是传递 2 个参数。您必须按如下方式调用它

foo 1 2

关于Powershell 陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/803521/

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