PoshCode Archive  Artifact [5b00d867ba]

Artifact 5b00d867ba67d98a83536d8f5bad81686868b31bc9a3addcb38798ff9502c002:

  • File ConvertTo-Function.ps1 — part of check-in [77947463ab] at 2018-06-10 14:25:07 on branch trunk — This script takes a path to a script (full or relative), a fileinfo object, or either as pipeline input. It converts the script’s content to a function of the same name as the file. For example, ./ConvertTo-Function Get-Server.ps1 would create a function called Get-Server. If the function already exists, it will replace it with the new script. (user: unknown size: 1587)

# encoding: ascii
# api: powershell
# title: ConvertTo-Function
# description: This script takes a path to a script (full or relative), a fileinfo object, or either as pipeline input.  It converts the script’s content to a function of the same name as the file.  For example, ./ConvertTo-Function Get-Server.ps1 would create a function called Get-Server.  If the function already exists, it will replace it with the new script.
# version: 0.1
# type: function
# license: CC0
# x-poshcode-id: 849
# x-archived: 2009-02-08T14:59:12
#
#
## ConvertTo-Function
## By Steven Murawski (http://www.mindofroot.com / http://blog.usepowershell.com)
###################################################################################################
## Usage:
## ./ConvertTo-Function Get-Server.ps1 
## dir *.ps1 | ./convertto-Function
###################################################################################################
param ($filename)

PROCESS
{
	if ($_ -ne $Null)
	{
		$filename = $_
	}
	
	if ($filename -is [System.IO.FileInfo])
	{
		$filename = $filename.Name
	}
	
	if (Test-Path $filename) 
	{	
		
		$name = (Resolve-Path $filename | Split-Path -Leaf) -replace '\.ps1'	
		
		$scriptblock = get-content $filename | Out-String
		
		if (Test-Path function:global:$name)
		{
			Set-Item -Path function:global:$name -Value $scriptblock 
			Get-Item -Path function:global:$name
		}
		else
		{
			New-Item -Path function:global:$name -Value $scriptblock
		}
	}
	else 
	{
		throw 'Either a valid path or a FileInfo object'
	}
}