# Powershell

{% hint style="info" %}
Useful Websites:

* [Powershell Cheatsheet](https://www.comparitech.com/net-admin/powershell-cheat-sheet/)
* [Exchange/Teams/Compliance](https://practicalpowershell.com/powershellcheatsheets/)
* [Powershell Gallery](https://www.powershellgallery.com/)
  {% endhint %}

{% hint style="success" %}
Related Page:

* [powershell-cheatsheet](https://viceintelpro.gitbook.io/viceintelpro/powershell/powershell-cheatsheet "mention")
  {% endhint %}

Below is a table of Powershell Commands, and an encryption script.

## Powershell Commands

***

| Command                     | Description                                          | Example                                                               |
| --------------------------- | ---------------------------------------------------- | --------------------------------------------------------------------- |
| `Get-Help`                  | Displays information about PowerShell commands.      | Get-Help Get-Process                                                  |
| `Get-Command`               | Lists all available commands in PowerShell.          | Get-Command                                                           |
| `Get-ChildItem`             | Retrieves files and folders in a specified location. | Get-ChildItem C:\|                                                    |
| `Set-Location`              | Changes the current working directory.               | Set-Location D:\|                                                     |
| `Get-Content`               | Reads the content of a file.                         | Get-Content file.txt                                                  |
| `Out-File`                  | Writes output to a file.                             | Get-Process \| Out-File processes.txt                                 |
| `Write-Output`              | Sends output to the pipeline.                        | Write-Output “Hello, PowerShell!”                                     |
| `Select-Object`             | Selects specific properties of objects.              | Get-Process \| Select-Object Name, CPU                                |
| `Where-Object`              | Filters objects based on specified criteria.         | Get-Service \| Where-Object { $\_.Status -eq “Running” }              |
| `ForEach-Object`            | Performs an operation on each object in a pipeline.  | 1..5 \| ForEach-Object { $\_ \* 2 }                                   |
| `Format-Table`              | Formats output as a table.                           | Get-Process \| Format-Table -AutoSize                                 |
| `Sort-Object`               | Sorts objects by specified properties.               | Get-Service \| Sort-Object Status                                     |
| `Measure-Object`            | Calculates properties of objects (e.g., length).     | “Hello, PowerShell!” \| Measure-Object -Character                     |
| `New-Item`                  | Creates a new item (file, folder, etc.).             | New-Item newfile.txt -ItemType File                                   |
| `Remove-Item`               | Deletes an item.                                     | Remove-Item file.txt                                                  |
| `Copy-Item`                 | Copies files or folders.                             | Copy-Item file.txt newfolder                                          |
| `Rename-Item`               | Renames an item.                                     | Rename-Item file.txt newname.txt                                      |
| `Test-Path`                 | Checks if a file or folder exists.                   | Test-Path file.txt                                                    |
| `Get-Service`               | Retrieves services.                                  | Get-Service                                                           |
| `Start-Service`             | Starts a service.                                    | Start-Service serviceName                                             |
| `Stop-Service`              | Stops a service.                                     | Stop-Service serviceName                                              |
| `Restart-Service`           | Restarts a service.                                  | Restart-Service serviceName                                           |
| `Get-Process`               | Retrieves processes.                                 | Get-Process                                                           |
| `Start-Process`             | Starts a process.                                    | Start-Process notepad                                                 |
| `Stop-Process`              | Stops a process.                                     | Stop-Process -Name notepad                                            |
| `Get-WmiObject`             | Retrieves management information using WMI.          | Get-WmiObject Win32\_ComputerSystem                                   |
| `Get-EventLog`              | Retrieves event log data.                            | Get-EventLog -LogName Application                                     |
| `Get-Content`               | Reads the content of a file.                         | Get-Content file.txt                                                  |
| `Set-Content`               | Writes content to a file.                            | Set-Content file.txt “New content”                                    |
| `Test-Connection`           | Tests network connectivity.                          | Test-Connection google.com                                            |
| `Test-NetConnection`        | Comprehensive network connectivity test.             | Test-NetConnection google.com                                         |
| `Invoke-WebRequest`         | Performs HTTP requests.                              | Invoke-WebRequest [https://www.example.com](https://www.example.com/) |
| `ConvertTo-Json`            | Converts objects to JSON format.                     | Get-Process \| ConvertTo-Json                                         |
| `ConvertFrom-Json`          | Converts JSON data to objects.                       | ‘{“Name”:”John”,”Age”:30}’ \| ConvertFrom-Json                        |
| `Get-Date`                  | Retrieves the current date and time.                 | Get-Date                                                              |
| `New-Object`                | Creates a new object.                                | New-Object PSObject                                                   |
| `Get-Content`               | Reads the content of a file.                         | Get-Content file.txt                                                  |
| `Set-Content`               | Writes content to a file.                            | Set-Content file.txt “New content”                                    |
| `Invoke-Expression`         | Invokes a command or expression as if by typing it.  | Invoke-Expression ‘Get-Process’                                       |
| `Write-Host`                | Displays messages to the console.                    | Write-Host “Hello, PowerShell!”                                       |
| `Out-GridView`              | Displays data in a graphical table.                  | Get-Process \| Out-GridView                                           |
| `Out-Printer`               | Sends output to a printer.                           | Get-Process \| Out-Printer                                            |
| `Get-Host`                  | Retrieves host information.                          | Get-Host                                                              |
| `Get-Module`                | Lists the modules imported into the session.         | Get-Module                                                            |
| `Import-Module`             | Imports a module into the session.                   | Import-Module MyModule                                                |
| `Remove-Module`             | Removes imported modules from the session.           | Remove-Module MyModule                                                |
| `Get-Command`               | Lists available commands.                            | Get-Command                                                           |
| `Get-Alias`                 | Lists aliases.                                       | Get-Alias                                                             |
| `Set-Alias`                 | Creates or changes aliases.                          | Set-Alias np Notepad                                                  |
| `Clear-Host`                | Clears the console screen.                           | Clear-Host                                                            |
| `Clear-Content`             | Clears the content of a file.                        | Clear-Content file.txt                                                |
| `Clear-Item`                | Removes the content of an item.                      | Clear-Item file.txt                                                   |
| `Clear-Variable`            | Removes variable values.                             | Clear-Variable varName                                                |
| `Clear-RecycleBin`          | Clears the contents of the Recycle Bin.              | Clear-RecycleBin                                                      |
| `Compare-Object`            | Compares two sets of objects.                        | Compare-Object object1 object2                                        |
| `Complete-Transaction`      | Completes a transaction.                             | Complete-Transaction                                                  |
| `ConvertFrom-Csv`           | Converts CSV-formatted data to objects.              | Get-Content data.csv \| ConvertFrom-Csv                               |
| `ConvertTo-Csv`             | Converts objects to CSV format.                      | Get-Process \| ConvertTo-Csv -NoTypeInformation                       |
| `Debug-Process`             | Debugs a process.                                    | Debug-Process -Id processId                                           |
| `Disable-PSBreakpoint`      | Disables breakpoints.                                | Disable-PSBreakpoint -Id breakpointId                                 |
| `Enable-PSBreakpoint`       | Enables breakpoints.                                 | Enable-PSBreakpoint -Id breakpointId                                  |
| `Exit`                      | Exits the current session.                           | Exit                                                                  |
| `Export-Alias`              | Exports aliases to a file.                           | Get-Alias \| Export-Alias -Path aliases.txt                           |
| `Export-Clixml`             | Exports objects to an XML file.                      | Get-Process \| Export-Clixml process.xml                              |
| `Export-Csv`                | Exports objects to a CSV file.                       | Get-Process \| Export-Csv process.csv                                 |
| `ForEach-Object`            | Iterates through objects in the pipeline.            | 1..5 \| ForEach-Object { $\_ \* 2 }                                   |
| `Format-Custom`             | Formats output using a customized view.              | Get-Process \| Format-Custom                                          |
| `Format-Hex`                | Formats data as hexadecimal values.                  | Format-Hex 123                                                        |
| `Format-List`               | Formats output as a list of properties.              | Get-Process \| Format-List                                            |
| `Format-Table`              | Formats output as a table.                           | Get-Process \| Format-Table -AutoSize                                 |
| `Format-Wide`               | Formats output as a table with a single wide column. | Get-Process \| Format-Wide                                            |
| `Get-Acl`                   | Retrieves access control lists (ACLs).               | Get-Acl file.txt                                                      |
| `Set-Acl`                   | Sets access control lists (ACLs).                    | Set-Acl file.txt -AclObject $aclObj                                   |
| `Get-Alias`                 | Gets aliases.                                        | Get-Alias                                                             |
| `Get-AuthenticodeSignature` | Retrieves digital signatures.                        | Get-AuthenticodeSignature file.exe                                    |
| `Get-ChildItem`             | Retrieves items in a location.                       | Get-ChildItem C:\|                                                    |
| `Get-Clipboard`             | Retrieves the current clipboard contents.            | Get-Clipboard                                                         |
| `Get-Command`               | Gets commands.                                       | Get-Command                                                           |
| `Get-ComputerInfo`          | Retrieves computer information.                      | Get-ComputerInfo                                                      |
| `Get-Content`               | Retrieves the content of an item.                    | Get-Content file.txt                                                  |
| `Get-Credential`            | Retrieves stored credentials.                        | Get-Credential                                                        |
| `Get-Culture`               | Retrieves culture information.                       | Get-Culture                                                           |
| `Get-Date`                  | Retrieves the current date and time.                 | Get-Date                                                              |
| `Get-Event`                 | Retrieves events.                                    | Get-Event                                                             |
| `Get-History`               | Retrieves the command history.                       | Get-History                                                           |
| `Get-Host`                  | Retrieves host information.                          | Get-Host                                                              |
| `Get-HotFix`                | Retrieves installed hotfixes.                        | Get-HotFix                                                            |
| `Get-Item`                  | Retrieves items.                                     | Get-Item                                                              |
| `Get-ItemProperty`          | Retrieves property values of an item.                | Get-ItemProperty file.txt -Name Length                                |
| `Get-Job`                   | Retrieves background jobs.                           | Get-Job                                                               |
| `Get-Location`              | Retrieves the current location.                      | Get-Location                                                          |
| `Get-Member`                | Retrieves members of an object.                      | Get-Process \| Get-Member                                             |
| `Get-Module`                | Lists the modules imported into the session.         | Get-Module                                                            |
| `Get-OSVersion`             | Retrieves the operating system version.              | Get-WmiObject Win32\_OperatingSystem \| Select-Object Caption         |
| `Get-Process`               | Retrieves processes.                                 | Get-Process                                                           |
| `Get-Random`                | Generates random numbers.                            | Get-Random -Minimum 1 -Maximum 100                                    |
| `Get-Service`               | Retrieves services.                                  | Get-Service                                                           |
| `Get-Transaction`           | Retrieves transactions.                              | Get-Transaction                                                       |
| `Get-UICulture`             | Retrieves user interface culture information.        | Get-UICulture                                                         |
| `Get-Unique`                | Retrieves unique items.                              | Get-ChildItem \| Get-Unique                                           |
| `Get-FileHash`              | Retrieves hash of a file                             | Get-FileHash -Algorithm SHA256                                        |

## AESEncryption Script

***

Many different methods can be used to encrypt files and information on Windows systems. One of the simplest methods is the [Invoke-AESEncryption.ps1](https://www.powershellgallery.com/packages/DRTools/4.0.2.3/Content/Functions/Invoke-AESEncryption.ps1) PowerShell script. This script is small and provides encryption of files and strings.

Using this script: [File Encryption on Windows](app://obsidian.md/Protected%20File%20Transfers.md#File%20Encryption%20on%20Windows)

```powershell

<#
.SYNOPSIS
Encryptes or Decrypts Strings or Byte-Arrays with AES
 
.DESCRIPTION
Takes a String or File and a Key and encrypts or decrypts it with AES256 (CBC)
 
.PARAMETER Mode
Encryption or Decryption Mode
 
.PARAMETER Key
Key used to encrypt or decrypt
 
.PARAMETER Text
String value to encrypt or decrypt
 
.PARAMETER Path
Filepath for file to encrypt or decrypt
 
.EXAMPLE
Invoke-AESEncryption -Mode Encrypt -Key "p@ssw0rd" -Text "Secret Text"
 
Description
-----------
Encrypts the string "Secret Test" and outputs a Base64 encoded cipher text.
 
.EXAMPLE
Invoke-AESEncryption -Mode Decrypt -Key "p@ssw0rd" -Text "LtxcRelxrDLrDB9rBD6JrfX/czKjZ2CUJkrg++kAMfs="
 
Description
-----------
Decrypts the Base64 encoded string "LtxcRelxrDLrDB9rBD6JrfX/czKjZ2CUJkrg++kAMfs=" and outputs plain text.
 
.EXAMPLE
Invoke-AESEncryption -Mode Encrypt -Key "p@ssw0rd" -Path file.bin
 
Description
-----------
Encrypts the file "file.bin" and outputs an encrypted file "file.bin.aes"
 
.EXAMPLE
Invoke-AESEncryption -Mode Encrypt -Key "p@ssw0rd" -Path file.bin.aes
 
Description
-----------
Decrypts the file "file.bin.aes" and outputs an encrypted file "file.bin"
#>
function Invoke-AESEncryption {
    [CmdletBinding()]
    [OutputType([string])]
    Param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Encrypt', 'Decrypt')]
        [String]$Mode,

        [Parameter(Mandatory = $true)]
        [String]$Key,

        [Parameter(Mandatory = $true, ParameterSetName = "CryptText")]
        [String]$Text,

        [Parameter(Mandatory = $true, ParameterSetName = "CryptFile")]
        [String]$Path
    )

    Begin {
        $shaManaged = New-Object System.Security.Cryptography.SHA256Managed
        $aesManaged = New-Object System.Security.Cryptography.AesManaged
        $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
        $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
        $aesManaged.BlockSize = 128
        $aesManaged.KeySize = 256
    }

    Process {
        $aesManaged.Key = $shaManaged.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($Key))

        switch ($Mode) {
            'Encrypt' {
                if ($Text) {$plainBytes = [System.Text.Encoding]::UTF8.GetBytes($Text)}
                
                if ($Path) {
                    $File = Get-Item -Path $Path -ErrorAction SilentlyContinue
                    if (!$File.FullName) {
                        Write-Error -Message "File not found!"
                        break
                    }
                    $plainBytes = [System.IO.File]::ReadAllBytes($File.FullName)
                    $outPath = $File.FullName + ".aes"
                }

                $encryptor = $aesManaged.CreateEncryptor()
                $encryptedBytes = $encryptor.TransformFinalBlock($plainBytes, 0, $plainBytes.Length)
                $encryptedBytes = $aesManaged.IV + $encryptedBytes
                $aesManaged.Dispose()

                if ($Text) {return [System.Convert]::ToBase64String($encryptedBytes)}
                
                if ($Path) {
                    [System.IO.File]::WriteAllBytes($outPath, $encryptedBytes)
                    (Get-Item $outPath).LastWriteTime = $File.LastWriteTime
                    return "File encrypted to $outPath"
                }
            }

            'Decrypt' {
                if ($Text) {$cipherBytes = [System.Convert]::FromBase64String($Text)}
                
                if ($Path) {
                    $File = Get-Item -Path $Path -ErrorAction SilentlyContinue
                    if (!$File.FullName) {
                        Write-Error -Message "File not found!"
                        break
                    }
                    $cipherBytes = [System.IO.File]::ReadAllBytes($File.FullName)
                    $outPath = $File.FullName -replace ".aes"
                }

                $aesManaged.IV = $cipherBytes[0..15]
                $decryptor = $aesManaged.CreateDecryptor()
                $decryptedBytes = $decryptor.TransformFinalBlock($cipherBytes, 16, $cipherBytes.Length - 16)
                $aesManaged.Dispose()

                if ($Text) {return [System.Text.Encoding]::UTF8.GetString($decryptedBytes).Trim([char]0)}
                
                if ($Path) {
                    [System.IO.File]::WriteAllBytes($outPath, $decryptedBytes)
                    (Get-Item $outPath).LastWriteTime = $File.LastWriteTime
                    return "File decrypted to $outPath"
                }
            }
        }
    }

    End {
        $shaManaged.Dispose()
        $aesManaged.Dispose()
    }
}
```
