I love that you can do so much with PowerShell on the fly. For example, I don’t need to launch a script editor to create a PowerShell function. I can do it right from the command prompt.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
PS C:\> function tm {(get-date).ToLongTimeString()}
PS C:\> tm
12:41:27 PM
As long as my PowerShell session is open, I can use the tm function. I can create as many other functions on the fly as I wish. Most of the time when I do this, the function is a throw-away. But occasionally I create a function from the command prompt that I’d like to keep. I can see that the function object has a definition:
PS C:\> dir function:tm
CommandType Name Definition
----------- ---- ----------
Function tm (get-date).ToLongTimeString()
All I need is a way to grab the definition and write it to a file. I may even want to write several functions to a single file or append the function to an existing file. Thus was born my Export-Function function.
Function Export-Function {
<#
.Synopsis
Export a PowerShell function to a file.
.Description
Get a Windows PowerShell function and export it to a file. You can export functions
individually, each to its own file, or you can export them to the same file using
-Append. By default the filename will be a PowerShell script file with the same
name as the function, but you can specify an alternate name. See examples.
.Parameter Name
The name of the function to export.
.Parameter Path
The folder for the exported function.
.Parameter Filename
The filename for the exported function. The default is the function name.
.Parameter Append
Write each function to the same file.
.Example
PS C:\> Export-Function "MyFunction"
This will export the MyFunction function to a script file called MyFunction.ps1.
.Example
PS C:\> dir function:*ISE* | Export-Function -path c:\export -filename ISEFunctions.psm1 -append
Get all functions with ISE in the name and export them to a module file C:\export\ISEFunctions.psm1
.Inputs
Strings for function names
.Outputs
None
.Link
About_Functions
Function (provider)
.Notes
VERSION: 1.0
This function supports cmdlet binding so you can use -Verbose and -Whatif.
#>
[cmdletbinding(SupportsShouldProcess=$True)]
Param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$True,
HelpMessage="Enter the name of a current function to export")]
[ValidateNotNullorEmpty()]
[string]$name,
[Parameter(Position=1,HelpMessage="Enter the folder to store the file.")]
[ValidateScript({Test-path $_})]
[string]$path="C:\scripts",
[Parameter(Position=2,
HelpMessage="Enter the name of the file to create. The default is the function name.")]
[ValidateNotNullorEmpty()]
[string]$filename="$name.ps1",
[switch]$append
)
Begin {
Write-Verbose "Starting $($myinvocation.mycommand)"
#initialize a counter
$i=0
}
Process {
#verify function exists
try {
$myfunction=Get-Command -Name $name -ErrorAction "Stop"
}
catch {
Write-Warning "Failed to find function $name"
Return
}
#function found so continue
if ($myFunction) {
#increment the counter by 1
$i++
#strip out illegal filename characters from function name
[regex]$r="[:/\\]"
if ($r.matches($filename)[0]) {
Write-Verbose "Removing illegal filename characters from $filename"
$r.matches($filename) | foreach {
$filename=$filename.replace($_.value,"")
}
} #if $r.matches
$filepath=Join-Path -Path $path -ChildPath $filename
#this command needs to be left justifie so the final result is nicely
#formatted
$output=@(
"{0} {1} {2}
{3}
{4} #end function
###############################################################################
" -f $myFunction.commandtype,$myFunction.name,"{",$myFunction.definition,"}")
if ($pscmdlet.ShouldProcess($name)) {
if ($append) {
write-Verbose "Exporting and appending to $filepath"
$output | Out-File -FilePath $filepath -Append
}
else {
Write-Verbose "Exporting $name to $filepath"
$output | Out-File -FilePath $filepath
}
} #if shouldprocess
} #if $myFunction
} #process
End {
Write-Verbose "Ending $($myinvocation.mycommand)"
Write-Host "Exported $i functions" -ForegroundColor Green
}
} #end function
Set-Alias -Name ef -Value Export-Function
This is an advanced PowerShell 2.0 function with complete help and examples. The script file that loads the function also defines an alias of ef.
By default Export-Function takes a function and creates a ps1 file using the function name as the file name. For example, to export my tm function
PS C:\> export-function tm
This will create a file called tm.ps1 in C:\Scripts. The function has a –Path parameter to specify the default folder. I’ve given it a default value of C:\scripts. You might want to change the default value.
Because a function might have characters in the name like :, which don’t make good file names, I use a regular expression object to strip them out of the filename. If you specify a filename, then the function names will be left alone. At the end of each function is a separator line of ######################################. This comes in handy when exporting a number of functions to the same file.
PS C:\> dir function:*firefox* | export-function -path c:\work -filename Firefox.psm1 –append
This will take all the functions in my current session with Firefox in the name and add them to a module file, c:\work\firefox.psm1. Very handy when you want to throw together a module. The function supports cmdlet binding so you can use –Verbose and –Whatif.
PS C:\> dir function:out* | export-function -whatif -verbose
VERBOSE: Starting Export-Function
What if: Performing operation "Export-Function" on Target "Out-Notepad".
What if: Performing operation "Export-Function" on Target "Out-MSWord".
What if: Performing operation "Export-Function" on Target "Out-Clip".
VERBOSE: Ending Export-Function
Exported 0 functions
As always, I hope you find this useful and will let me know what you think.
1 thought on “Export-Function”
Comments are closed.