在Powershell中执行wmi查询时函数失败

时间:2013-03-01 15:34:51

标签: powershell wmi

我试图使用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."

我做错了什么?

2 个答案:

答案 0 :(得分:3)

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

getRegValue $strComputer $a $b

答案 1 :(得分:1)

要避免此类问题,可以使用PowerShell的strictmode。 遇到不正确的语法时,此选项会抛出异常(对于函数调用就是这种情况)。

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