PowerShell 减法是否在内部将 uint32 值转换为 int32?
当我想编写涉及两个 [unit32] 变量的减法脚本时,我收到警告“错误:“对于 Int32 来说值太大或太小。”
一个示例来说明我所看到的情况
$v1 = [uint32]([int32]::MaxValue + 1)
$v2 = [uint32]([int32]::MaxValue + 2)
$v2 - $v1
这是正常行为吗? 我怎样才能避免这个错误?
When I wanted to script a subtraction involving two [unit32] variables I got the warning "Error: "Value was either too large or too small for an Int32."
A sample to illustrate what I saw
$v1 = [uint32]([int32]::MaxValue + 1)
$v2 = [uint32]([int32]::MaxValue + 2)
$v2 - $v1
Is this normal behaviour ?
And how can I avoid the error ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的,这有点奇怪。但正确的写法如下,并且有效:
解释是
([int32]::MaxValue + 1)
是没有意义的。如果你分解你的第一个情感,你会发现它变成了双重情感。真正奇怪的是,如果你只添加一行,它就会再次起作用。
您可以使用 Cmdlet
Trace-Command
研究此类表达式:大多数情况下
Trace-Command
会提供更多信息。太平绅士
You are right it's a bit strange. But the correct way of writting it, is the following and it works :
The explanation is that
([int32]::MaxValue + 1)
is non sense. If you decompose your first affectation you can see a conversion into a double.The really strange thing is that if you just add a line it works again.
You can investigate such expression with the Cmdlet
Trace-Command
:Most of the time
Trace-Command
give more informations.JP
显然,PowerShell 的算术总是有符号的,并且确实在必要时不会转换为下一个更大的类型。作为解决方法,您可以使用
[long]
/[Int64]
:或者最初将变量声明为
[long]
。Apparently PowerShell's arithmetic is always signed and does not convert into the next larger type if necessary, indeed. As a workaround you can use
[long]
/[Int64]
:Or just declare your variables to be
[long]
initially.