使用不存在的变量或属性时,为什么没有Powershell输出错误?

时间:2017-03-06 15:40:50

标签: powershell

例如,如果我这样做:

class minion : public Enemy{ // This tells the compiler that the minion class is inherited from the Enemy class
public:
    int specialAttack(int x)
    {
        int attackPower = x;
        cout << "Take this you chump! " << attackPower + 6; 
    }
};

不产生错误,只产生新的命令提示符。

PS> foreach ($i in $list)
{
    Write-Host $i
}

即使在不存在的对象上调用属性,也不要输出任何错误:

PS>

新命令提示符

PS>(Get-SPWeb "http://homesite").Sites

但它应该是:

PS>

正确的结果:

PS>(Get-SPWeb "http://homesite").Site

1 个答案:

答案 0 :(得分:3)

因为这只是PowerShell实现的方式,但是有很多方法可以检查对象上的键。

Least Pedantic:

$s = Get-SPWeb "http://homesite"
if ($a.sites -eq $null) {Write-Error "Invalid Key used!"}

中等迂腐

$s = Get-SPWeb "http://homesite"
# gm is an alias for Get-Member
if (!($s | gm -MemberType Properties | % Name).contains("sites")) {Write-Error "Invalid Key used!"}

非常迂腐

{{1}}