Do you have a bunch of PowerShell functions in your arsenal that you use every now and then? Wouldn’t it be nice if those functions where readily available to you whenever you started PowerShell (or even better the PowerShell ISE)? Well good news – in this post I will show you a simple way to achieve just that.
It’s really rather simple and involves only a few steps:
1. Create a folder for your functions
First create the folder in which you will be storing your functions. In this post I am using a folder called “Functions” under the “My Documents\WindowsPowerShell” directory (feel free to substitute that with whatever folder you prefer)
mkdir "$env:USERPROFILE\Documents\WindowsPowerShell\Functions"
2. Store your functions in the folder
Save the functions in .ps1 files within the folder you created – to keep things simple I store each function in it’s own file (e.g a “Hello-World” function is stored in a “Hello-World.ps1” file) but you are not required to do so. You can call the files whatever you want (as long as they have the .ps1 extension) and you can place more functions within the same file if you please.
3. Add a few lines of PowerShell to your profile
The “Windows PowerShell” console and the “Windows PowerShell ISE” integrated scripting environment both load a profile at startup. The profile is actually just a PowerShell script, and you can easily add your own stuff to that file. The full path to your profile file is stored in the $profile variable. If nothing has been added to your profile already, the file itself might not exist, but the $profile variable will still point to the file.
Here’s a small snippet that will create the file for your if it does not exist, and then open it in notepad.exe. If you run it in the Windows PowerShell console it will open the console profile, if you run it in the Windows PowerShell ISE it will open the ISE profile.
if (!(Test-Path (Split-Path $profile))) { mkdir (Split-Path $profile) } ; if (!(Test-Path $profile)) { New-Item $profile -ItemType file } ; notepad $profile
Now that you have a profile file you can go ahead and add these few lines to the script which will “dot source” the PowerShell functions placed in your functions directory whenever you start PowerShell (replace the value of the $OwnFunctionsDir variable with the path to your functions folder)
# Load own custom functions at startup $OwnFunctionsDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Functions" Write-Host "Loading own PowerShell functions from:" -ForegroundColor Green Write-Host "$OwnFunctionsDir" -ForegroundColor Yellow Get-ChildItem "$OwnFunctionsDir\*.ps1" | %{.$_} Write-Host ''