2013-03-01 32 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