Home > Net >  How to save function in powershell?
How to save function in powershell?

Time:10-27

Hi so i've tried to make my first function. A simple one that will restart powershell in windows terminal. And it's working.

function Restart-PowerShell{
Get-Process -Id $PID | Select-Object -ExpandProperty Path | ForEach-Object { Invoke-Command { & "$_" } -NoNewScope }

But when i restart powershell the function disappear, it doesn't save it. How can i save it? I've tried to look around but couldn't find any way to save

CodePudding user response:

You save PowerShell functions by simply putting their definition in a file on disk:

"function Restart-PowerShell {${function:Restart-PowerShell}}" |Set-Content Restart-PowerShell.ps1

This will write it to a file Restart-PowerShell.ps1 in the current directory.

Next time you need to re-use your function, it's as simple as dot-sourcing the file:

PS ~> . .\path\to\Restart-PowerShell.ps1
PS ~> Restart-PowerShell # now the function is available in the current session

CodePudding user response:

Mathias R. Jessen's helpful answer shows how to save your function's definition to a custom file that you can dot-source on demand in future sessions.

However, there is a file that is dot-sourced automatically when a PowerShell session starts (unless explicitly suppressed with -NoProfile via the PowerShell CLI): your $PROFILE file, and that's where customizations of your sessions - such as custom functions and aliases - are typically stored.

Therefore, if you add your function to your $PROFILE file, it automatically becomes available in future sessions too.

You can open $PROFILE in your text editor or, building on Mathias' technique, add the function programmatically, as follows, which ensures on-demand creation of the file and its parent directory (on a pristine machine, neither exists):

# Make sure the $PROFILE file exists.
If (-not (Test-Path $PROFILE)) { $null = New-Item -Force $PROFILE }

# Append the function definition to it.
@"

function Restart-PowerShell { 
${function:Restart-PowerShell}
}
"@ | Add-Content $PROFILE

Note: To reload your profile mid-session after having modified $PROFILE, use . $PROFILE.

  • Related