Skip navigation

Save Your PowerShell Code in Profile and Script Files

The final lesson in the PowerShell 201 series explores how to make PowerShell code last for more than just one session

Executive Summary:
In this final lesson of the PowerShell 201 series, you'll learn how to create profile files and script files in Windows PowerShell and how to add PowerShell statements to them. You'll also learn how to access the code in profile and script files from the console and how to use input parameters in script files. With this foundation, you'll be able to create PowerShell code that meets your specific needs and that will ultimately streamline the steps necessary to perform a wide variety of administrative tasks.

In Windows PowerShell, any functions, variables, or other language elements that you defined during your session will be lost when you exit the PowerShell console. However, that doesn't have to be the case. You can use profile files and script files to save your code. Profile files make the code available whenever you start PowerShell, whereas script files make the code available on demand.

I'll walk you through how to create both types of files and how to add PowerShell statements to them. I'll also show you how to access the code in profile and script files from the console and how to use input parameters in script files. With this foundation, you'll be able to create code that meets your specific needs and that will ultimately streamline the steps necessary to perform a wide variety of administrative tasks.

Creating a Profile File

A profile file is a text file with a specific name and path, both of which are predefined by PowerShell. When you start PowerShell, it reads existing profile files and loads their code into memory. Any code you define in a profile file is available to you during your sessions. For example, if a profile file includes a function, you can call that function from the PowerShell console without having to enter that function's code.

You must create your own profile file. The easiest way to do this is to take advantage of PowerShell's built-in $profile variable. This variable stores the fully qualified pathname of the current user's individual profile file. The variable is predefined with this information whether or not a profile file has been created. You can view the $profile value by running the command

$profile

The exact path stored in $profile will vary depending on the user and the OS. For example, in Windows Vista, the path will look similar to C:\Users\user1\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1. In Windows XP, the path will look similar to C:\Documents and Settings\user1\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.

To create a profile file with the $profile variable, you need to use the New-Item cmdlet and specify $profile as the -path parameter's value, as in

