PowerShell 2.0 中的位移位

Bit Shifting in PowerShell 2.0

左移 (-shl) 和右移 (-shr) 运算符仅适用于 PowerShell 3.0 及更高版本。

如何在 PowerShell 2.0 中转换?

这就是我目前所拥有的。有没有更好的方法?

>>>$x = 1
>>>$shift = 3
>>>$x * [math]::pow(2, $shift)
8
>>>$x = 32
>>>$shift = -3
>>>$x * [math]::pow(2, $shift)
4

不幸的是,您无法在 PowerShell (afaik) 中实现新的运算符,但您可以将操作包装在一个函数中:

function bitshift {
    param(
        [Parameter(Mandatory,Position=0)]
        [int]$x,

        [Parameter(ParameterSetName='Left')]
        [ValidateRange(0,[int]::MaxValue)]
        [int]$Left,

        [Parameter(ParameterSetName='Right')]
        [ValidateRange(0,[int]::MaxValue)]
        [int]$Right
    ) 

    $shift = if($PSCmdlet.ParameterSetName -eq 'Left')
    { 
        $Left
    }
    else
    {
        -$Right
    }

    return [math]::Floor($x * [math]::Pow(2,$shift))
}

这使 use 更具可读性:

PS> bitshift 32 -right 3
4
PS> bitshift 1 -left 3
8

我偶然发现了同样的问题,我想提供一些有用的信息:

PoSh2.0-BitShifting 创建一个 $Global:Bitwise 对象,该对象提供大部分按位运算。

使用示例(来自其自述文件):

PS C:\> Enable-BitShift
PS C:\> $Bitwise

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    PoShBitwiseBuilder                       System.Object


PS C:\> $Bitwise::Lsh(32,2)
128
PS C:\> $Bitwise::Rsh(128,2)
32