Changes

Windows PowerShell 1.0 Functions

2,381 bytes added, 14:59, 5 December 2008
Windows PowerShell Function Administration
PS C:\Users\Administrator> rm function:/filelengths
</pre>
 
== Loading Function Definitions from a Windows PowerShell Script File ==
 
Functions are not persistent across Windows PowerShell sessions. In other words, if you define a function from within the Windows PowerShell interactive shell environment and then exit the session, the function will no longer exist in future sessions. One way of quickly re-loading predefined functions is to place them into a script file and then load that script file from within the shell environment. The way this works isn't quite as most people might expect so this issue needs a little explanation. For the purposes of this description, we will create a simple function in a script file called ''myfunction.ps1'' as follows:
 
<pre>
function hello ($name)
{
if ($name -ne "Fred")
{
return "Sorry $name, I was looking for Fred!"
}
 
"Hello Fred!"
}
</pre>
 
Ordinarily, a script file is loaded and executed simply by referencing the name of the script at the PowerShell prompt. In fact, when this is performed, PowerShell executes the commands in the script and then discards any new settings, functions and variables once the script exists. So executing our ''myfunction.ps1'' script in the usual way isn't actually going to result in the new function being retained in the function namespace of the current session as illustrated below:
 
<pre>
PS C:\Users\Administrator> dir function:hello
Get-ChildItem : Cannot find path 'hello' because it does not exist.
At line:1 char:4
+ dir <<<< function:hello
</pre>
 
In order to have the settings, functions and variables from a script file retained, it is necessary to perform a task known as ''dotting'' the script file (also known as ''sourcing'' in the UNIX and Linux worlds). This is achieved by prefixing the script name with a dot and a space as follows:
 
<pre>
PS C:\Users\Administrator> . ./myfunction.ps1
PS C:\Users\Administrator> dir function:hello
 
CommandType Name Definition
----------- ---- ----------
Function hello param($name) if ($name -ne "Fred")...
</pre>
 
As illustrated above, the function is now retained in the Windows PowerShell session. This technique applies equally to variables and any other settings that may be included in a script file which is subsequently ''dotted''.