7

PowerShell 似乎在算术运算和转换之后执行边界检查。例如,以下操作失败:

[byte]$a = 255
$a++

$a = [byte]256

有没有办法强制溢出或类型转换,而无需通过模或 C# 和 Add-Type 进行手动计算?

4

2 回答 2

5

The behavior you want in PowerShell is achievable, though, it's a bit of a hack; and maybe there's a better way.

If you just want cryptographic functionality though, it's worth calling out, that there's a TON of that already built-in to the BCL, and it's fully accessible from PowerShell (MD5, SHA, RSA, X509, a ton of other stuff too).

But if you're dead set on performing unchecked arithmetic in PowerShell, this is a hack that should give you what you want (basically we're embedding C# code, and using the unchecked keyword):

$members = @' 
public static UInt32 ToUInt32(int value)
{
    unchecked
    {
        return (UInt32)value;
    }
}


public static byte ToByte(int value)
{
    unchecked
    {
        return (byte)value;
    }
}
'@;

$type = Add-Type -Name "Convert" -Namespace "Helpers" `
        -MemberDefinition $members -PassThru -ErrorAction SilentlyContinue;

Usage:

PS C:\Some\Folder> [Helpers.Convert]::ToUInt32(-1);
4294967295

PS C:\Some\Folder> [Helpers.Convert]::ToByte(-1);
255

PS C:\Some\Folder> [Helpers.Convert]::ToByte(256);
0

Of Note:

  • We're calling [Helpers.Convert]::To... and not [System.Convert]::To....
  • If you need other methods, the actual C# methods will need to be inserted into the $members block at the top of the code.
  • If you run Add-Type multiple times in a row for the same Namespace and Name combination, in the same PowerShell session, it will fail; and you will be left with the previously registered type. -- I've added -ErrorAction SilentlyContinue to ignore this specific scenario. -- That way, you can dump this code into a .ps1 script, and call it every single time, before you use them methods, and they will always be present. -- But if you are modifying the C# code and retesting, you will want to change the type name after every change you make; it's kind of painful.
于 2017-05-17T03:26:14.917 回答
1

PowerShell 是一种脚本语言,而不是编程语言,它不支持许多高级技术,例如重载运算符(在这种情况下会很方便)。

要添加到您已经建议的内容,您可以捕获错误。

[byte]$a = 255
try {$a++} catch {$a=1}

或者编写你自己的函数并在那里做一些模数的乐趣。

于 2013-03-31T21:47:28.773 回答