Modulus Operator

You can use the Modulus Operator ‘%’ in a few ways that can be very helpful depending on what you are trying to achive. Modulus can be thought of as a remainder when one number divides another. For instance 5 Mod 3 is 2 and 5 Mod 6 is 5.

 #5 Divided by 3 leaves a remainder of 2
5 % 3
2

#5 Divided by 6 leaves a remainder of 5
5 % 6
5

Find Multiples of x
To find multiples of a given number you can simply find all numbers in an array that have a remainder of 0 when divided by x

 $arr = {Array](1..100)
#Find all multiples of 3
$arr | ?{$_ % 3 -eq 0}

Find every xth item
When not working with numbers you can also use % to find every 2nd, 3rd, … xth item in an array by using $i as a counter. Bare in mind 0 is the first element of an array which can become confusing in this example

 #Get the first value and every xth value thereafter
$arr = 'one','two','three','four','five','six','seven','eight','nine','ten'
$i = 0
$x = 2
While ($i -lt $arr.Length){
    if(($i % $x) -eq 0){
        $arr[$i]
    }
    $i++
}

one
three
five
seven
nine

Base64 Encode/Decode

Using Get-Content you can convert a file such as .pdf or .jpeg into a stream of bytes. Here the ‘-raw’ switch tell Get-Content to read the file as one long string, keeping the line endings exactly as they were. Without this switch the file would be read line by line.

 $doc = Get-Content -Path C:\tmp\file.pdf -Raw -Encoding Byte 

Now you have the file content as Bytes saved as a variable (from the console you will see a decimal representation of a byte on each line). You can convert these bytes to binary or you can convert this entire variable into a Base64 string that can be sent in a file or copy-pasted.

Base64 makes a better transport option than binary (https://en.wikipedia.org/wiki/Base64)

#Just for fun really
$DocAsBin = $a | %{[System.Convert]::ToString($_,2)}

#Converts to a single transportable string
$DocAsStr = [Convert]::ToBase64String($doc)

To reassemble the file you will need to convert back from Base64 string and use the Set-Content cmdlet.

 
[System.Convert]::FromBase64String($DocAsStr) | Set-Content -Path C:\tmp\file.pdf​ 

You can also encode and run a script block in much the same way


$string = {(Get-WindowsFeature).Where{$PSItem.Installed}}.ToString()

$encodedcommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($string))

powershell.exe -EncodedCommand $encodedcommand