PowerShell Start-Process在作为字符串传递给函数的数字上失去精度 [英] PowerShell Start-Process loses precision on number passed as a string to a function

查看:136
本文介绍了PowerShell Start-Process在作为字符串传递给函数的数字上失去精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以编辑注册表,因此需要以管理员身份运行.为此,我从正在运行的PowerShell脚本中启动了一个新的PowerShell进程,并传入了一部分注册表项路径,该路径恰好是版本号,例如"12.0".新PowerShell过程中的函数虽然接收的字符串为"12",而不是"12.0",所以我遇到了无法找到注册表项的错误.

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.

我创建了一个小示例powershell脚本来重现该问题.这是代码段:

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"")}"

在这里,我已经硬编码了"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.

推荐答案

好吧,经过一些试验,以下内容似乎可以正常工作:

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.

因此,事实证明我是一个假人,问题是我使用的是Cc语法Test(""$version"")而不是正确的PowerShell语法Test ""version""来调用该函数.通过此更改,它现在可以按预期运行.

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.

这篇关于PowerShell Start-Process在作为字符串传递给函数的数字上失去精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