PowerShell登录脚本以记录Microsoft Office版本

时间:2019-02-07 19:33:40

标签: powershell

我遇到了PowerShell脚本,以在域上记录远程计算机的Microsoft Office版本。我想将其作为登录脚本运行,以将OpenRemoteBaseKey修改为OpenBaseKey,这是代码:

$version = 0
$reg = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', 'Default')

$reg.OpenSubKey('software\Microsoft\Office').GetSubKeyNames() |% {
  if ($_ -match '(\d+)\.') {
    if ([int]$matches[1] -gt $version) {
      $version = $matches[1]
    }
  }    
}

if ($version) {
    Add-Content -Path \\server\share\oversion.txt -Value "$env:computername $env:username : $version"
}
else {
    Add-Content -Path \\server\share\oversion.txt -Value "$env:computername $env:username : 0"
}

但现在我收到错误消息:

You cannot call a method on a null-valued expression.
At line:4 char:1
+ $reg.OpenSubKey('software\Microsoft\Office').GetSubKeyNames() |% {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

但不确定GetSubKeyNames的含义是什么:https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey.getsubkeynames?view=netframework-4.7.2,也可以与OpenRemoteBaseKey一起使用,请问有人可以向我指出正确的方向吗?

1 个答案:

答案 0 :(得分:0)

我不确定OpenRemoteBaseKey为何起作用,但是OpenBaseKey却不起作用,因为我无法复制它。.
但是,您可以尝试使用更多的Powershell方法:

$version = 0
Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\Office' -Name | Where-Object {$_ -match '(\d+)\.\d+'} | ForEach-Object {
    $version = [math]::Max([int]$_, $version)
}
Add-Content -Path \\server\share\oversion.txt -Value "$env:COMPUTERNAME $env:USERNAME : $version"