相关疑难解决方法(0)

Powershell陷阱

您遇到的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 …
Run Code Online (Sandbox Code Playgroud)

powershell

24
推荐指数
6
解决办法
4654
查看次数

当只有一个元素存在时,Jagged PowerShell数组会丢失一个维度

我有以下PowerShell功能,适用于任何输入,除了1.如果我传递它,它的输入1将返回一个包含两个元素的数组,1,1而不是一个元素,它本身就是一个包含两个元素的数组(1,1).

任何想法如何让PowerShell返回一个锯齿状数组,其中一个元素本身就是一个数组?

function getFactorPairs {
    param($n)
    $factorPairs = @()
    $maxDiv = [math]::sqrt($n)
    write-verbose "Max Divisor: $maxDiv"
    for($c = 1; $c -le $maxDiv; $c ++) {
        $o = $n / $c;
        if($o -eq [math]::floor($o)) {
            write-debug "Factor Pair: $c, $o"
            $factorPairs += ,@($c,$o) # comma tells powershell to add defined array as element in existing array instead of adding array elements to existing array
        }
    }
    return $factorPairs
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试,它的输出显示了问题.您可以看到第一个示例(1作为输入)返回的长度为2,即使找到了一个因子对.第二个例子(6为输入)工作正常,返回长度为2,找到两个因子对.

~» (getFactorPairs 1).length …
Run Code Online (Sandbox Code Playgroud)

.net arrays powershell

8
推荐指数
2
解决办法
1875
查看次数

标签 统计

powershell ×2

.net ×1

arrays ×1