Question

I have some code that edits the registry, so it needs to run as admin. To do this, I start up a new PowerShell process from my running PowerShell script, and pass in part of the registry key path, which happens to be a version number, e.g. "12.0". The function in the new PowerShell process receives the string as "12" though, not "12.0", and so I'm getting errors that it can't find the registry key.

I've created a little sample powershell script that reproduces the problem. Here's the snippet:

$ScriptBlock = {
    function Test([string]$VisualStudioVersion)
    {
        $VisualStudioVersion    # This always displays 12, instead of 12.0
        $Host.UI.RawUI.ReadKey()
    }
}

# Run the script block's function.
Start-Process -FilePath PowerShell -ArgumentList "-Command & {$ScriptBlock Test(""12.0"")}"

Here I've hardcoded "12.0", but in practice I want to pass in a variable.

Any ideas on what I'm doing wrong? Thanks in advance.

Was it helpful?

Solution

Ok, after some experimenting the following seems to work correctly:

Start-Process -FilePath PowerShell -ArgumentList "-Command & {$ScriptBlock Test('12.0')}"

and it even works when using a variable:

$version = "12.0"
Start-Process -FilePath PowerShell -ArgumentList "-Command & {$ScriptBlock Test('$version')}"

I'm still not sure why using double quotes causes it to lose the precision and single quotes keeps it, but at least I solved my problem.

Update

So it turns out I'm a dummy and the problem was that I was using C# syntax of Test(""$version"") to call the function, instead of the proper PowerShell syntax Test ""version"". With this change it now works as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top