about_Variables TOPIC about_Variables SHORT DESCRIPTION Describes how variables store values that can be used in Windows PowerShell. LONG DESCRIPTION You can store all types of values in Windows PowerShell variables. They are typically used to store the results of commands and to store elements that are used in commands and expressions, such as names, paths, settings, and values. A variable is a unit of memory in which values are stored. In Windows PowerShell, variables are represented by text strings that begin with a dollar sign ($), such as $a, $process, or $my_var. Variable names are not case-sensitive. Variable names can include spaces and special characters, but these are difficult to use and should be avoided. There are several different types of variables in Windows PowerShell. -- User-created variables: User-created variables are created and maintained by the user. By default, the variables that you create at the Windows PowerShell command line exist only while the Windows PowerShell window is open, and they are lost when you close the window. To save a variable, add it to your Windows PowerShell profile. You can also create variables in scripts with global, script, or local scope. -- Automatic variables: Automatic variables store the state of Windows PowerShell. These variables are created by Windows PowerShell, and Windows PowerShell changes their values as required to maintain their accuracy. Users cannot change the value of these variables. For example, the $PSHome variable stores the path to the Windows PowerShell installation directory. For more information, a list, and a description of the automatic variables, see about_Automatic_Variables. -- Preference variables: Preference variables store user preferences for Windows PowerShell. These variables are created by Windows PowerShell and are populated with default values. Users can change the values of these variables. For example, the $MaximumHistoryCount variable determines the maximum number of entries in the session history. For more information, a list, and a description of the preference variables, see about_Preference_Variables. WORKING WITH VARIABLES To create a new variable, use an assignment statement to assign a value to the variable. You do not have to declare the variable before using it. The default value of all variables is $null. For example: PS> $MyVariable = 1, 2, 3 PS> $path = "C:\Windows\System32" Variables are very useful for storing the results of commands. For example: PS> $processes = Get-Process PS> $Today = (Get-Date).date To display the value of a variable, type the variable name, preceded by a dollar sign ($). For example: PS> $MyVariable 1 2 3 PS> $Today Thursday, September 03, 2009 12:00:00 AM To change the value of a variable, assign a new value to the variable. The following examples displays the value of the $MyVariable variable, changes the value of the variable, and then displays the new value. PS> $MyVariable 1 2 3 PS> $MyVariable = "The green cat." PS> $MyVariable The green cat. To delete the value of a variable, use the Clear-Variable cmdlet or change the value to $null. PS> Clear-Variable -name MyVariable -or- PS> $MyVariable = $null To delete the variable, use the Remove-Variable or Remove-Item cmdlets. (These cmdlets are discussed later in this topic.) PS> remove-variable -name MyVariable PS> remove-item -path variable:\myvariable To get a list of all of the variables in your Windows PowerShell session, type: get-variable TYPES OF VARIABLES You can store any type of object in a variable, including integers, strings, arrays, hash tables, and objects that represent processes, services, event logs, and computers. Windows PowerShell variables are "loosely typed," which means that they are not limited to a particular type of object. A single variable can even contain a collection (an "array") of different types of objects at the same time. The data type of a variable, which is a .NET Framework type, is determined by the .NET types of the values of the variable. For example: PS> $a = 12 (System.Int32) PS> $a = "Word" (System.String) PS> $a = 12, "Word" (System.Int32, System.String) PS> $a = dir C:\Windows\System32 (Files and folders) You can use a type attribute and cast notation to ensure that a variable can contain only objects of the specified type or objects that can be converted to that type. If you try to assign a value of another type, Windows PowerShell tries to convert the value to its type. If it cannot, the assignment statement fails. To use cast notation, enter a type name, enclosed in brackets, before the variable name (on the left side of the assignment statement). The following example creates an $number variable that can contain only integers, a $words variable that can contain only strings, and a $dates variable that can contain only DateTime objects. PS> [int]$number = 8 PS> $a = "12345" (The string is converted to an integer.) PS> $a = "Hello" Cannot convert value "Hello" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:3 + $a <<<< = "Hello" + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException PS> [string]$words = "Hello" PS> $words = 2 (The integer is converted to a string.) PS> $words + 10 (The strings are concatenated.) 210 PS> [datetime] $dates = "09/12/91" (The string is converted to a DateTime object.) PS> $dates Thursday, September 12, 1991 12:00:00 AM PS> $dates = 10 (The integer is converted to a DateTime object.) PS> $dates Monday, January 01, 0001 12:00:00 AM USING VARIABLES IN COMMANDS AND EXPRESSIONS To use a variable in a command or expression, type the variable name, preceded by the dollar sign ($). If the variable name (and dollar sign) are not enclosed in quotation marks, or if they are enclosed in double quotation marks ("), the value of the variable is used in the command or expression. If the variable name (and dollar sign) are enclosed in single quotation marks, ('), the variable name is used in the expression. For example, the first command gets the value of the $profile variable, which is the path to the Windows PowerShell user profile file in the Windows PowerShell console. The second command opens the file in Notepad, and the third and fourth commands use the name of the variable in an expression. PS> $profile C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 PS> notepad $profile - or - PS> notepad "$profile" C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 PS> '$profile' $profile PS> 'Use the $profile variable.' Use the $profile variable. For more information about using quotation marks in Windows PowerShell, see about_Quoting_Rules. VARIABLE NAMES THAT INCLUDE SPECIAL CHARACTERS Variable names begin with a dollar sign. They can include alphanumeric characters and special characters. The length of the variable name is limited only by available memory. Whenever possible, variable names should include only alphanumeric characters and the underscore character (_). Variable names that include spaces and other special characters, are difficult to use and should be avoided. To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs Windows PowerShell to interpret the characters in the variable name literally. For example, the following command creates and then displays a variable named "save-items". C:\PS> ${save-items} = "a", "b", "c" C:\PS> ${save-items} a b c The following command gets the child items in the directory that is represented by the "ProgramFiles(x86)" environment variable. C:\PS> Get-childitem ${env:ProgramFiles(x86)} To refer to a variable name that includes braces, enclose the variable name in braces, and use the backtick (escape) character to escape the braces. For example, to create a variable named "this{value}is" with a value of 1, type: C:\PS> ${this`{value`}is} = 1 C:\PS> ${this`{value`}is} 1 VARIABLES AND SCOPE By default, variables are available only in the scope in which they are created. For example, a variable that you create in a function is available only within the function. A variable that you create in a script is available only within the script (unless you dot-source the script, which adds it to the current scope). You can use a scope modifier to change the default scope of the variable. The following expression creates a variable named "Computers". The variable has a global scope, even when it is created in a script or function. $global:computers = "Server01" For more information, see about_Scopes. SAVING VARIABLES Variables that you create are available only in the session in which you create them. They are lost when you close your session. To create the in every Windows PowerShell session that you start, add the variable to your Windows PowerShell profile. For example, to change the value of the $VerbosePreference variable in every Windows PowerShell session, add the following command to your Windows PowerShell profile. $VerbosePreference = "Continue" You can add this command to your profile by opening the profile file in a text editor, such as Notepad. For more information about Windows PowerShell profiles, see about_profiles. THE VARIABLE: DRIVE Windows PowerShell Variable provider creates a Variable: drive that looks and acts like a file system drive, but it contains the variables in your session and their values. To change to the variable: drive, type: set-location variable: (or "cd variable:") To list the items (variables) in the Variable: drive, use the Get-Item or Get-ChildItem cmdlets. For example: get-childitem variable: (or "dir" or "ls") To get the value of a particular variable, use file system notation to specify the name of the drive and the name of the variable. For example, to get the $PSCulture automatic variable, use the following command. get-item variable:\PSCulture Name Value ---- ----- PSCulture en-US For more information about the Variable: drive and the Windows PowerShell Variable provider, type "get-help variable". THE VARIABLE CMDLETS Windows PowerShell includes a set of cmdlets that are designed to manage variables. Cmdlet Name Description ----------- ----------- Clear-Variable Deletes the value of a variable. Get-Variable Gets the variables in the current console. New-Variable Creates a new variable. Remove-Variable Deletes a variable and its value. Set-Variable Changes the value of a variable. To get help for these cmdlets, type: "Get-Help ". VARIABLE SQUEEZING Windows PowerShell supports a simplified syntax for showing the contents of variables during variable assignment. To do this, wrap the variable assignment statement in parentheses. Typically, assigning and then displaying variable output requires two separate Windows PowerShell commands. But you can consolidate the two processes into one statement by using the variable squeezing technique. The following examples show the difference. # Assign the variable $ProcessList = Get-Process; # Display the variablefs contents $ProcessList; # Use variable squeezing to assign and output the variable ($ProcessList = Get-Process); SEE ALSO about_Automatic_Variables about_Environment_Variables about_Preference_Variables about_Profiles about_Quoting_Rules about_Scopes about_Automatic_Variables TOPIC about_Automatic_Variables SHORT DESCRIPTION Describes variables that store state information for Windows PowerShell. These variables are created and maintained by Windows PowerShell. LONG DESCRIPTION Here is a list of the automatic variables in Windows PowerShell: $$ Contains the last token in the last line received by the session. $? Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed. $^ Contains the first token in the last line received by the session. $_ Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline. $AllNodes This variable is available inside of a DSC configuration document when configuration data has been passed into it by using the -ConfigurationData parameter. For more information about configuration data, see "Separating Configuration and Environment Data" on Microsoft TechNet (http://technet.microsoft.com/library/dn249925.aspx). $Args Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block. When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name. In an event action, the $Args variable contains objects that represent the event arguments of the event that is being processed. This variable is populated only within the Action block of an event registration command. The value of this variable can also be found in the SourceArgs property of the PSEventArgs object (System.Management.Automation.PSEventArgs) that Get-Event returns. $ConsoleFileName Contains the path of the console file (.psc1) that was most recently used in the session. This variable is populated when you start Windows PowerShell with the PSConsoleFile parameter or when you use the Export-Console cmdlet to export snap-in names to a console file. When you use the Export-Console cmdlet without parameters, it automatically updates the console file that was most recently used in the session. You can use this automatic variable to determine which file will be updated. $Error Contains an array of error objects that represent the most recent errors. The most recent error is the first error object in the array ($Error[0]). To prevent an error from being added to the $Error array, use the ErrorAction common parameter with a value of Ignore. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). $Event Contains a PSEventArgs object that represents the event that is being processed. This variable is populated only within the Action block of an event registration command, such as Register-ObjectEvent. The value of this variable is the same object that the Get-Event cmdlet returns. Therefore, you can use the properties of the $Event variable, such as $Event.TimeGenerated , in an Action script block. $EventArgs Contains an object that represents the first event argument that derives from EventArgs of the event that is being processed. This variable is populated only within the Action block of an event registration command. The value of this variable can also be found in the SourceEventArgs property of the PSEventArgs (System.Management.Automation.PSEventArgs) object that Get-Event returns. $EventSubscriber Contains a PSEventSubscriber object that represents the event subscriber of the event that is being processed. This variable is populated only within the Action block of an event registration command. The value of this variable is the same object that the Get-EventSubscriber cmdlet returns. $ExecutionContext Contains an EngineIntrinsics object that represents the execution context of the Windows PowerShell host. You can use this variable to find the execution objects that are available to cmdlets. $False Contains FALSE. You can use this variable to represent FALSE in commands and scripts instead of using the string "false". The string can be interpreted as TRUE if it is converted to a non-empty string or to a non-zero integer. $ForEach Contains the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable. This variable exists only while the ForEach loop is running; it is deleted after the loop is completed. For detailed information, see about_ForEach. $Home Contains the full path of the user's home directory. This variable is the equivalent of the %homedrive%%homepath% environment variables, typically C:\Users\. $Host Contains an object that represents the current host application for Windows PowerShell. You can use this variable to represent the current host in commands or to display or change the properties of the host, such as $Host.version or $Host.CurrentCulture, or $host.ui.rawui.setbackgroundcolor("Red"). $Input Contains an enumerator that enumerates all input that is passed to a function. The $input variable is available only to functions and script blocks (which are unnamed functions). In the Process block of a function, the $input variable enumerates the object that is currently in the pipeline. When the Process block completes, there are no objects left in the pipeline, so the $input variable enumerates an empty collection. If the function does not have a Process block, then in the End block, the $input variable enumerates the collection of all input to the function. $LastExitCode Contains the exit code of the last Windows-based program that was run. $Matches The $Matches variable works with the -match and -notmatch operators. When you submit scalar input to the -match or -notmatch operator, and either one detects a match, they return a Boolean value and populate the $Matches automatic variable with a hash table of any string values that were matched. For more information about the -match operator, see about_comparison_operators. $MyInvocation Contains an information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or "invoked," such as the name of the script that called the current command. $MyInvocation is populated only for scripts, function, and script blocks. You can use the information in the System.Management.Automation.InvocationInfo object that $MyInvocation returns in the current script, such as the path and file name of the script ($MyInvocation.MyCommand.Path) or the name of a function ($MyInvocation.MyCommand.Name) to identify the current command. This is particularly useful for finding the name of the current script. Beginning in Windows PowerShell 3.0, $MyInvocation has the following new properties. -- PSScriptRoot: Contains the full path to the script that invoked the current command. The value of this property is populated only when the caller is a script. -- PSCommandPath: Contains the full path and file name of the script that invoked the current command. The value of this property is populated only when the caller is a script. Unlike the $PSScriptRoot and $PSCommandPath automatic variables, the PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script. $NestedPromptLevel Contains the current prompt level. A value of 0 indicates the original prompt level. The value is incremented when you enter a nested level and decremented when you exit it. For example, Windows PowerShell presents a nested command prompt when you use the $Host.EnterNestedPrompt method. Windows PowerShell also presents a nested command prompt when you reach a breakpoint in the Windows PowerShell debugger. When you enter a nested prompt, Windows PowerShell pauses the current command, saves the execution context, and increments the value of the $NestedPromptLevel variable. To create additional nested command prompts (up to 128 levels) or to return to the original command prompt, complete the command, or type "exit". The $NestedPromptLevel variable helps you track the prompt level. You can create an alternative Windows PowerShell command prompt that includes this value so that it is always visible. $NULL $null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts. Windows PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values. For example, when $null is included in a collection, it is counted as one of the objects. C:\PS> $a = ".dir", $null, ".pdf" C:\PS> $a.count 3 If you pipe the $null variable to the ForEach-Object cmdlet, it generates a value for $null, just as it does for the other objects. PS C:\ps-test> ".dir", "$null, ".pdf" | Foreach {"Hello"} Hello Hello Hello As a result, you cannot use $null to mean "no parameter value." A parameter value of $null overrides the default parameter value. However, because Windows PowerShell treats the $null variable as a placeholder, you can use it scripts like the following one, which would not work if $null were ignored. $calendar = @($null, $null, gMeetingh, $null, $null, gTeam Lunchh, $null) $days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" $currentDay = 0 foreach($day in $calendar) { if($day ?ne $null) { "Appointment on $($days[$currentDay]): $day" } $currentDay++ } Appointment on Tuesday: Meeting Appointment on Friday: Team lunch $OFS $OFS is a special variable that stores a string that you want to use as an output field separator. Use this variable when you are converting an array to a string. By default, the value of $OFS is " ", but you can change the value of $OFS in your session, by typing $OFS="". If you are expecting the default value of " " in your script, module, or configuration output, be careful that the $OFS default value has not been changed elsewhere in your code. Examples: PS> $a="1","2","3","4" PS> $a 1 2 3 4 PS> [string]$a 1 2 3 4 PS> $OFS="";[string]$a 1234 PS> $OFS=",";[string]$a 1,2,3,4 PS> $OFS="--PowerShellRocks--";[string]$a 1--PowerShellRocks--2--PowerShellRocks--3--PowerShellRocks--4 PS> $OFS="`n`n";[string]$a 1 2 3 4 $PID Contains the process identifier (PID) of the process that is hosting the current Windows PowerShell session. $Profile Contains the full path of the Windows PowerShell profile for the current user and the current host application. You can use this variable to represent the profile in commands. For example, you can use it in a command to determine whether a profile has been created: test-path $profile Or, you can use it in a command to create a profile: new-item -type file -path $pshome -force You can also use it in a command to open the profile in Notepad: notepad $profile $PSBoundParameters Contains a dictionary of the parameters that are passed to a script or function and their current values. This variable has a value only in a scope where parameters are declared, such as a script or function. You can use it to display or change the current values of parameters or to pass parameter values to another script or function. For example: function Test { param($a, $b) # Display the parameters in dictionary format. $PSBoundParameters # Call the Test1 function with $a and $b. test1 @PSBoundParameters } $PsCmdlet Contains an object that represents the cmdlet or advanced function that is being run. You can use the properties and methods of the object in your cmdlet or function code to respond to the conditions of use. For example, the ParameterSetName property contains the name of the parameter set that is being used, and the ShouldProcess method adds the WhatIf and Confirm parameters to the cmdlet dynamically. For more information about the $PSCmdlet automatic variable, see about_Functions_Advanced. $PSCommandPath Contains the full path and file name of the script that is being run. This variable is valid in all scripts. $PsCulture Contains the name of the culture currently in use in the operating system. The culture determines the display format of items such as numbers, currrency, and dates. This is the value of the System.Globalization.CultureInfo.CurrentCulture.Name property of the system. To get the System.Globalization.CultureInfo object for the system, use the Get-Culture cmdlet. $PSDebugContext While debugging, this variable contains information about the debugging environment. Otherwise, it contains a NULL value. As a result, you can use it to indicate whether the debugger has control. When populated, it contains a PsDebugContext object that has Breakpoints and InvocationInfo properties. The InvocationInfo property has several useful properties, including the Location property. The Location property indicates the path of the script that is being debugged. $PsHome Contains the full path of the installation directory for Windows PowerShell, typically, %windir%\System32\WindowsPowerShell\v1.0. You can use this variable in the paths of Windows PowerShell files. For example, the following command searches the conceptual Help topics for the word "variable": Select-String -Pattern Variable -Path $pshome\*.txt $PSItem Same as $_. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline. $PSScriptRoot Contains the directory from which a script is being run. In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts. $PSSenderInfo Contains information about the user who started the PSSession, including the user identity and the time zone of the originating computer. This variable is available only in PSSessions. The $PSSenderInfo variable includes a user-configurable property, ApplicationArguments, which, by default, contains only the $PSVersionTable from the originating session. To add data to the ApplicationArguments property, use the ApplicationArguments parameter of the New-PSSessionOption cmdlet. $PsUICulture Contains the name of the user interface (UI) culture that is currently in use in the operating system. The UI culture determines which text strings are used for user interface elements, such as menus and messages. This is the value of the System.Globalization.CultureInfo.CurrentUICulture.Name property of the system. To get the System.Globalization.CultureInfo object for the system, use the Get-UICulture cmdlet. $PsVersionTable Contains a read-only hash table that displays details about the version of Windows PowerShell that is running in the current session. The table includes the following items: CLRVersion: The version of the common language runtime (CLR) BuildVersion: The build number of the current version PSVersion: The Windows PowerShell version number WSManStackVersion: The version number of the WS-Management stack PSCompatibleVersions: Versions of Windows PowerShell that are compatible with the current version SerializationVersion The version of the serialization method PSRemotingProtocolVersion The version of the Windows PowerShell remote management protocol $Pwd Contains a path object that represents the full path of the current directory. $ReportErrorShowExceptionClass $ReportErrorShowInnerException $ReportErrorShowSource $ReportErrorShowStackTrace The "ReportErrorShow" variables are defined in Windows PowerShell, but they are not implemented. Get-Variable gets them, but they do not contain valid data. $Sender Contains the object that generated this event. This variable is populated only within the Action block of an event registration command. The value of this variable can also be found in the Sender property of the PSEventArgs (System.Management.Automation.PSEventArgs) object that Get-Event returns. $ShellID Contains the identifier of the current shell. $StackTrace Contains a stack trace for the most recent error. $This In a script block that defines a script property or script method, the $This variable refers to the object that is being extended. $True Contains TRUE. You can use this variable to represent TRUE in commands and scripts. SEE ALSO about_Hash_Tables about_Preference_Variables about_Variables about_Environment_Variables TOPIC about_Environment_Variables SHORT DESCRIPTION Describes how to access Windows environment variables in Windows PowerShell. LONG DESCRIPTION Environment variables store information about the operating system environment. This information includes details such as the operating system path, the number of processors used by the operating system, and the location of temporary folders. The environment variables store data that is used by the operating system and other programs. For example, the WINDIR environment variable contains the location of the Windows installation directory. Programs can query the value of this variable to determine where Windows operating system files are located. Windows PowerShell lets you view and change Windows environment variables, including the variables set in the registry, and those set for a particular session. The Windows PowerShell environment provider simplifies this process by making it easy to view and change the environment variables. Unlike other types of variables in Windows PowerShell, environment variables and their values are inherited by child sessions, such as local background jobs and the sessions in which module members run. This makes environment variables well suited to storing values that are needed in both parent and child sessions. Windows PowerShell Environment Provider The Windows PowerShell environment provider lets you access Windows environment variables in Windows PowerShell in a Windows PowerShell drive (the Env: drive). This drive looks much like a file system drive. To go to the Env: drive, type: Set-Location Env: Then, to display the contents of the Env: drive, type: Get-ChildItem You can view the environment variables in the Env: drive from any other Windows PowerShell drive, and you can go into the Env: drive to view and change the environment variables. Environment Variable Objects In Windows PowerShell, each environment variable is represented by an object that is an instance of the System.Collections.DictionaryEntry class. In each DictionaryEntry object, the name of the environment variable is the dictionary key. The value of the variable is the dictionary value. To display an environment variable in Windows PowerShell, get an object that represents the variable, and then display the values of the object properties. When you change an environment variable in Windows PowerShell, use the methods that are associated with the DictionaryEntry object. To display the properties and methods of the object that represents an environment variable in Windows PowerShell, use the Get-Member cmdlet. For example, to display the methods and properties of all the objects in the Env: drive, type: Get-Item -Path Env:* | Get-Member Displaying Environment Variables You can use the cmdlets that contain the Item noun (the Item cmdlets) to display and change the values of environment variables. Because environment variables do not have child items, the output of Get-Item and Get-ChildItem is the same. When you refer to an environment variable, type the Env: drive name followed by the name of the variable. For example, to display the value of the COMPUTERNAME environment variable, type: Get-Childitem Env:Computername To display the values of all the environment variables, type: Get-ChildItem Env: By default, Windows PowerShell displays the environment variables in the order in which it retrieves them. To sort the list of environment variables by variable name, pipe the output of a Get-ChildItem command to the Sort-Object cmdlet. For example, from any Windows PowerShell drive, type: Get-ChildItem Env: | Sort Name You can also go into the Env: drive by using the Set-Location cmdlet: Set-Location Env: When you are in the Env: drive, you can omit the Env: drive name from the path. For example, to display all the environment variables, type: Get-ChildItem To display the value of the COMPUTERNAME variable from within the Env: drive, type: Get-ChildItem ComputerName You can also display and change the values of environment variables without using a cmdlet by using the expression parser in Windows PowerShell. To display the value of an environment variable, use the following syntax: $Env: For example, to display the value of the WINDIR environment variable, type the following command at the Windows PowerShell command prompt: $Env:windir In this syntax, the dollar sign ($) indicates a variable, and the drive name indicates an environment variable. Changing Environment Variables To make a persistent change to an environment variable, use System in Control Panel (Advanced tab or the Advanced System Settings item) to store the change in the registry. When you change environment variables in Windows PowerShell, the change affects only the current session. This behavior resembles the behavior of the Set command in Windows-based environments and the Setenv command in UNIX-based environments. You must also have permission to change the values of the variables. If you try to change a value without sufficient permission, the command fails, and Windows PowerShell displays an error. You can change the values of variables without using a cmdlet by using the following syntax: $Env: = "" For example, to append ";c:\temp" to the value of the Path environment variable, use the following syntax: $Env:path = $env:path + ";c:\temp" You can also use the Item cmdlets, such as Set-Item, Remove-Item, and Copy-Item to change the values of environment variables. For example, to use the Set-Item cmdlet to append ";c:\temp" to the value of the Path environment variable, use the following syntax: Set-Item -Path Env:Path -Value ($Env:Path + ";C:\Temp") In this command, the value is enclosed in parentheses so that it is interpreted as a unit. Saving Changes to Environment Variables To create or change the value of an environment variable in every Windows PowerShell session, add the change to your Windows PowerShell profile. For example, to add the C:\Temp directory to the Path environment variable in every Windows PowerShell session, add the following command to your Windows PowerShell profile. $Env:Path = $Env:Path + ";C:\Temp" To add the command to an existing profile, such as the CurrentUser,AllHosts profile, type: Add-Content -Path $Profile.CurrentUserAllHosts -Value '$Env:Path = $Env:Path + ";C:\Temp"' Environment Variables That Store Preferences Windows PowerShell features can use environment variables to store user preferences. These variables work like preference variables, but they are inherited by child sessions of the sessions in which they are created. For more information about preference variables, see about_preference_variables. The environment variables that store preferences include: PSExecutionPolicyPreference Stores the execution policy set for the current session. This environment variable exists only when you set an execution policy for a single session. You can do this in two different ways. -- Use PowerShell.exe to start a session at the command line and use its ExecutionPolicy parameter to set the execution policy for the session. -- Use the Set-ExecutionPolicy cmdlet. Use the Scope parameter with a value of "Process". For more information, see about_Execution_Policies. PSModulePath Stores the paths to the default module directories. Windows PowerShell looks for modules in the specified directories when you do not specify a full path to a module. The default value of $Env:PSModulePath is: $home\Documents\WindowsPowerShell\Modules; $pshome\Modules Windows PowerShell sets the value of "$pshome\Modules" in the registry. It sets the value of "$home\Documents\WindowsPowerShell\Modules" each time you start Windows PowerShell. In addition, setup programs that install modules in other directories, such as the Program Files directory, can append their locations to the value of PSModulePath. To change the default module directories for the current session, use the following command format to change the value of the PSModulePath environment variable. For example, to add the "C:\Program Files\Fabrikam\Modules" directory to the value of the PSModulePath environment variable, type: $Env:PSModulePath = $Env:PSModulePath + ";C:\Program Files\Fabrikam\Modules" The semi-colon (;) in the command separates the new path from the path that precedes it in the list. To change the value of PSModulePath in every session, add the previous command to your Windows PowerShell profile or use the SetEnvironmentVariable method of the Environment class. The following command uses the GetEnvironmentVariable method to get the machine setting of PSModulePath and the SetEnvironmentVariable method to add the C:\Program Files\Fabrikam\Modules path to the value. $path = [System.Environment]::GetEnvironmentVariable("PSModulePath", "Machine") [System.Environment]::SetEnvironmentVariable("PSModulePath", $path + ` ";C:\Program Files\Fabrikam\Modules", "Machine") To add a path to the user setting, change the target value to User. $path = [System.Environment]::GetEnvironmentVariable("PSModulePath", "User") [System.Environment]::SetEnvironmentVariable("PSModulePath", $path + ` ";$home\Documents\Fabrikam\Modules", "User") For more information about the methods of the System.Environment class, see "Environment Methods" in MSDN at http://go.microsoft.com/fwlink/?LinkId=242783. You can add also add a command that changes the value to your profile or use System in Control Panel to change the value of the PSModulePath environment variable in the registry. For more information, see about_Modules. SEE ALSO Environment (provider) about_Modules about_Preference_Variables TOPIC Preference Variables SHORT DESCRIPTION Variables that customize the behavior of Windows PowerShell LONG DESCRIPTION Windows PowerShell includes a set of variables that enable you to customize its behavior. These "preference variables" work like the options in GUI-based systems. The preference variables affect the Windows PowerShell operating environment and all commands run in the environment. In many cases, the cmdlets have parameters that you can use to override the preference behavior for a specific command. The following table lists the preference variables and their default values. Variable Default Value -------- ------------- $ConfirmPreference High $DebugPreference SilentlyContinue $ErrorActionPreference Continue $ErrorView NormalView $FormatEnumerationLimit 4 $InformationPreference SilentlyContinue $LogCommandHealthEvent False (not logged) $LogCommandLifecycleEvent False (not logged) $LogEngineHealthEvent True (logged) $LogEngineLifecycleEvent True (logged) $LogProviderLifecycleEvent True (logged) $LogProviderHealthEvent True (logged) $MaximumAliasCount 4096 $MaximumDriveCount 4096 $MaximumErrorCount 256 $MaximumFunctionCount 4096 $MaximumHistoryCount 4096 $MaximumVariableCount 4096 $OFS (Space character (" ")) $OutputEncoding ASCIIEncoding object $ProgressPreference Continue $PSDefaultParameterValues (None - empty hash table) $PSEmailServer (None) $PSModuleAutoLoadingPreference All $PSSessionApplicationName WSMAN $PSSessionConfigurationName http://schemas.microsoft.com/PowerShell/microsoft.PowerShell $PSSessionOption (See below) $VerbosePreference SilentlyContinue $WarningPreference Continue $WhatIfPreference 0 Windows PowerShell also includes the following environment variables that store user preferences. For more information about these environment variables, see about_Environment_Variables. Variable -------- PSExecutionPolicyPreference PSModulePath WORKING WITH PREFERENCE VARIABLES This document describes each of the preference variables. To display the current value of a specific preference variable, type the name of the variable. In response, Windows PowerShell provides the value. For example, the following command displays the value of the $ConfirmPreference variable. PS> $ConfirmPreference High To change the value of a variable, use an assignment statement. For example, the following statement assigns the value "Medium" to the $ConfirmPreference variable. PS> $ConfirmPreference = "Medium" Like all variables, the values that you set are specific to the current Windows PowerShell session. To make them effective in all Windows PowerShell session, add them to your Windows PowerShell profile. For more information, see about_Profiles. WORKING REMOTELY When you run commands on a remote computer, the remote commands are subject only to the preferences set in the Windows PowerShell client on the remote computer. For example, when you run a remote command, the value of the $DebugPreference variable on remote computer determines how Windows PowerShell responds to debugging messages. For more information about remote commands, see about_remote. $ConfirmPreference ------------------ Determines whether Windows PowerShell automatically prompts you for confirmation before running a cmdlet or function. When the value of the $ConfirmPreference variable (High, Medium, Low) is less than or equal to the risk assigned to the cmdlet or function (High, Medium, Low), Windows PowerShell automatically prompts you for confirmation before running the cmdlet or function. If the value of the $ConfirmPreference variable is None, Windows PowerShell never automatically prompts you before running a cmdlet or function. To change the confirming behavior for all cmdlets and functions in the session, change the value of the $ConfirmPreference variable. To override the $ConfirmPreference for a single command, use the Confirm parameter of the cmdlet or function. To request confirmation, use -Confirm. To suppress confirmation, use -Confirm:$false Valid values of $ConfirmPreference: None: Windows PowerShell does not prompt automatically. To request confirmation of a particular command, use the Confirm parameter of the cmdlet or function. Low: Windows PowerShell prompts for confirmation before running cmdlets or functions with a low, medium, or high risk. Medium: Windows PowerShell prompts for confirmation before running cmdlets or functions with a medium, or high risk. High: Windows PowerShell prompts for confirmation before running cmdlets or functions with a high risk. DETAILED EXPLANATION When the actions of a cmdlet or function significantly affect the system, such as those that delete data or use a significant amount of system resources, Windows PowerShell can automatically prompt you for confirmation before performing the action. For example, PS> remove-item file.txt Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\file.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): The estimate of the risk is an attribute of the cmdlet or function known as its "ConfirmImpact". Users cannot change it. Cmdlets and functions that might pose a risk to the system have a Confirm parameter that you can use to request or suppress confirmation for a single command. Because most cmdlets and functions use the default risk value (ConfirmImpact) of Medium, and the default value of $ConfirmPreference is High, automatic confirmation rarely occurs. However, you can activate automatic confirmation by changing the value of $ConfirmPreference to Medium or Low. EXAMPLES This example shows the effect of the default value of $ConfirmPreference. The High value only confirms high-risk cmdlets and functions. Since most cmdlets and functions are medium risk, they are not automatically confirmed. PS> $confirmpreference #Get the current value of the High variable PS> remove-item temp1.txt #Delete a file PS> #Deleted without confirmation PS> remove-item temp2.txt -confirm #Use the Confirm parameter to request confirmation Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): The following example shows the effect of changing the value of $ConfirmPreference to Medium. Because most cmdlets and function are medium-risk, they are automatically confirmed. To suppress the confirmation prompt for a single command, use the Confirm parameter with a value of $false PS> $confirmpreference = "Medium" #Change the value of $ConfirmPreference PS> remove-item temp2.txt #Deleting a file triggers confirmation Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\temp2.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): PS> remove-item temp3.txt -confirm:$false #Use Confirm parameter to suppress confirmation PS> $DebugPreference ------------------ Determines how Windows PowerShell responds to debugging messages generated by a script, cmdlet or provider, or by a Write-Debug command at the command line. Some cmdlets display debugging messages, which are typically very technical messages designed for programmers and technical support professionals. By default, debugging messages are not displayed, but you can display debugging messages by changing the value of $DebugPreference. You can also use the Debug common parameter of a cmdlet to display or hide the debugging messages for a specific command. For more information, type: "get-help about_commonparameters". Valid values: Stop: Displays the debug message and stops executing. Writes an error to the console. Inquire: Displays the debug message and asks you whether you want to continue. Note that adding the Debug common parameter to a command--when the command is configured to generate a debugging message--changes the value of the $DebugPreference variable to Inquire. Continue: Displays the debug message and continues with execution. SilentlyContinue: No effect. The debug message is not (Default) displayed and execution continues without interruption. EXAMPLES The following examples show the effect of changing the values of $DebugPreference when a Write-Debug command is entered at the command line. The change affects all debugging messages, including those generated by cmdlets and scripts. The examples also show the use of the Debug common parameter, which displays or hides the debugging messages related to a single command. This example shows the effect of the default value, "SilentlyContinue." The debug message is not displayed and processing continues. The final command uses the Debug parameter to override the preference for a single command. PS> $debugpreference # Get the current value of SilentlyContinue $DebugPreference PS> write-debug "Hello, World" PS> # The debug message is not displayed. PS> write-debug "Hello, World" -Debug # Use the Debug parameter DEBUG: Hello, World # The debug message is displayed and confirmation is requested. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): This example shows the effect of the "Continue" value. The final command uses the Debug parameter with a value of $false to suppress the message for a single command. PS> $debugpreference = "Continue" # Change the value to "Continue" PS> write-debug "Hello, World" DEBUG: Hello, World # The debug message is displayed PS> and processing continues. PS> write-debug "Hello, World" -Debug:$false # Use the Debug parameter with false. PS> # The debug message is not displayed. This example shows the effect of the "Stop" value. The final command uses the Debug parameter with a value of $false to suppress the message for a single command. PS> $debugpreference = "Stop" #Change the value to "Stop" PS> write-debug "Hello, World" DEBUG: Hello, World Write-Debug : Command execution stopped because the shell variable "DebugPreference" is set to Stop. At line:1 char:12 + write-debug <<<< "Hello, World" PS> write-debug "Hello, World" -Debug:$false # Use the Debug parameter with $false PS> # The debug message is not displayed and processing is not stopped. This example shows the effect of the "Inquire" value. The final command uses the Debug parameter with a value of $false to suppress the message for a single command. PS> $debugpreference = "Inquire" PS> write-debug "Hello, World" DEBUG: Hello, World Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): PS> write-debug "Hello, World" -Debug:$false # Use the Debug parameter with $false PS> # The debug message is not displayed and processing continues without interruption. $ErrorActionPreference ---------------------- Determines how Windows PowerShell responds to a non-terminating error (an error that does not stop the cmdlet processing) at the command line or in a script, cmdlet, or provider, such as the errors generated by the Write-Error cmdlet. You can also use the ErrorAction common parameter of a cmdlet to override the preference for a specific command. Valid values: Stop: Displays the error message and stops executing. Inquire: Displays the error message and asks you whether you want to continue. Continue: Displays the error message and continues (Default) executing. Suspend: Automatically suspends a workflow job to allow for further investigation. After investigation, the workflow can be resumed. SilentlyContinue: No effect. The error message is not displayed and execution continues without interruption. NOTE: The Ignore value of the ErrorAction common parameter is not a valid value of the $ErrorActionPreference variable. The Ignore value is intended for per-command use, not for use as saved preference. Neither $ErrorActionPreference nor the ErrorAction common parameter affect how Windows PowerShell responds to terminating errors (those that stop cmdlet processing). For more information about the ErrorAction common parameter, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). EXAMPLES These examples show the effect of the different values of $ErrorActionPreference and the use of the ErrorAction common parameter to override the preference for a single command. The ErrorAction parameter has the same valid values as the $ErrorActionPreference variable. This example shows the effect of the Continue value, which is the default. PS> $erroractionpreference Continue# Display the value of the preference. PS> write-error "Hello, World" # Generate a non-terminating error. write-error "Hello, World" : Hello, World # The error message is displayed and execution continues. PS> write-error "Hello, World" -ErrorAction:SilentlyContinue # Use the ErrorAction parameter with a value of "SilentlyContinue". PS> # The error message is not displayed and execution continues. This example shows the effect of the SilentlyContinue value. PS> $ErrorActionPreference = "SilentlyContinue" # Change the value of the preference. PS> write-error "Hello, World" # Generate an error message. PS> # Error message is suppressed. PS> write-error "Hello, World" -erroraction:continue # Use the ErrorAction parameter with a value of "Continue". write-error "Hello, World" -erroraction:continue : Hello, World # The error message is displayed and execution continues. This example shows the effect of a real error. In this case, the command gets a non-existent file, nofile.txt. The example also uses the ErrorAction common parameter to override the preference. PS> $erroractionpreference SilentlyContinue # Display the value of the preference. PS> get-childitem -path nofile.txt PS> # Error message is suppressed. PS> $ErrorActionPreference = "Continue" # Change the value to Continue. PS> get-childitem -path nofile.txt Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. At line:1 char:4 + get-childitem <<<< nofile.txt PS> get-childitem -path nofile.txt -erroraction SilentlyContinue # Use the ErrorAction parameter PS> # Error message is suppressed. PS> $ErrorActionPreference = "Inquire" # Change the value to Inquire. PS> get-childitem -path nofile.txt Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): y Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. At line:1 char:4 + get-childitem <<<< nofile.txt PS> $ErrorActionPreference = "Continue" # Change the value to Continue. PS> Get-Childitem nofile.txt -erroraction "Inquire" # Use the ErrorAction parameter to override the preference value. Confirm Cannot find path 'C:\nofile.txt' because it does not exist. [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): $ErrorView ---------- Determines the display format of error messages in Windows PowerShell. Valid values: NormalView: A detailed view designed for most users. (default) Consists of a description of the error, the name of the object involved in the error, and arrows (<<<<) that point to the words in the command that caused the error. CategoryView: A succinct, structured view designed for production environments. The format is: {Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason} For more information about the fields in CategoryView, see "ErrorCategoryInfo class" in the Windows PowerShell SDK. EXAMPLES These example show the effect of the ErrorView values. This example shows how an error appears when the value of $ErrorView is NormalView. In this case, the Get-ChildItem command is used to find a non-existent file. PS> $ErrorView # Verify the value. NormalView PS> get-childitem nofile.txt # Find a non-existent file. Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist. At line:1 char:14 + get-childitem <<<< nofile.txt This example shows how the same error appears when the value of $ErrorView is CategoryView. PS> $ErrorView = "CategoryView" # Change the value to CategoryView PS> get-childitem nofile.txt ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException This example demonstrates that the value of ErrorView only affects the error display; it does not change the structure of the error object that is stored in the $error automatic variable. For information about the $error automatic variable, see about_automatic_variables. This command takes the ErrorRecord object associated with the most recent error in the error array (element 0) and formats all of the properties of the error object in a list. PS> $error[0] | format-list -property * -force Exception : System.Management.Automation.ItemNotFoundException: Cannot find path 'C:\nofile.txt' because it does not exist. at System.Management.Automation.SessionStateInternal.GetChildItems(String path, Boolean recurse, CmdletProviderContext context) at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(String path, Boolean recurse, CmdletProviderContext context) at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord() TargetObject : C:\nofile.txt CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo $FormatEnumerationLimit ----------------------- Determines how many enumerated items are included in a display. This variable does not affect the underlying objects; just the display. When the value of $FormatEnumerationLimit is less than the number of enumerated items, Windows PowerShell adds an ellipsis (...) to indicate items not shown. Valid values: Integers (Int32) Default value: 4 EXAMPLES This example shows how to use the $FormatEnumerationLimit variable to improve the display of enumerated items. The command in this example generates a table that lists all of the services running on the computer in two groups; one for running services and one for stopped services. It uses a Get-Service command to get all of the services, and then send the results through the pipeline to the Group-Object cmdlet, which groups the results by the service status. The resulting display is a table that lists the status in the Name column and the processes with that status in the Group column. (To change the column labels, use a hash table. For more information, see the examples in "get-help format-table -examples".) There are a maximum of 4 services listed in the Group column for each status. To increase the number of items listed, increase the value of $FormatEnumerationLimit to 1000. In the resulting display, the list in the Group column is now limited by the line length. In the final command in the example, use the Wrap parameter of Format-Table to display all of the processes in each Status group. PS> $formatenumerationlimit # Find the current value 4 PS> get-service | group-object -property status # List all services grouped by status Count Name Group ----- ---- ----- 60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...} 41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...} # The list is truncated after 4 items. PS> $formatenumerationlimit = 1000 # Increase the limit to 1000. PS> get-service | group-object -property status # Repeat the command. Count Name Group ----- ---- ----- 60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec... 41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc... PS> get-service | group-object -property status | format-table -wrap # Add the Wrap parameter. Count Name Group ----- ---- ----- 60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec, Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver, lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla, NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan, RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS, SharedAccess, ShellHWDetection, SMT PSVC, Spooler, srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes, TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, wuauserv, WZCSVC, zzInterix} 41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc, ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, CronService, dmadmin, FastUserSwitchingCompatibility, HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc, MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc, NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator, SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, WmdmPmSN, Wmi, WmiApSrv, xmlprov} $InformationPreference ---------------------- The $InformationPreference variable lets you set information stream preferences (specifically, informational messages that you have added to commands or scripts by adding the Write-Information cmdlet, and want displayed to users) for a Windows PowerShell session. The value of the -InformationAction parameter, if used, overrides the current value of the $InformationPreference variable. Valid values: Stop: Stops a command or script at an occurrence of the Write-Information command. Inquire: Displays the informational message that you specify in a Write-Information command, then asks whether you want to continue. Continue: Displays the informational message, and continues running. Suspend: Automatically suspends a workflow job after a Write-Information command is carried out, to allow users to see the messages before continuing. The workflow can be resumed at the userfs discretion. SilentlyContinue: No effect. The informational messages are not (Default) displayed, and the script continues without interruption. $Log*Event ---------- The Log*Event preference variables determine which types of events are written to the Windows PowerShell event log in Event Viewer. By default, only engine and provider events are logged, but you can use the Log*Event preference variables to customize your log, such as logging events about commands. The Log*Event preference variables are as follows: $LogCommandHealthEvent: Logs errors and exceptions in command initialization and processing. Default = $false (not logged). $LogCommandLifecycleEvent: Logs the starting and stopping of commands and command pipelines and security exceptions in command discovery. Default = $false (not logged). $LogEngineHealthEvent: Logs errors and failures of sessions. Default = $true (logged). $LogEngineLifecycleEvent: Logs the opening and closing of sessions. Default = $true (logged). $LogProviderHealthEvent: Logs provider errors, such as read and write errors, lookup errors, and invocation errors. Default = $true (logged). $LogProviderLifecycleEvent: Logs adding and removing of Windows PowerShell providers. Default = $true (logged). (For information about Windows PowerShell providers, type: "get-help about_provider". To enable a Log*Event, type the variable with a value of $true, for example: $LogCommandLifeCycleEvent - or - $LogCommandLifeCycleEvent = $true To disable an event type, type the variable with a value of $false, for example: $LogCommandLifeCycleEvent = $false The events that you enable are effective only for the current Windows PowerShell console. To apply the configuration to all consoles, save the variable settings in your Windows PowerShell profile. $MaximumAliasCount ------------------ Determines how many aliases are permitted in a Windows PowerShell session. The default value, 4096, should be sufficient for most uses, but you can adjust it to meet your needs. Valid values: 1024 - 32768 (Int32) Default: 4096 To count the aliases on your system, type: (get-alias).count $MaximumDriveCount ------------------ Determines how many Windows PowerShell drives are permitted in a given session. This includes file system drives and data stores that are exposed by Windows PowerShell providers and appear as drives, such as the Alias: and HKLM: drives. Valid values: 1024 - 32768 (Int32) Default: 4096 To count the aliases on your system, type: (get-psdrive).count $MaximumErrorCount ------------------ Determines how many errors are saved in the error history for the session. Valid values: 256 - 32768 (Int32) Default: 256 Objects that represent each retained error are stored in the $Error automatic variable. This variable contains an array of error record objects, one for each error. The most recent error is the first object in the array ($Error[0]). To count the errors on your system, use the Count property of the $Error array. Type: $Error.count To display a specific error, use array notation to display the error. For example, to see the most recent error, type: $Error[0] To display the oldest retained error, type: $Error[($Error.Count -1] To display the properties of the ErrorRecord object, type: $Error[0] | format-list -property * -force In this command, the Force parameter overrides the special formatting of ErrorRecord objects and reverts to the conventional format. To delete all errors from the error history, use the Clear method of the error array. PS> $Error.count 17 PS> $Error.clear() PS> PS> $Error.count 0 To find all properties and methods of an error array, use the Get-Member cmdlet with its InputObject parameter. When you pipe a collection of objects to Get-Member, Get-Member displays the properties and methods of the objects in the collection. When you use the InputObject parameter of Get-Member, Get-Member displays the properties and methods of the collection. $MaximumFunctionCount ------------------ Determines how many functions are permitted in a given session. Valid values: 1024 - 32768 (Int32) Default: 4096 To see the functions in your session, use the Windows PowerShell Function: drive that is exposed by the Windows PowerShell Function provider. (For more information about the Function provider, type "get-help function"). To list the functions in the current session, type: get-childitem function: To count the functions in the current session, type: (get-childitem function:).count $MaximumHistoryCount ------------------ Determines how many commands are saved in the command history for the current session. Valid values: 1 - 32768 (Int32) Default: 4096 To determine the number of commands current saved in the command history, type: (get-history).count To see the command saved in your session history, use the Get-History cmdlet. For more information, see about_History (http://go.microsoft.com/fwlink/?LinkID=113233). NOTE: In Windows PowerShell 2.0, the default value of the $MaximumHistoryCount variable is 64. $MaximumVariableCount ------------------ Determines how many variables are permitted in a given session, including automatic variables, preference variables, and the variables that you create in commands and scripts. Valid values: 1024 - 32768 (Int32) Default: 4096 To see the variables in your session, use the Get-Variable cmdlet and the features of the Windows PowerShell Variable: drive and the Windows PowerShell Variable provider. For information about the Variable provider, type "get-help variable". To find the current number of variables on the system, type: (get-variable).count $OFS ---- Output Field Separator. Specifies the character that separates the elements of an array when the array is converted to a string. Valid values: Any string. Default: Space By default, the $OFS variable does not exist and the output file separator is a space, but you can add this variable and set it to any string. EXAMPLES This example shows that a space is used to separate the values when an array is converted to a string. In this case, an array of integers is stored in a variable and then the variable is cast as a string. PS> $array = 1,2,3 # Store an array of integers. PS> [string]$array # Cast the array to a string. 1 2 3 # Spaces separate the elements To change the separator, add the $OFS variable by assigning a value to it. To work correctly, the variable must be named $OFS. PS> $OFS = "+" # Create $OFS and assign a "+" PS> [string]$array # Repeat the command 1+2+3 # Plus signs separate the elements To restore the default behavior, you can assign a space (" ") to the value of $OFS or delete the variable. This command deletes the variable and then verifies that the separator is a space. PS> Remove-Variable OFS # Delete $OFS PS> PS> [string]$array # Repeat the command 1 2 3 # Spaces separate the elements $OutputEncoding --------------- Determines the character encoding method that Windows PowerShell uses when it sends text to other applications. For example, if an application returns Unicode strings to Windows PowerShell, you might need to change the value to UnicodeEncoding to send the characters correctly. Valid values: Objects derived from an Encoding class, such as ASCIIEncoding, SBCSCodePageEncoding, UTF7Encoding, UTF8Encoding, UTF32Encoding, and UnicodeEncoding. Default: ASCIIEncoding object (System.Text.ASCIIEncoding) EXAMPLES This example shows how to make the FINDSTR command in Windows work in Windows PowerShell on a computer that is localized for a language that uses Unicode characters, such as Chinese. The first command finds the value of $OutputEncoding. Because the value is an encoding object, display only its EncodingName property. PS> $OutputEncoding.EncodingName # Find the current value US-ASCII In this example, a FINDSTR command is used to search for two Chinese characters that are present in the Test.txt file. When this FINDSTR command is run in the Windows Command Prompt (Cmd.exe), FINDSTR finds the characters in the text file. However, when you run the same FINDSTR command in Windows PowerShell, the characters are not found because the Windows PowerShell sends them to FINDSTR in ASCII text, instead of in Unicode text. PS> findstr # Use findstr to search. PS> # None found. To make the command work in Windows PowerShell, set the value of $OutputEncoding to the value of the OutputEncoding property of the console, which is based on the locale selected for Windows. Because OutputEncoding is a static property of the console, use double-colons (::) in the command. PS> $OutputEncoding = [console]::outputencoding PS> # Set the value equal to the OutputEncoding property of the console. PS> $OutputEncoding.EncodingName OEM United States # Find the resulting value. As a result of this change, the FINDSTR command finds the characters. PS> findstr test.txt: # Use findstr to search. It find the characters in the text file. $ProgressPreference ------------------- Determines how Windows PowerShell responds to progress updates generated by a script, cmdlet or provider, such as the progress bars generated by the Write-Progress cmdlet. The Write-Progress cmdlet creates progress bars that depict the status of a command. Valid values: Stop: Does not display the progress bar. Instead, it displays an error message and stops executing. Inquire: Does not display the progress bar. Prompts for permission to continue. If you reply with Y or A, it displays the progress bar. Continue: Displays the progress bar and continues with (Default) execution. SilentlyContinue: Executes the command, but does not display the progress bar. $PSEmailServer -------------- Specifies the default e-mail server that is used to send e-mail messages. This preference variable is used by cmdlets that send e-mail, such as the Send-MailMessage cmdlet. $PSDefaultParameterValues ------------------------- Specifies default values for the parameters of cmdlets and advanced functions. The value of $PSDefaultParameterValues is a hash table where the key consists of the cmdlet name and parameter name separated by a colon (:) and the value is a custom default value that you specify. This variable was introduced in Windows PowerShell 3.0 For more information about this preference variable, see about_Parameters_Default_Values. $PSModuleAutoloadingPreference ------------------------------ Enables and disables automatic importing of modules in the session. "All" is the default. Regardless of the value of this variable, you can use the Import-Module cmdlet to import a module. Valid values are: All Modules are imported automatically on first-use. To import a module, get (Get-Command) or use any command in the module. ModuleQualified Modules are imported automatically only when a user uses the module-qualified name of a command in the module. For example, if the user types "MyModule\MyCommand", Windows PowerShell imports the MyModule module. None Automatic importing of modules is disabled in the session. To import a module, use the Import-Module cmdlet. For more information about automatic importing of modules, see about_Modules (http://go.microsoft.com/fwlink/?LinkID=144311). $PSSessionApplicationName --------------------------- Specifies the default application name for a remote command that uses WS-Management technology. The system default application name is WSMAN, but you can use this preference variable to change the default. The application name is the last node in a connection URI. For example, the application name in the following sample URI is WSMAN. http://Server01:8080/WSMAN The default application name is used when the remote command does not specify a connection URI or an application name. The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the URLPrefix property of a listener on the remote computer. To override the system default and the value of this variable, and select a different application name for a particular session, use the ConnectionURI or ApplicationName parameters of the New-PSSession, Enter-PSSession or Invoke-Command cmdlets. This preference variable is set on the local computer, but it specifies a listener on the remote computer. If the application name that you specify does not exist on the remote computer, the command to establish the session fails. $PSSessionConfigurationName --------------------------- Specifies the default session configuration that is used for PSSessions created in the current session. This preference variable is set on the local computer, but it specifies a session configuration that is located on the remote computer. The value of the $PSSessionConfigurationName variable is a fully qualified resource URI. The default value: http://schemas.microsoft.com/PowerShell/microsoft.PowerShell indicates the Microsoft.PowerShell session configuration on the remote computer. If you specify only a configuration name, the following schema URI is prepended: http://schemas.microsoft.com/PowerShell/ You can override the default and select a different session configuration for a particular session by using the ConfigurationName parameter of the New-PSSession, Enter-PSSession or Invoke-Command cmdlets. You can change the value of this variable at any time. When you do, remember that the session configuration that you select must exist on the remote computer. If it does not, the command to create a session that uses the session configuration fails. This preference variable does not determine which local session configurations are used when remote users create a session that connects to this computer. However, you can use the permissions for the local session configurations to determine which users may use them. $PSSessionOption ---------------- Establishes the default values for advanced user options in a remote session. These option preferences override the system default values for session options. The $PSSessionOption variable contains a PSSessionOption object (System.Management.Automation.Remoting.PSSessionObject). Each property of the object represents a session option. For example, the NoCompression property turns of data compression during the session. By default, the $PSSessionOption variable contains a PSSessionOption object with the default values for all options, as shown below. MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False ProxyAccessType : None ProxyAuthentication : Negotiate ProxyCredential : SkipCACheck : False SkipCNCheck : False SkipRevocationCheck : False OperationTimeout : 00:03:00 NoEncryption : False UseUTF16 : False IncludePortInSPN : False OutputBufferingMode : None Culture : UICulture : MaximumReceivedDataSizePerCommand : MaximumReceivedObjectSize : 209715200 ApplicationArguments : OpenTimeout : 00:03:00 CancelTimeout : 00:01:00 IdleTimeout : -00:00:00.0010000 For descriptions of these options, see the help topic for the New-PSSessionOption cmdlet. To change the value of the $PSSessionOption preference variable, use the New-PSSessionOption cmdlet to create a PSSessionOption object with the option values you prefer. Save the output in a variable called $PSSessionOption. For example, $PSSessionOption = New-PSSessionOption -NoCompression To use the $PSSessionOption preference variable in every Windows PowerShell session, add a New-PSSessionOption command that creates the $PSSessionOption variable to your Windows PowerShell profile. You can also set custom options for a particular remote session. The options that you set take precedence over the system defaults and the value of the $PSSessionOption preference variable. To set custom session options, use the New-PSSessionOption cmdlet to create a PSSessionOption object. Then, use the PSSessionOption object as the value of the SessionOption parameter in cmdlets that create a session, such as New-PSSession, Enter-PSSession, and Invoke-Command. For more information about the New-PSSessionOption cmdlet, see the help topic for New-PSSessionOption. For more information about remote commands and sessions, see about_Remote and about_PSSessions. For more information about using a profile, see about_Profiles. $VerbosePreference ------------------ Determines how Windows PowerShell responds to verbose messages generated by a script, cmdlet or provider, such as the messages generated by the Write-Verbose cmdlet. Typically, verbose messages describe the actions performed to execute a command. By default, verbose messages are not displayed, but you can change this behavior by changing the value of $VerbosePreference. You can also use the Verbose common parameter of a cmdlet to display or hide the verbose messages for a specific command. For more information, type: "get-help about_commonparameters". Valid values: Stop: Displays the verbose message and an error message and then stops executing. Inquire: Displays the verbose message and then displays a prompt that asks you whether you want to continue. Continue: Displays the verbose message and then continues with execution. SilentlyContinue: Does not display the verbose message. Continues executing. (Default) EXAMPLES These examples show the effect of the different values of $VerbosePreference and the use of the Verbose common parameter to override the preference value. This example shows the effect of the SilentlyContinue value, which is the default. PS> $VerbosePreference # Find the current value. SilentlyContinue PS> Write-Verbose "Verbose message test." PS> # Write a verbose message. # Message is not displayed. PS> Write-Verbose "Verbose message test." -verbose VERBOSE: Verbose message test. # Use the Verbose parameter. This example shows the effect of the Continue value. PS> $VerbosePreference = "Continue" # Change the value to Continue. PS> Write-Verbose "Verbose message test." # Write a verbose message. VERBOSE: Verbose message test. # Message is displayed. PS> Write-Verbose "Verbose message test." -verbose:$false # Use the Verbose parameter with a value of $false. PS> # Message is not displayed. This example shows the effect of the Stop value. PS> $VerbosePreference = "Stop" # Change the value to Stop. PS> Write-Verbose "Verbose message test." # Write a verbose message. VERBOSE: Verbose message test. Write-Verbose : Command execution stopped because the shell variable "VerbosePreference" is set to Stop. At line:1 char:14 + Write-Verbose <<<< "Verbose message test." PS> Write-Verbose "Verbose message test." -verbose:$false # Use the Verbose parameter with a value of $false PS> # Message is not displayed. This example shows the effect of the Inquire value. PS> $VerbosePreference = "Inquire" # Change the value to Inquire. PS> Write-Verbose "Verbose message test." VERBOSE: Verbose message test. # Write a verbose message. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): y PS> PS> Write-Verbose "Verbose message test." -verbose:$false # Use the Verbose parameter. PS> # Message is not displayed. $WarningPreference ------------------ Determines how Windows PowerShell responds to warning messages generated by a script, cmdlet or provider, such as the messages generated by the Write-Warning cmdlet. By default, warning messages are displayed and execution continues, but you can change this behavior by changing the value of $WarningPreference. You can also use the WarningAction common parameter of a cmdlet to determine how Windows PowerShell responds to warnings from a particular command. For more information, type: "get-help about_commonparameters". Valid values: Stop: Displays the warning message and an error message and then stops executing. Inquire: Displays the warning message and then prompts for permission to continue. Continue: Displays the warning message and then (Default) continues executing. SilentlyContinue: Does not display the warning message. Continues executing. EXAMPLES These examples show the effect of the different values of $WarningPreference and the use of the WarningAction common parameter to override the preference value. This example shows the effect of the Continue value, which is the default. PS> $WarningPreference # Find the current value. Continue # Write a warning message. PS> Write-Warning "This action can delete data." WARNING: This action can delete data. # Use the WarningAction parameter to # suppress the warning for this command PS> Write-Warning "This action can delete data." -warningaction silentlycontinue This example shows the effect of the SilentlyContinue value. PS> $WarningPreference = "SilentlyContinue" # Change the value to SilentlyContinue. PS> Write-Warning "This action can delete data." PS> # Write a warning message. PS> Write-Warning "This action can delete data." -warningaction stop # Use the WarningAction parameter to stop # processing when this command generates a # warning. WARNING: This action can delete data. Write-Warning : Command execution stopped because the shell variable "WarningPreference" is set to Stop. At line:1 char:14 + Write-Warning <<<< "This action can delete data." -warningaction stop This example shows the effect of the Inquire value. PS> $WarningPreference = "Inquire" # Change the value to Inquire. PS> Write-Warning "This action can delete data." # Write a warning message. WARNING: This action can delete data. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): y PS> PS> Write-Warning "This action can delete data." -warningaction silentlycontinue PS> # Use the WarningAction parameter to change the # response to a warning for the current command. This example shows the effect of the Stop value. PS> $WarningPreference = "Stop" # Change the value to Stop. PS> Write-Warning "This action can delete data." # Write a warning message. WARNING: This action can delete data. Write-Warning : Command execution stopped because the shell variable "WarningPreference" is set to Stop. At line:1 char:14 + Write-Warning <<<< "This action can delete data." PS> Write-Warning "This action can delete data." -warningaction inquire WARNING: This action can delete data. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): # Use the WarningAction parameter to change the # response to a warning for the current command. $WhatIfPreference ------------------ Determines whether WhatIf is automatically enabled for every command that supports it. When WhatIf is enabled, the cmdlet reports the expected effect of the command, but does not execute the command. Valid values: 0: WhatIf is not automatically enabled. To (Default) enable it manually, use the WhatIf parameter of the command. 1: WhatIf is automatically enabled on any command that supports it. Users can use the WhatIf command with a value of False to disable it manually (WhatIf:$false). DETAILED EXPLANATION When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the command, instead of executing the command. For example, instead of deleting the test.txt file in response to a Remove-Item command, Windows PowerShell reports what it would delete. A subsequent Get-Childitem command confirms that the file was not deleted. PS> remove-item test.txt What if: Performing operation "Remove-Item" on Target "Item: C:\test.txt PS> get-childitem test.txt Directory: Microsoft.PowerShell.Core\FileSystem::C: Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 7/29/2006 7:15 PM 84 test.txt EXAMPLES These examples show the effect of the different values of $WhatIfPreference. They also show how to use the WhatIf cmdlet parameter to override the preference value for a specific command. This example shows the effect of the 0 (not enabled) value, which is the default. PS> $whatifpreference 0 # Check the current value. PS> get-childitem test.txt | format-list FullName FullName : C:\test.txt # Verify that the file exists. PS> remove-item test.txt PS> # Delete the file. PS> get-childitem test.txt | format-list -property FullName # Verify that the file is deleted. Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist. At line:1 char:14 + get-childitem <<<< test.txt | format-list fullname This example shows the effect of using the WhatIf parameter when the value of $WhatIfPreference is 0. PS> get-childitem test2.txt | format-list -property FullName FullName : C:\test2.txt # Verify that the file exists. PS> remove-item test2.txt -whatif What if: Performing operation "Remove File" on Target "C:\test2.txt". # Use the WhatIf parameter PS> get-childitem test2.txt | format-list -property FullName FullName : C:\test2.txt # Verify that the file was not deleted This example shows the effect of the 1 (WhatIf enabled) value. When you use Remove-Item to delete a cmdlet, Remove-Item displays the path to the file that it would delete, but it does not delete the file. PS> $whatifpreference = 1 PS> $whatifpreference 1 # Change the value. PS> remove-item test.txt What if: Performing operation "Remove File" on Target "C:\test.txt". # Try to delete a file. PS> get-childitem test.txt | format-list FullName FullName : C:\test.txt # Verify that the file exists. This example shows how to delete a file when the value of $WhatIfPreference is 1. It uses the WhatIf parameter with a value of $false. PS> remove-item test.txt -whatif:$false # Use the WhatIf parameter with $false. This example demonstrates that some cmdlets support WhatIf behavior and others do not. In this example, in which the value of $WhatIfPreference is 1 (enabled), a Get-Process command, which does not support WhatIf, is executed, but a Stop-Process command performs the WhatIf behavior. You can override the WhatIf behavior of the Stop-Process command by using the WhatIf parameter with a value of $false. PS> $whatifpreference = 1 # Change the value to 1. PS> get-process winword # A Get-Process command completes. Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 234 8 6324 15060 154 0.36 2312 WINWORD PS> stop-process -name winword What if: Performing operation "Stop-Process" on Target "WINWORD (2312)". # A Stop-Process command uses WhatIf. PS> stop-process -name winword -whatif:$false PS> # WhatIf:$false overrides the preference. PS> get-process winword Get-Process : Cannot find a process with the name 'winword'. Verify the process name and call the cmdlet again. At line:1 char:12 + get-process <<<< winword # Verify that the process is stopped. SEE ALSO about_Automatic_Variables about_CommonParameters about_Environment_Variables about_Profiles about_Remote about_Scopes about_Variables