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

# PowerShell Reflection

Reflection in PowerShell enabled three main techniques

1. Type introspection: used if we want to determine all .NET assemblies that reference `System.Management.Automation.dll`, determine what classes and methods exist in an assembly or during .NET malware analysis
2. Overwriting member visibility: useful to borrow .NET code that isn't publicly accessible and editing internal properties or fields - with access to the reflection API, we have access to any field / property / method within a given class in PowerShell
3. Dynamic code invocation & generation (metaprogramming): used in .NET assembly in-memory loading & execution, dynamic .NET malware analysis and .NET malware re-purposing

We can use reflection for the following:

* type retrieval

```powershell
# type retrieval standard method
[System.Diagnostics.ProcessStartInfo]

# type retrieval reflection method
# referencing a known public class from the same assembly
# the full class name must be specified
[System.Diagnostics.Process].Assembly.GetType('System.Diagnostics .ProcessStartInfo')
```

* object instantiation

```powershell
# standard method
$ProcStartInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo -ArgumentList 'cmd.exe'

# reflection method #1
$ProcStartInfo = [Activator]::CreateInstance([System.Diagnostics.ProcessStartInfo], [Object[]] @('cmd.exe'))

# reflection method #2
$ProcessStartInfoStringConstructor = [System.Diagnostics.ProcessStartInfo].GetConstructor([Type[]] @([String]))
$ProcStartInfo = $ProcessStartInfoStringConstructor.Invoke([Object[]] @('cmd.exe'))
```

* method invocation

```powershell
# converting an Int32 to a hex string using the standard method
(1094795585).ToString('X8')

# reflection method
$IntToConvert = 1094795585
$ToStringMethod = [Int32].GetMethod('ToString', [Reflection.BindingFlags] 'Public, Instance', $null, [Type[]] @([String]), $null) $ToStringMethod.Invoke($IntToConvert, [Object[]] @('X8'))
```

Find out how to use if offensively with [PowerShell reflection offensive use-case](/red-teaming/notes/powershell/powershell-snippets/powershell-reflection-offensive-use-case.md).
