0

我正在尝试使用 powershell 从服务器获取远程注册表值。

我在网上找到了一些对我有用的代码:

$strComputer = "remoteComputerName"    
$reg = [mcrosoft.win32.registryKey]::openRemoteBaseKey('LocalMachine',$strComputer)
$regKey = $reg.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion")
$regKey.getValue("ProgramFilesDir")

但是当我尝试把它放在一个函数中时:

$strComputer = "remoteComputerName"

function getRegValue {
    param($computerName, $strPath, $strKey)
    $reg = [mcrosoft.win32.registryKey]::openRemoteBaseKey('LocalMachine',$computerName) #Errors out here
    $regKey = $reg.OpenSubKey($strPath)
    $regKey.getValue($strKey)
}

$a = "Software\\Microsoft\\Windows\\CurrentVersion"
$b = "ProgramFilesDir"
getRegValue($strComputer, $a, $b)

错误:

Exception calling "OpenRemoteBaseKey" with "2" argument(s): "The endpoint format is invalid."

我究竟做错了什么?

4

2 回答 2

3

您应该按如下方式调用您的函数,因为当前格式会导致问题。

getRegValue $strComputer $a $b
于 2013-03-01T16:04:54.147 回答
1

为避免此类问题,您可以使用 PowerShell 的严格模式。当遇到不正确的语法(您的函数调用就是这种情况)时,此选项会引发异常。

function someFunction{
param($a,$b,$c)
Write-host $a $b $c
}

> someFunction("param1","param2","param3")
> # Nothing happens

> Set-strictmode -version 2
> someFunction("param1","param2","param3")

The function or command was called as if it were a method. Parameters should
be separated by spaces. For information about parameters, see the
about_Parameters Help topic.
At line:1 char:1
+ someFunction("param1","param2","param3")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : StrictModeFunctionCallWithParens
于 2013-03-01T18:14:09.600 回答