Powershell 陷阱 [英] Powershell pitfalls
本文介绍了Powershell 陷阱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您陷入了哪些 Powershell 陷阱?:-)
What Powershell pitfalls you have fall into? :-)
我的是:
# -----------------------------------
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
想知道你的,带他们四处走走:-)
Would like to know yours to walk them around :-)
推荐答案
我个人最喜欢的是
function foo() {
param ( $param1, $param2 = $(throw "Need a second parameter"))
...
}
foo (1,2)
对于那些不熟悉 powershell 的人,该行会抛出该行,因为它实际上创建了一个数组并传递了一个参数,而不是传递 2 个参数.你必须按如下方式调用它
For those unfamiliar with powershell that line throws because instead of passing 2 parameters it actually creates an array and passes one parameter. You have to call it as follows
foo 1 2
这篇关于Powershell 陷阱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文