functions/public/Export-FunctionToFile.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 64 65 66 67 68 69 70 |
Function Export-FunctionToFile { [cmdletbinding(SupportsShouldProcess)] [alias("etf")] [OutputType("none", "System.IO.FileInfo")] Param( [Parameter( Position = 0, Mandatory, ValueFromPipeline, HelpMessage = "Specify the name of a function loaded in your PowerShell session." )] [string]$Name, [Parameter(HelpMessage = "Specify the location for the new file.")] [ValidateScript({ Test-Path $_ })] [string]$Path = ".", [Parameter(HelpMessage = "Show the file result.")] [switch]$PassThru, [Parameter(HelpMessage = "Specify #Requires statements, including the #")] [ValidatePattern("^#[rR]equires")] [string[]]$Requires ) Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($MyInvocation.MyCommand)" } #begin Process { Try { $fun = Get-Item function:\$name -ErrorAction Stop } Catch { Throw "Can't find a loaded function called $Name." } if ($fun) { $value = @" $($requires -join "`n") <# $(Get-Date) This function was exported from $env:computername by $env:username. Feel free to delete this comment. #> Function $($fun.Name) { $($fun.Definition.Trim()) } #Close $($fun.name) "@ #parse out illegal filesystem characters from the name $Name = $Name -replace "[:\\\/\.]", "" $export = Join-Path -Path (Convert-Path $path) -ChildPath "$Name.ps1" Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Exporting $Name to $Export" Set-Content -Path $export -Value $value if ($PassThru -AND (-Not $WhatIfPreference)) { Get-Item -Path $export } } } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($MyInvocation.MyCommand)" } #end } #close Export-FunctionToFile |