New-Item -path $profile `
  -itemType file -force

This command specifies file as the -itemType value and includes the -force parameter, which overrides certain existing restrictions when creating the file. For example, if the file already exists, the -force parameter will overwrite the existing file.

After you create the file, you can open it by calling Notepad from within PowerShell with the code

Notepad $profile

When you run this command, Notepad opens and displays a blank file. You can then add PowerShell statements to the file. Note that if you run this command and the file doesn't exist, you'll receive an error saying that system can't find the path specified.

Adding Content to a Profile File

To add content to a profile file, you simply enter the statements as you would enter them in the PowerShell console. For example, you can define a variable such as

# Retrieve day and date.
$today = Get-Date -displayHint date

The $today variable retrieves the current day and date. When adding code to a profile file, it's always good practice to include comments that specify the purpose of the code, like the comment shown here (the line preceded by the number sign). PowerShell ignores any lines preceded by a number sign.

You can add as many statements as necessary to your profile. For example, you can include the function

# Retrieve 10 most recent events.
function events ($log="system")
\{
  Get-EventLog $log -newest 10
\}

The events function retrieves the most recent 10 events in the specified log. If you don't specify a log as an input parameter when you call the function, it retrieves events from the System log. (For information about user-defined functions, see "Create Your Own PowerShell Functions." After you finish entering statements in the profile file, save it and close Notepad. Figure 1 shows a sample profile file.

Figure 1: Adding the $today variable and the events function to the profile file

To use the profile file, you must restart your PowerShell session. However, before you do so, you should verify PowerShell's current execution policy. The execution policy determines whether a script file can run—and a profile file is a type of script file. Script files and profile files are text files with a .ps1 extension. By default, PowerShell sets its execution policy to Restricted, which means that script files will not run and profile files will not load.

To verify the current execution policy, run the command

Get-ExecutionPolicy

If PowerShell returns a setting of Restricted, as Figure 2 shows, you can use the Set-ExecutionPolicy cmdlet to change the execution policy. Before you decide which execution policy to use, see PowerShell's About Signing and Execution Policies Help file to view details about the four different policies. Once you decide on the policy, you can run a command such as

Set-ExecutionPolicy RemoteSigned

This command sets the execution policy to RemoteSigned. After you set the policy, you can run the Get-ExecutionPolicy cmdlet again to verify that the change was made, as shown in Figure 2.

Figure 2: Setting the execution policy

After you set the execution policy, close and reopen PowerShell to start a new session in order for the profile to be loaded and the code to take effect. In the new session, you can access the variable and function as you would if you had created them at the console. For example, to access the $today variable, you enter the variable's name in the console like this

$today

Figure 3 shows the type of results you can expect from this command.

Figure 3: Accessing the $today variable and events function in the profile file

You can also call the events function, which requires an event log name as an input parameter, as in

events "windows powershell"

PowerShell calls the function, passes in the parameter value, and returns the results, as shown in Figure 3. As you can see, profiles provide a useful way for storing code. To learn more about profile files, see the "Getting Started" guide that's included with the PowerShell installation.

Creating a Script File

When you add code to a profile file, PowerShell runs that code whenever you open the console. Although this might be useful for functions and variables, it's not very useful for code whose execution you want to control. For example, you might want to run a script that retrieves data about services running on multiple computers on the network, but you wouldn't want this script to run each time PowerShell starts. In such cases, you can save the code in a script file, then run that file from the PowerShell console when necessary.

As I mentioned previously, script files are text files with a .ps1 extension. To create a script file, you need to create a new text file in Notepad, add the code you want to run, and save the file with the .ps1 extension. For example, you might add code such as

# Retrieve running services.
Get-Service |
  where \{$_.Status -eq 'running'\} |
  sort -property DisplayName

to a file in Notepad and save it as Services.ps1 in the C:\PSscripts folder. Services.ps1 retrieves a list of running services and sorts them by their display names.

Before you run Services.ps1 (or any other script file) for the first time, you should use the Get-ExecutionPolicy cmdlet to make sure that PowerShell's execution policy allows you to run a script file. Once confirmed, you can call Services.ps1 by entering its entire pathname, as in

C:\PSscripts\Services.ps1

That's all there is to it. The script file will run and return results like those shown in Figure 4.

Figure 4: Running a script file

Note that you can also call a script file by dragging it from Windows Explorer to the PowerShell console. After you drag the script file to the console, press Enter to run it. Another way to run it is to change the current working directory to the directory where the script file is located with a command such as

Set-Location C:\PSscripts

then run the script file with statement

.\Services.ps1

The period before the backslash tells PowerShell to use the current working directory.

Adding Input Parameters to a Script File

Like functions, script files can have input parameters. Input parameters let you pass values to a script file when you call it. To add input parameters, you must add a param statement to your script file. For example, to narrow the list of services that Services.ps1 retrieves, you can add a param statement to the script file, as in

# Retrieve running services.
param ($service="*windows*")
Get-Service -DisplayName $service |
where \{$_.Status -eq 'running'\} |
sort -property DisplayName

As the second line shows, a param statement begins with the param keyword, followed by one or more parameters in parentheses. (You should separate multiple parameters with commas.) You can also define your input parameters with default values, as I've done here. PowerShell allows wildcards in parameter values.

Now if you want to call Services.ps1, you enter its full pathname and the desired parameter value, with a space between them, as in

C:\PSscripts\Services.ps1 *net*

Services.ps1 will now return any running services whose display name includes the string net, as shown in Figure 5. If you don't include an input parameter, the script file will return running services whose display name includes the string windows.

Figure 5: Providing an input parameter value when running a script file

Although the code in Services.ps1 is basic, you can create complex script files that perform a variety of actions. And by being able to pass in parameter values, you can create a single script file that you can use in multiple environments and under different circumstances.

Take Advantage of PowerShell's Features

Profile and script files let you easily store the various commands and logic you need to perform a wide range of administrative tasks. Both types of files are easy to implement and maintain, and they can contain code that's as simple or complex as you need it to be. The more you work with PowerShell, the more useful you'll find both types of files. However, as is the case with any tool, these files are only as useful as your knowledge of the underlying technology, so the better you understand PowerShell and its language, the more effectively you can take advantage of profile and script files as well as any of the other powerful features in PowerShell.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish