0

I am attempting to get remote registry values from a server using powershell.

I found some code online that worked for me:

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

but when I try to put it in a function:

$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)

errors out:

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

What am I doing wrong?

2
  • Get rid of the parens and the commas when you call the function. Commented Mar 1, 2013 at 15:59
  • I feel foolish... Thanks Commented Mar 1, 2013 at 16:30

2 Answers 2

3

You should call your function as follows as the current format is causing the issue.

getRegValue $strComputer $a $b
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is correct. To clarify: When you call a function in PowerShell, don't use parentheses or separate the parameters with commas.
1

To avoid this type of issue, you can use PowerShell's strictmode. This option throws exceptions when encountering improper syntax (which is the case for your function call).

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.