PoshCode Logo PowerShell Code Repository

Get-Field by Andrew Savinykh 3 years ago (modification of post by Andrew Savinykh view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/2067"></script>download | new post

Displays private fields of passed object. This function is useful only if you want to want to see what is under the hood in powershell

  1. function Get-Field{
  2. [CmdletBinding()]
  3.         param (
  4.                 [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
  5.                 $InputObject,
  6.                 [Parameter(Position=1,Mandatory=$false)]
  7.                 [string]$Name,
  8.                 [switch]$Force,
  9.                 [switch]$AsHashtable
  10.         )
  11.        
  12.        
  13.         $publicNonPublic = [Reflection.BindingFlags]::Public -bor [Reflection.BindingFlags]::NonPublic
  14.         $instance = $publicNonPublic -bor [Reflection.BindingFlags]::Instance
  15.         $getField = $instance -bor [Reflection.BindingFlags]::GetField
  16.        
  17.        
  18.         $type = $InputObject.gettype()
  19.         $result = @()
  20.        
  21.         while ($type -ne [object] -and $type -ne [MarshalByRefObject] ) {
  22.                 $fields = $type.GetFields($instance)
  23.                 $result += $fields | Select-Object @{n="Name";e={$_.Name}},@{n="Value";e={$type.InvokeMember($_.Name, $getField, $null, $InputObject, $null)}}
  24.                 $type = $type.BaseType
  25.                 if (!$Force) { break; }
  26.         }
  27.        
  28.         if (!$Name) {
  29.                 if ($AsHashtable) {
  30.                         $hash = @{}
  31.                         $result | Foreach-Object {
  32.                                 $hash[$_.Name] = $_.Value
  33.                         }
  34.                         return $hash
  35.                 }
  36.                 else {
  37.                         return $result
  38.                 }
  39.         }
  40.         $result | ForEach-Object { if ($_.Name -eq $Name) { $_.Value } }
  41. }
  42.  
  43. New-Alias -Name gf -Value Get-Field -Force

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me