Home > Powershell > Appending a Function to a Powershell Profile

## Appending a Function to a Powershell Profile

Powershell profiles provide the opportunity to extend custom functionality either via the console or a scripting engine like PowerGui or the ISE.  They are normal PS scripts and end with a .ps1 file extension. Like all PS scripts they can be edited in notepad, ISE, PowerGUI (my favorite) or any other script\text editor.   Profiles can be used to import modules, such as ServerManager, Applocker, BestPractices or customized settings such as Aliases,Functions,etc..

Let’s take a look at the available modules for import on this machine.

Get-Module -ListAvailable

The box I’m running is Server 2008R2 and on a default install includes only 7 modules (or there about). I’ve installed the additional tools such as PSCX and the MSDN  PowershellPack , both of which have added extended the default list of modules.

When Powerhsell starts, it looks for the existence of 4 specific profiles and runs them in the following order with the end result being a sum total of all existing profile settings, unless there is a conflict and then the more specific profile setting takes precednece.

1. All Users, All Hosts
2. All Users – Powershell or ISE (depending which one is being used)
3. Current User, All Hosts
4. Current User – Powershell or ISE (depending which one is being used)

Profiles don’t exist by default and must be created and thier location is defined in the $Profile variable. I’ve created the below code to select only the Name and Path for the profiles.$Profile | Get-Member |?{$_.membertype -eq “note*”} | Select name,@{label=”Path”;e={$_.definition -replace  “^.+=”,””| Format-Table -autosize

The potential that lies in loading preconfigured profiles is endless and as a small example I’ve decided to create a Active Directory Logon Script that will determine if the CurrentUserCurrentHost profile exists and if not, will create it, and then continue to populate it with a simple function called Get-WMIClass.

If (!( Test-Path $Profile )) { New-Item$Profile  -Type  File  -Force
} Else  {
$A = Get-Content$Profile }

If (!( $A -Like "*Get-WMIClass*" )) {$Content = @(
"Function GET-WMIClass {"
'$NS="Root\CIMV2"' '$Class=$args[0]' 'Get-WMIObject -Namespace$NS -Class $Class' "}" )$Content | Add-Content \$Profile -Encoding  UTF8
}