2

我有下面的脚本,我一生都无法理解为什么它给了我“你不能在空值表达式上调用方法”。它在两个地方出错。

Which computer?: NFDW2206
What is the AssetID?: 00000007
Checking NFDW2206 to see if the Registry Key exists..
You cannot call a method on a null-valued expression.
At \\NFDNT007\Dept\Corporate\IT\Network Services\Documentation\Asset Tag.ps1:11 char:33
+         $regassetid = $regKey.GetValue <<<< ("AssetID")
    + CategoryInfo          : InvalidOperation: (GetValue:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

The Key does not exist. Writing AssetID.....
You cannot call a method on a null-valued expression.
At \\NFDNT007\Dept\Corporate\IT\Network Services\Documentation\Asset Tag.ps1:18 char:20
+             $regKey.Setvalue <<<< ('AssetID', $AssetID, 'String')
    + CategoryInfo          : InvalidOperation: (Setvalue:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

代码如下

$Computer = Read-Host "Which computer?"
$AssetID = Read-Host "What is the AssetID?"

if (($Computer -eq "") -or ($AssetID -eq "")) {
    Write-Host "Error: A blank parameter was detected" -BackgroundColor Black -ForegroundColor Yellow
} else {
    if (Test-Connection -comp $Computer -count 1 -quiet) {
        Write-Host "Checking $Computer to see if the Registry Key exists.."
        $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $Computer)
        $regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield")
        $regassetid = $regKey.GetValue("AssetID")

        if ($regassetid -eq $null) {

            Write-Host "The Key does not exist. Writing AssetID....."
            $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $Computer)
            $regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield",$True) ## $True = Write
            $regKey.Setvalue('AssetID', $AssetID, 'String')

        } else {

            $OverWrite = Read-Host "AssetID exists do you wish to continue?"

            if (($OverWrite -eq "y") -or ($OverWrite -eq "yes")) {
                $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer)
                $regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield",$True) ## $True = Write
                $regKey.Setvalue("AssetID", $AssetID, "String")
            }

        }
    } else {
        Write-Host "Error: $computer is offline..." -BackgroundColor Black -ForegroundColor Yellow
    }
}
4

1 回答 1

1

文档说,如果操作失败,OpenSubKey 将返回 null。很可能是找不到钥匙。远程系统是 64 位操作系统吗?如果是这样,则可能是您遇到了注册表虚拟化问题。可能需要往下看SOFTWARE\WOW6432Node\Multek Northfield

于 2012-06-21T19:35:35.360 回答