> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/prog/powershell/looping.md).

# Looping

## Looping examples

Some looping examples with `%` an alias for `ForEach-Object`

```powershell
PS C:\> Get-Alias -Name %

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           % -> ForEach-Object
```

### Ping a given IP range

This example will ping IP-addresses from 10.0.2.1 to 10.0.2.15

```powershell
1..15 | % {Write-Output "10.0.2.$_"; ping -n 10.0.2.$_ | Select-String ttl}
```

### Simple port scanner

This example will scan ports 1-1024 on 10.10.30.55

```powershell
1..1024 | % {Write-Output ((New-Object Net.Sockets.TcpClient).Connect("10.10.30.55", $_)) "Open port on - $_"} 2>$null
```

## Resources

about\_Foreach - Microsoft Learn: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_foreach?view=powershell-5.1>
