PowerShell Start-Process loses precision on number passed as a string to a function

喜你入骨 提交于 2020-01-17 10:23:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/22519613/powershell-start-process-loses-precision-on-number-passed-as-a-string-to-a-funct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!