微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我尝试访问 Powershell 中的注册表项时,为什么 OpenSubKey() 方法返回 null?

如何解决当我尝试访问 Powershell 中的注册表项时,为什么 OpenSubKey() 方法返回 null?

我正在尝试通过读取路径 Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows 下的注册表项 Device 来制作一个返回远程 pc 列表的认打印机的脚本。 我的代码中的问题似乎出在返回 null 的方法 OpenSubKey 中,因此方法 GetValue 失败。 注册表项的路径应该是正确的。

$Workstations=Import-Csv -Path C:\Users\mmarinari\Downloads\pclist2.csv -Header "PcName"

Remove-job *
foreach($workstation in $Workstations) {
    Out-File  -FilePath $logpath -InputObject $workstation.PcName -Append
    Write-Output $workstation.PcName
    $Reg=$null
    $remotereg=Get-Service -ComputerName $workstation.PcName -Name RemoteRegistry
    if($remotereg.Status -ne "Running"){
        Get-Service -ComputerName $workstation.PcName -Name RemoteRegistry | Set-Service -StartupType Manual -Passthru| Start-Service
        Write-Output "Service Started"
    }
    $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('CurrentUser',$workstation.PcName)
    If($Reg -eq $null){
        Write-Output "Reg is null"
    }
    else{
        
            $RegKey= $Reg.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows")
            $DefaultPrinter = $RegKey.GetValue("Device")
            Write-Output $DefaultPrinter  
            $RegKey.dispose()    
            
    }    
    $Reg.dispose()
}

我得到的错误如下:

    You cannot call a method on a null-valued expression.
At C:\Users\mmwa\Documents\ProgrammiVS\find_default_printer.ps1:28 char:13
+             $DefaultPrinter = $RegKey.GetValue("Device")
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [],RuntimeException
    + FullyQualifiedErrorId : InvokeMethodonNull

编辑:我为 Reg 和 RegKey 添加dispose 方法以及 $reg= $null 指令,但这并没有解决问题,错误已经在第一次迭代中发生了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。