Public/Get-FunctionCode.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
function Get-FunctionCode {
  <#
      .Synopsis
      Get the code of a powershell function or filter
      .EXAMPLE
      # Gets the code for New-Guid
      Get-FunctionCode New-Guid
      .EXAMPLE
      # Outputs the code for New-Guid into a new PowerShell ISE Tab
      Get-FunctionCode -Function New-Guid -OutISE
      .EXAMPLE
      # Gets the code for New-Guid and saves it to V:\temp\New-Guid.ps1
      Get-FunctionCode New-Guid -OutFile V:\temp\New-Guid.ps1
      .EXAMPLE
      # Outputs the code for New-Guid into a new PowerShell ISE Tab and saves it to V:\temp\New-Guid.ps1
      Get-FunctionCode -Function New-Guid -OutISE -OutFile V:\temp\New-Guid.ps1
  #>

  Param(
    # Function Name
    [Parameter(Mandatory)]
    [ValidateScript({
          if (-not (Get-Command -Name $_ -CommandType Function,Filter -ErrorAction SilentlyContinue)) {
            throw ('Cannot find function - {0}' -f $_)
          }
          return $true
    })]
    [String]$Function,
    [ValidateScript({
          if (-not ($psISE)) {
            throw ('{0}-OutISE can only be use within PowerShell ISE' -f ("`n"))
          }
          return $true
    })]
    [switch]$OutISE,
    [ValidateScript({
          if($_ | Test-Path -PathType Leaf) {
            throw 'File already exists'
          }
          return $true
    })]
    [string]$OutFile
  )
  Process {
    $CmdInfo = Get-Command -Name $Function -CommandType Function,Filter
    $FCode = '{0} {1} {3}{2}{4}' -f $CmdInfo.CommandType,$CmdInfo.Name,$CmdInfo.Definition,('{'),('}')
    $FCode = ($FCode.Split("`n") | ForEach-Object { $_ -replace '\s*$' }) -join "`n"
    if($OutISE) {
      $IseFile1 = $psISE.CurrentPowerShellTab.Files.Add()
      $IseFile1.Editor.Text = $FCode
      $IseFile1.Editor.SetCaretPosition(1,1)
      if($OutFile) {
        $IseFile1.SaveAs($OutFile,[System.Text.UTF8Encoding]::new($false))
      }
    }
    else {
      if($OutFile) {
        [System.IO.File]::WriteAllLines($OutFile,$FCode,[System.Text.UTF8Encoding]::new($false))
      }
      $FCode | Write-Output
    }
  }
}