2013-03-01 111 views
0

我试图从使用powershell的服务器获取远程注册表值。函数在Powershell中执行wmi查询时失败

我发现一些代码,在网上为我工作:

$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." 

什么我做错了吗?

+0

当您调用该函数时,请去掉parens和逗号。 – EBGreen 2013-03-01 15:59:35

+0

我觉得很愚蠢......谢谢 – Jeff 2013-03-01 16:30:27

回答

3

由于当前格式导致问题,因此应该按以下方式调用您的函数。

getRegValue $strComputer $a $b 
+0

这个回答是正确的。澄清:在PowerShell中调用函数时,请勿使用括号或用逗号分隔参数。 – 2013-03-01 16:08:03

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