When you write a Powershell function how long does it last in memory. So I have developed a custom function and ran it to create the function, does this function remain on my machine permanently so all I need to do is call the function? If i turned my machine on and off and re-booted can I call the function etc. Does another user need to run the function first before they can use it?
-
What happened when you tried it? (Hint: save the text of the function before closing the PowerShell window or rebooting.) – Andrew Morton Jun 27 '19 at 09:50
-
[Loading custom functions in PowerShell](https://stackoverflow.com/questions/18764312/loading-custom-functions-in-powershell) may be of use to you. – Andrew Morton Jun 27 '19 at 09:53
2 Answers
The function exists only in the session where it's code is executed. As soon as you close the Powershell process it's gone. But you can just load up the function definition again and it's back. If you want to have a function in every powershell session available create a module and add it to you userprofile (here is how).
function foo {write-host "I am alife"}
foo

- 1,814
- 1
- 9
- 22
Powershell functions last as the powershell session itself, so when you define a function in the console, you can still call it as this console is running, once you close it, you will have to define the function again.
However, Powershell has specific scripts in the system that runs whenever Powershell session is started, these scripts are called Powershell profiles.
So in your case, if you put the function in Powershell profile, it will be defined directly when you open your Powershell session and it will be permanently defined.
Look here to see about powershell profile
This code will put your function in the profile:
New-Item -Type Directory -Path "$home/Documents/WindowsPowerShell"
"<Your Function Here>" | Out-File -Force -FilePath $profile.CurrentUserAllHosts
Now whenever you open a new Powershell console (or any powershell process runs), your function will be loaded (even after you reboot your system).
If you have a powershell file (.ps1) that contains many functions, you can simply copy its content to $Profile.CurrentUserAllHosts, or put this code in $Profile.CurrentUserAllHosts to import your file as Powershell starts.
Import-Module "<Your File (.ps1) Path Here>"
Update
I forgot to tell you that you have to change your Powershell privacy policy to unrestricted, otherwise you will get error telling you that running script is disabled on this system.

- 556
- 2
- 13