PowerShell commands with help and examples
Add-Computer NAME Add-Computer SYNOPSIS Add the local computer to a domain or workgroup. SYNTAX Add-Computer [-DomainName] <string> [-Credential <PSCredential>] [-OUPath string>] [-Server <string>] [-Unsecure] [-PassThru] [-Confirm] [-WhatIf] [ CommonParameters>] Add-Computer [-WorkGroupName] <string> [-Credential <PSCredential>] [-PassT hru] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Add-Computer cmdlet adds the local computer to a domain or workgroup, o r moves it from one domain to another. It also creates a domain account if the computer is added to the domain without an account. You can use the parameters of this cmdlet to specify an organizational unit (OU) and domain controller or to perform an unsecure join. To get the results of the command, use the Verbose and PassThru parameters. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. Required? false Position? named Default value Current User Account Credentials Accept pipeline input? false Accept wildcard characters? false -DomainName <string> Specifies a domain for the computer account. This parameter is required . Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -OUPath <string> Specifies an organizational unit (OU) for the domain account. Enter the full distinguished name of the OU. The default value is the default O U for machine objects in the domain. Required? false Position? named Default value The default OU for machine objects for in the domain Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns the results of the command. By default, this cmdlet does not ge nerate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Server <string> Specifies the name of a domain controller that adds the computer to the domain. Enter the name in DomainName\ComputerName format. The default is the local computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Unsecure [<SwitchParameter>] Performs an unsecure join. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WorkGroupName <string> Specifies the name of a work group for the computer. If you omit this p arameter, the computer is joined to a domain. Required? true Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Add-Computer. OUTPUTS Microsoft.PowerShell.Commands.ComputerChangeInfo When you use the PassThru parameter, Add-Computer returns a ComputerCha ngeInfo object. Otherwise, this cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>add-computer -domainname Domain01; restart-computer Description ----------- These commands add the local computer to the Domain01 domain using the cred entials of the current user. The first command adds the computer to the domain. The second command uses the Restart-Computer cmdlet to restart the computer, which completes the jo in operation. The semi-colon (;) separates the two commands. -------------------------- EXAMPLE 2 -------------------------- C:\PS>add-computer -workgroupname WORKGROUP-A Description ----------- This command adds the local computer to the Workgroup-A workgroup. -------------------------- EXAMPLE 3 -------------------------- C:\PS>add-computer -DomainName Domain01 -Server Domain01\DC01 -passthru -ve rbose Description ----------- This command adds the local computer to the Domain01 domain by using the Do main01\DC01 domain controller. The command uses the PassThru and Verbose parameters to get detailed inform ation about the results of the command. -------------------------- EXAMPLE 4 -------------------------- C:\PS>Add-Computer -domainname Domain02 -OUPath OU=testOU,DC=domain,DC=Doma in,DC=com Description ----------- This command adds the Server01 and Server02 computers to the Domain02 domai n. It uses the OUPath command to specify the organization unit for the new accounts. -------------------------- EXAMPLE 5 -------------------------- C:\PS>Add-Computer -domainname Domain02 -cred Domain02\Admin02 -passthru Description ----------- This command adds the local computer to the Domain02 domain by using the cr edentials of a domain administrator. The command uses the PassThru paramete r to generate a brief report about the results of the command. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135194 Checkpoint-Computer Remove-Computer Restart-Computer Restore-Computer Stop-Computer Test-Connection Add-Content NAME Add-Content SYNOPSIS Adds content to the specified items, such as adding words to a file. SYNTAX Add-Content [-LiteralPath] <string[]> [-Value] <Object[]> [-Credential <PSC redential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <st ring[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParamet ers>] Add-Content [-Path] <string[]> [-Value] <Object[]> [-Credential <PSCredenti al>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]> ] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Add-Content cmdlet appends content to a specified item or file. You can specify the content by typing the content in the command or by specifying an object that contains the content. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Overrides the read-only attribute, allowing you to add content to a rea d-only file. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Adds only the specified items. The value of this parameter qualifies th e Path parameter. Enter a path element or pattern, such as "*.txt". Wil dcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies the path to the items that receive the additional content. Un like Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape ch aracters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape seque nces. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the added content. By default, this cmdl et does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the items that receive the additional content. Wi ldcards are permitted. If you specify multiple paths, use commas to sep arate the paths. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Value <Object[]> Specifies the content to be added. Type a quoted string, such as "This data is for internal use only", or specify an object that contains cont ent, such as the DateTime object that Get-Date generates. You cannot specify the contents of a file by typing its path, because t he path is just a string, but you can use a Get-Content command to get the content and pass it to the Value parameter. Required? true Position? 2 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe the objects to be added (the Value) to Add-Content. OUTPUTS None or System.String When you use the Passthru parameter, Add-Content generates a System.Str ing object representing the content. Otherwise, this cmdlet does not ge nerate any output. NOTES When you pipe an object to Add-Content, the object is converted to a st ring before it is added to the item. The object type determines the str ing format, but the format might be different than the default display of the object. To control the string format, use the formatting paramet ers of the sending cmdlet. You can also refer to Add-Content by its built-in alias, "ac". For more information, see about_Aliases. The Add-Content cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-P sProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>add-content -path *.txt -exclude help* -value "END" Description ----------- This command adds "END" to all text files in the current directory, except for those with file names that begin with "help". -------------------------- EXAMPLE 2 -------------------------- C:\PS>add-content -Path file1.log, file2.log -Value (get-date) -passthru Description ----------- This command adds the date to the end of the File1.log and File2.log files and then displays the date at the command line. The command uses the Get-Da te cmdlet to get the date, and it uses the Value parameter to pass the date to Add-Content. The PassThru parameter passes an object representing the a dded content through the pipeline. Because there is no other cmdlet to rece ive the passed object, it is displayed at the command line. -------------------------- EXAMPLE 3 -------------------------- C:\PS>add-content -path monthly.txt -value (get-content c:\rec1\weekly.txt) Description ----------- This command adds the contents of the Weekly.txt file to the end of the Mon thly.txt file. It uses the Get-Content cmdlet to get the contents of the We ekly.txt file, and it uses the Value parameter to pass the content of weekl y.txt to Add-Content. The parentheses ensure that the Get-Content command i s complete before the Add-Content command begins. You can also copy the content of Weekly.txt to a variable, such as $w, and then use the Value parameter to pass the variable to Add-Content. In that c ase, the command would be "add-content -path monthly.txt -value $w". -------------------------- EXAMPLE 4 -------------------------- C:\PS>add-content -value (get-content test.log) -path C:\tests\test134\logs \test134.log Description ----------- This command creates a new directory and file and copies the content of an existing file to the newly created file. This command uses the Add-Content cmdlet to add the content. The value of t he Value parameter is a Get-Content command that gets content from an exist ing file, Test.log. The value of the path parameter is a path that does not exist when the comm and runs. In this example, only the C:\Tests directories exist. The command creates the remaining directories and the Test134.log file. The Force parameter is not required for this command. Add-Content creates d irectories to complete a path even without the Force parameter. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113278 about_Providers Get-Content Set-Content Clear-Content Get-Item Add-History NAME Add-History SYNOPSIS Appends entries to the session history. SYNTAX Add-History [[-InputObject] <PSObject[]>] [-PassThru] [<CommonParameters>] DESCRIPTION The Add-History cmdlet adds entries to the end of the session history, that is, the list of commands entered during the current session. You can use the Get-History cmdlet to get the commands and pass them to Add -History, or you can export the commands to a CSV or XML file, then import the commands, and pass the imported file to Add-History. You can use this c mdlet to add specific commands to the history or to create a single history file that includes commands from more than one session. PARAMETERS -InputObject <PSObject[]> Adds the specified HistoryInfo object to the session history. You can u se this parameter to submit a HistoryInfo object from Get-History, Impo rt-Clixml, or Import-Csv to Add-History. Required? false Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns a history object for each history entry. By default, this cmdle t does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS Microsoft.PowerShell.Commands.HistoryInfo You can pipe a HistoryInfo object to Add-History. OUTPUTS None or Microsoft.PowerShell.Commands.HistoryInfo When you use the PassThru parameter, Add-History generates a HistoryInf o object. Otherwise, this cmdlet does not generate any output. NOTES The session history is a list of the commands entered during the sessio n along with the ID. The session history represents the order of execut ion, the status, and the start and end times of the command. As you ent er each command, Windows PowerShell adds it to the history so that you can reuse it. For more information about the session history, see abou t_History. To specify the commands to add to the history, use the InputObject para meter. The Add-History command accepts only HistoryInfo objects, such a s those generated for each command by Get-History. You cannot pass it a path and file name or a list of commands. You can use the -InputObject parameter to pass a file of HistoryInfo ob jects to Add-History. To do so, export the results of a Get-History com mand to a file by using Export-Csv or Export-Clixml and then import the file by using Import-Csv or Import-Clixml. You can then pass the file of imported HistoryInfo objects to Add-History through a pipeline or in a variable. For more information, see the examples. The file of HistoryInfo objects that you pass to Add-History must inclu de the type information, column headings, and all of the properties of the HistoryInfo objects. If you intend to pass the objects back to Add- History, do not use the NoTypeInformation parameter of Export-Csv and d o not delete the type information, column headings, or any fields in th e file. To edit the session history, export the session to a CSV or XML file, e dit the file, import the file, and use Add-History to append it to the current session history. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-history | export-csv c:\testing\history.csv C:\PS>import-csv history.csv | add-history Description ----------- These commands add the commands typed in one Windows PowerShell session to the history of a different Windows PowerShell session. The first command ge ts objects representing the commands in the history and exports them to the History.csv file. The second command is typed at the command line of a dif ferent session. It uses the Import-Csv cmdlet to import the objects in the History.csv file. The pipeline operator passes the objects to the Add-Histo ry cmdlet, which adds the objects representing the commands in the History. csv file to the current session history. -------------------------- EXAMPLE 2 -------------------------- C:\PS>import-clixml c:\temp\history.xml | add-history -passthru | foreach-o bject {invoke-history} Description ----------- This command imports commands from the History.xml file, adds them to the c urrent session history, and then executes the commands in the combined hist ory. The first command uses the Import-Clixml command to import a command histor y that was exported to the History.xml file. The pipeline operator (|) pass es the commands to the Add-History parameter, which adds the commands to th e current session history. The PassThru parameter passes the objects repres enting the added commands down the pipeline. The command then uses the ForEach-Object cmdlet to apply the Invoke-History command to each of the commands in the combined history. The Invoke-Histor y command is formatted as a script block, which is enclosed in braces ({}) because ForEach-Object requires a script block even when there is only one command to apply. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-history -id 5 -count 5 | add-history Description ----------- This command adds the first five commands in the history to the end of the history list. It uses the Get-History cmdlet to get the five commands endin g in command 5. The pipeline operator (|) passes them to the Add-History cm dlet, which appends them to the current history. The Add-History command do es not include any parameters, but Windows PowerShell associates the object s passed through the pipeline with the InputObject parameter. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$a = import-csv c:\testing\history.csv C:\PS>add-history -inputobject $a -passthru Description ----------- These commands add the commands in the History.csv file to the current sess ion history. The first command uses the Import-Csv cmdlet to import the com mands in the History.csv file and store its contents in the variable $a. Th e second command uses the Add-History cmdlet to add the commands from Histo ry.csv to the current session history. It uses the InputObject parameter to specify the $a variable and the PassThru parameter to generate an object t o display at the command line. Without the PassThru parameter, Add-History does not generate any output to display. -------------------------- EXAMPLE 5 -------------------------- C:\PS>add-history -inputobject (import-clixml c:\temp\history01.xml) Description ----------- This command adds the commands in the History01.xml file to the current ses sion history. It uses the InputObject parameter to pass the results of the command in parentheses to Add-History. The command in parentheses, which is executed first, imports the History01.xml file into Windows PowerShell. Ad d-History then adds the commands in the file to the session history. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113279 about_History Get-History Invoke-History Clear-History Add-Member NAME Add-Member SYNOPSIS Adds a user-defined custom member to an instance of a Windows PowerShell ob ject. SYNTAX Add-Member [-MemberType] {AliasProperty | CodeProperty | Property | NotePro perty | ScriptProperty | Properties | PropertySet | Method | CodeMethod | S criptMethod | Methods | ParameterizedProperty | MemberSet | Event | All} [- Name] <string> -InputObject <psobject> [[-Value] <Object>] [[-SecondValue] <Object>] [-Force] [-PassThru] [<CommonParameters>] DESCRIPTION The Add-Member cmdlet adds a user-defined custom member to an instance of a Windows PowerShell object. It lets you add the following types of members: AliasProperty, CodeProperty, NoteProperty, ScriptProperty, PropertySet, Co deMethod, MemberSet, and ScriptMethod. You set the initial value of the mem ber by using the Value parameter. In the case of AliasProperty, ScriptPrope rty, CodeProperty, and CodeMethod, you can supply additional information by using the SecondValue parameter. The additional members are added to the particular instance of the object t hat you pipe to Add-Member or specify using the InputObject parameter. The additional member is available only while that instance exists. You can use the Export-Clixml cmdlet to save the instance, including the additional me mbers, to a file. The information stored in that file can be used by the Im port-Clixml cmdlet to re-create the instance of the object. PARAMETERS -Force [<SwitchParameter>] Adds a new member even if one with the same name already exists. Does n ot work for core members of a type. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the object to which the new member is added. Enter a variable that contains the objects, or type a command or expression that gets t he objects. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -MemberType <PSMemberTypes> Specifies the type of the member to add. This parameter is mandatory. The valid values for this parameter are: -- AliasProperty: A property that defines a new name for an existing pr operty. -- CodeMethod: A method that references a static method of a Microsoft .NET Framework class. -- CodeProperty: A property that references a static property of a .NET Framework class. -- MemberSet: A predefined collection of properties and methods, such a s PSBase, PSObject, and PSTypeNames. -- Method: A method of the underlying .NET Framework object. -- NoteProperty: A property with a static value. -- ParameterizedProperty: A property that takes parameters and paramete r values. -- Property: A property of the underlying .NET Framework object. -- PropertySet: A predefined collection of object properties. -- ScriptMethod: A method whose value is the output of a script. -- ScriptProperty: A property whose value is the output of a script. -- All: Gets all member types. -- Methods: Gets all types of methods of the object (e.g. method, codem ethod, scriptmethod) -- Properties: Gets all types of properties of the object (e.g. propert y, codeproperty, aliasproperty, scriptproperty). Not all objects have every type of member. If you specify a member type that the object does not have, Windows PowerShell returns an error. The Event member type is not valid for Add-Member. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? true -Name <string> Specifies the name of the member to be added. If you omit the "Name" parameter name, the value of the -Name parameter must be the second unnamed parameter value in the command. If you incl ude the parameter name, the parameters can appear in any order. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Passes the newly extended object to the pipeline. By default, this cmdl et does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SecondValue <Object> Specifies optional additional information about AliasProperty, ScriptPr operty, CodeProperty, or CodeMethod members. If used when adding an Ali asProperty, this parameter must be a data type. A conversion (cast) to the specified data type is added to the value of the AliasProperty. For example, if you add an AliasProperty that provides an alternate name f or a string property, you can also specify a SecondValue parameter of S ystem.Int32 to indicate that the value of that string property should b e converted to an integer when accessed by using the corresponding Alia sProperty. You can use the SecondValue parameter to specify an additional ScriptBl ock when adding a ScriptProperty member. In that case, the first Script Block, specified in the Value parameter, is used to get the value of a variable. The second ScriptBlock, specified in the SecondValue paramete r, is used to set the value of a variable. Required? false Position? 4 Default value Accept pipeline input? false Accept wildcard characters? false -Value <Object> Specifies the initial value of the added member. If you add an AliasPro perty, CodeProperty, or CodeMethod member, you can supply optional, add itional information by using the SecondValue parameter. Required? false Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object type to Add-Member. OUTPUTS None or System.Object When you use the PassThru parameter, Add-Member returns the newly-exten ded object. Otherwise, this cmdlet does not generate any output. NOTES You can add members only to PSObject objects. To determine if an object is a PSObject object, use the "is" operator. For example, to test an o bject stored in the $obj variable, type "$obj -is [PSObject]". The names of the MemberType, Name, Value, and SecondValue parameters ar e optional. If you omit the parameter names, the unnamed parameter valu es must appear in this order: MemberType, Name, Value, SecondValue. If you include the parameter names, the parameters can appear in any order -------------------------- EXAMPLE 1 -------------------------- C:\PS>$a = (get-childitem)[0] C:\PS> $a | add-member -membertype noteproperty -name Status -value done C:\PS> $a | get-member -type noteproperty TypeName: System.IO.DirectoryInfo Name MemberType Definition ---- ---------- ---------- PSChildName NoteProperty System.String PSChildName=Co PSDrive NoteProperty System.Management.Automation PSIsContainer NoteProperty System.Boolean PSIsContainer PSParentPath NoteProperty System.String PSParentPath=M PSPath NoteProperty System.String PSPath=Microso PSProvider NoteProperty System.Management.Automation Status NoteProperty System.String Status=done Description ----------- These commands add the Status note property to a DirectoryInfo object retur ned by Get-ChildItem and assigns it a value of "done". The first command gets the first object that Get-Childitem returns (index 0 ). The second command adds the note property. The third command uses a pipeline operator (|) to send the updated object t o the Get-Member cmdlet. The output shows that the property has been added. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$a = (get-childitem)[0] C:\PS> $a | add-member -membertype aliasproperty -name FileLength -value Le ngth C:\PS> $a.filelength Description ----------- These commands add the FileLength alias property to a DirectoryInfo object returned by Get-ChildItem. The new property is an alias for the Length prop erty. The first command gets the first object that Get-Childitem returns (index 0 ). The second command adds the alias property. The third command returns the value of the new FileLength property. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$a = "a string" C:\PS> $a = $a | add-member -membertype noteproperty -name StringUse -value Display -passthru C:\PS> $a.StringUse Description ----------- These commands add the StringUse a property to a string. Because the string is not a PSObject object, you must include the PassThru parameter in the c ommand to save the extended string in the variable. The last command in the example displays the new property. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$a = "this is a string" C:\PS> $a = add-member -inputobject $a -membertype scriptmethod -name words ` -value {$this.split()} -passthru C:\PS> $a.words() Description ----------- These commands add a script method to a string object. The script method ex poses the Split() method of the System.String .NET Framework Class Library class to make it convenient to return the individual words in a string by c alling a method named "Words" on the string object. Note that the PassThru parameter is specified to force Add-Member to return the extended string ob ject as output to be stored in the $a variable. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$event = get-eventlog -logname system -newest 1 C:\PS> $event.TimeWritten | get-member C:\PS> add-member -inputobject $event -membertype aliasproperty -name When ` -value TimeWritten -secondvalue System.String C:\PS> $event.When | get-member Description ----------- These commands add an AliasProperty to an EventLogEntry object returned by the Get-EventLog cmdlets. The AliasProperty is named "When" and is an alias for the TimeWritten property of the object. The SecondValue parameter is u sed to specify that the property value should be converted to type System.S tring when accessed by using the AliasProperty; the TimeWritten property is a DateTime object. The first command uses the Get-EventLog cmdlet to retrieve the most recent event from the System event log and stores it in the $event variable. The second command accesses the TimeWritten property of that event and pipe s it to the Get-Member cmdlet to demonstrate that the property is a DateTim e type. Add-Member is then used to add an AliasProperty member to the insta nce of the EventLogEntry object stored in the $event variable. The Name par ameter is used to set the name of the new member to "When" and the Value pa rameter is used to specify that it is an alias for the TimeWritten property . The SecondValue parameter is used to indicate that, when this new member is used, the value it returns should be cast from its original System.DateT ime type to a System.String type. The third command accesses the new member and pipes it to the Get-Member cm dlet to confirm that it is of type System.String. -------------------------- EXAMPLE 6 -------------------------- C:\PS>function Copy-Property ($From, $To) { foreach ($p in Get-Member -InputObject $From -MemberType Property) { Add-Member -InputObject $To -MemberType NoteProperty -Name $p.Name -Value $From.$($p.Name) -Force $To.$($p.Name) = $From.$($p.Name) } } Description ----------- This function copies all of the properties of one object to another object. The first command in the function declares the function name and lists its parameters. The Foreach loop uses the Get-Member cmdlet to get each of the properties o f the From object. The commands within the Foreach loop are performed in se ries on each of the properties. The Add-Member command adds the property of the From object to the To objec t as a NoteProperty. It uses the Force parameter to let the command add mem bers with the same member name. The last command in the function gives the new property the same name as th e original property. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113280 Get-Member Export-Clixml Import-Clixml Add-PSSnapin NAME Add-PSSnapin SYNOPSIS Adds one or more Windows PowerShell snap-ins to the current session. SYNTAX Add-PSSnapin [-Name] <string[]> [-PassThru] [<CommonParameters>] DESCRIPTION The Add-PSSnapin cmdlet adds registered Windows PowerShell snap-ins to the current session. After the snap-ins are added, you can use the cmdlets and providers that the snap-ins support in the current session. To add the snap-in to all future Windows PowerShell sessions, add an Add-PS Snapin command to your Windows PowerShell profile. For more information, se e about_Profiles. PARAMETERS -Name <string[]> Specifies the name of the snap-in. (This is the Name, not the AssemblyN ame or ModuleName.) To find the names of the registered snap-ins on your system, type: "get -pssnapin -registered". Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing each added snap-in. By default, this cmd let does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Add-PSSnapin. OUTPUTS None or System.Management.Automation.PSSnapInInfo When you use the PassThru parameter, Add-PSSnapin returns a PSSnapInInf o object that represents the snap-in. Otherwise, this cmdlet does not g enerate any output. NOTES For detailed information about snap-ins in Windows PowerShell, see abou t_PSSnapins. For information about how to create a Windows PowerShell s nap-in, see "How to Create a Windows PowerShell Snap-in" in the MSDN (M icrosoft Developer Network) library at http://go.microsoft.com/fwlink/? LinkId=144762. Add-PSSnapin adds the snap-in only to the current session. To add the s nap-in to all Windows PowerShell sessions, add it to your Windows Power Shell profile. For more information, see about_Profiles. You can add any Windows PowerShell snap-in that has been registered by using the Microsoft .NET Framework install utility. For more informatio n, see "How to Register Cmdlets, Providers, and Host Applications" in t he MSDN library at http://go.microsoft.com/fwlink/?LinkID=143619. To get a list of snap-ins that are registered on your computer, type "g et-pssnapin -registered". Before adding a snap-in, Add-PSSnapin checks the version of the snap-in to verify that it is compatible with the current version of Windows Po werShell. If the snap-in fails the version check, Windows PowerShell re ports an error. -------------------------- EXAMPLE 1 -------------------------- C:\PS>add-PSSnapIn Microsoft.Exchange, Microsoft.Windows.AD Description ----------- This command adds the Microsoft Exchange and Active Directory snap-ins to t he current session. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-pssnapin -registered | add-pssnapin -passthru Description ----------- This command adds all of the registered Windows PowerShell snap-ins to the session. It uses the Get-PSSnapin cmdlet with the Registered parameter to g et objects representing each of the registered snap-ins. The pipeline opera tor (|) passes the result to Add-PSSnapin, which adds them to the session. The PassThru parameter returns objects that represent each of the added sna p-ins. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-pssnapin Description ----------- This example demonstrates the process of registering a snap-in on your syst em and then adding it to your session. It uses ManagementFeatures, a fictit ious snap-in implemented in a file called ManagementCmdlets.dll. The first command gets snap-ins that have been added to the current session , including the snap-ins that are installed with Windows PowerShell. In thi s example, ManagementFeatures is not returned. This indicates that it has n ot been added to the session. get-pssnapin The second command gets snap-ins that have been registered on your system ( including those that have already been added to the session). It does not i nclude the snap-ins that are installed with Windows PowerShell. get-pssnapin -registered In this case, the command does not return any snap-ins. This indicates that the ManagementFeatures snapin has not been registered on the system. The third command creates an alias, "installutil", for the path to the Inst allUtil tool in the .NET Framework. set-alias installutil $env:windir\Microsoft.NET\Framework\v2.0.50727\in stallutil.exe The fourth command uses the InstallUtil tool to register the snap-in. The c ommand specifies the path to ManagementCmdlets.dll, the file name or "modul e name" of the snap-in. installutil C:\Dev\Management\ManagementCmdlets.dll The fifth command is the same as the second command. This time, you use it to verify that the ManagementCmdlets snap-in is registered. get-pssnapin -registered The sixth command uses the Add-PSSnapin cmdlet to add the ManagementFeature s snap-in to the session. It specifies the name of the snap-in, ManagementF eatures, not the file name. add-pssnapin ManagementFeatures To verify that the snap-in is added to the session, the seventh command use s the Module parameter of the Get-Command cmdlet. It displays the items tha t were added to the session by a snap-in or module. get-command -module ManagementFeatures You can also use the PSSnapin property of the object that Get-Command retur ns to find the snap-in or module in which a cmdlet originated. The eighth c ommand uses dot notation to find the value of the PSSnapin property of the Set-Alias command. (get-command set-alias).pssnapin RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113281 Get-PSSnapin Remove-PSSnapin about_Profiles Add-Type NAME Add-Type SYNOPSIS Adds a Microsoft .NET Framework type (a class) to a Windows PowerShell sess ion. SYNTAX Add-Type -AssemblyName <string[]> [-IgnoreWarnings] [-PassThru] [<CommonPar ameters>] Add-Type [-Name] <string> [-MemberDefinition] <string[]> [-CodeDomProvider <CodeDomProvider>] [-CompilerParameters <CompilerParameters>] [-Language {C Sharp | CSharpVersion3 | VisualBasic | JScript}] [-Namespace <string>] [-Ou tputAssembly <string>] [-OutputType <OutputAssemblyType>] [-ReferencedAssem blies <string[]>] [-UsingNamespace <string[]>] [-IgnoreWarnings] [-PassThru ] [<CommonParameters>] Add-Type [-Path] <string[]> [-CompilerParameters <CompilerParameters>] [-Ou tputAssembly <string>] [-OutputType <OutputAssemblyType>] [-ReferencedAssem blies <string[]>] [-IgnoreWarnings] [-PassThru] [<CommonParameters>] Add-Type [-TypeDefinition] <string> [-CodeDomProvider <CodeDomProvider>] [- CompilerParameters <CompilerParameters>] [-Language {CSharp | CSharpVersion 3 | VisualBasic | JScript}] [-OutputAssembly <string>] [-OutputType <Output AssemblyType>] [-ReferencedAssemblies <string[]>] [-IgnoreWarnings] [-PassT hru] [<CommonParameters>] DESCRIPTION The Add-Type cmdlet lets you define a .NET Framework class in your Windows PowerShell session. You can then instantiate objects (by using the New-Obje ct cmdlet) and use the objects, just as you would use any .NET Framework ob ject. If you add an Add-Type command to your Windows PowerShell profile, t he class will be available in all Windows PowerShell sessions. You can specify the type by specifying an existing assembly or source code files, or you can specify the source code inline or saved in a variable. Yo u can even specify only a method and Add-Type will define and generate the class. You can use this feature to make Platform Invoke (P/Invoke) calls to unmanaged functions in Windows PowerShell. If you specify source code, Add -Type compiles the specified source code and generates an in-memory assembl y that contains the new .NET Framework types. You can use the parameters of Add-Type to specify an alternate language and compiler (CSharp is the default), compiler options, assembly dependencies, the class namespace, the names of the type, and the resulting assembly. PARAMETERS -AssemblyName <string[]> Specifies the name of an assembly that includes the types. Add-Type tak es the types from the specified assembly. This parameter is required wh en you are creating types based on an assembly name. Enter the full or simple name (also known as the "partial name") of an assembly. Wildcard characters are permitted in the assembly name. If yo u enter a simple or partial name, Add-Type resolves it to the full name , and then uses the full name to load the assembly. This parameter does not accept a path or file name. To enter the path t o the assembly dynamic-link library (DLL) file, use the Path parameter. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? true -CodeDomProvider <CodeDomProvider> Specifies a code generator or compiler. Add-Type uses the specified com piler to compile the source code. The default is the CSharp compiler. Use this parameter if you are using a language that cannot be specified by using the Language parameter. The CodeDomProvider that you specify must be able to generate assemblies from source code. Required? false Position? named Default value CSharp compiler Accept pipeline input? false Accept wildcard characters? false -CompilerParameters <CompilerParameters> Specifies the options for the source code compiler. These options are s ent to the compiler without revision. This parameter allows you to direct the compiler to generate an executa ble file, embed resources, or set command-line options, such as the "/u nsafe" option. This parameter implements the CompilerParameters class ( System.CodeDom.Compiler.CompilerParameters). Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -IgnoreWarnings [<SwitchParameter>] Ignores compiler warnings. Use this parameter to prevent Add-Type from handling compiler warnings as errors. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Language <Language> Specifies the language used in the source code. Add-Type uses the lang uage to select the correct code compiler. Valid values are "CSharp", "CSharpVersion3", "VisualBasic", and "JScrip t". "CSharp" is the default. Required? false Position? named Default value CSharp Accept pipeline input? false Accept wildcard characters? false -MemberDefinition <string[]> Specifies new properties or methods for the class. Add-Type generates t he template code that is required to support the properties or methods. You can use this feature to make Platform Invoke (P/Invoke) calls to un managed functions in Windows PowerShell. For more information, see the examples. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies the name of the class to create. This parameter is required w hen generating a type from a member definition. The type name and namespace must be unique within a session. You cannot unload a type or change it. If you need to change the code for a type, you must change the name or start a new Windows PowerShell session. Ot herwise, the command fails. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Namespace <string> Specifies a namespace for the type. If this parameter is not included in the command, the type is created i n the Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes namespac e. If the parameter is included in the command with an empty string val ue or a value of $null, the type is generated in the global namespace. Required? false Position? named Default value Microsoft.PowerShell.Commands.AddType.Auto GeneratedTypes Accept pipeline input? false Accept wildcard characters? false -OutputAssembly <string> Generates a DLL file for the assembly with the specified name in the lo cation. Enter a path (optional) and file name. Wildcard characters are permitted. By default, Add-Type generates the assembly only in memory. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -OutputType <OutputAssemblyType> Specifies the output type of the output assembly. Valid values are Lib rary, ConsoleApplication, and WindowsApplication. By default, no output type is specified. This parameter is valid only when an output assembly is specified in th e command. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns a System.Runtime object that represents the types that were add ed. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to source code files or assembly DLL files that cont ain the types. If you submit source code files, Add-Type compiles the code in the file s and creates an in-memory assembly of the types. The file name extensi on specified in the value of Path determines the compiler that Add-Type uses. If you submit an assembly file, Add-Type takes the types from the assem bly. To specify an in-memory assembly or the global assembly cache, use the AssemblyName parameter. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -ReferencedAssemblies <string[]> Specifies the assemblies upon which the type depends. By default, Add-T ype references System.dll and System.Management.Automation.dll. The ass emblies that you specify by using this parameter are referenced in addi tion to the default assemblies. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -TypeDefinition <string> Specifies the source code that contains the type definitions. Enter the source code in a string or here-string, or enter a variable that conta ins the source code. For more information about here-strings, see about _Quoting_Rules. Include a namespace declaration in your type definition. If you omit th e namespace declaration, your type might have the same name as another type or the shortcut for another type, causing an unintentional overwri te. For example, if you define a type called "Exception", scripts that use "Exception" as the shortcut for System.Exception will fail. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -UsingNamespace <string[]> Specifies other namespaces that are required for the class. This is muc h like the Using keyword in C#. By default, Add-Type references the System namespace. When the MemberDe finition parameter is used, Add-Type also references the System.Runtime .InteropServices namespace by default. The namespaces that you add by u sing the UsingNamespace parameter are referenced in addition to the def ault namespaces. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Add-Type. OUTPUTS None or System.RuntimeType When you use the PassThru parameter, Add-Type returns a System.RuntimeT ype object that represents the new type. Otherwise, this cmdlet does no t generate any output. NOTES The types that you add exist only in the current session. To use the t ypes in all sessions, add them to your Windows PowerShell profile. For more information about the profile, see about_Profiles. Type names (and namespaces) must be unique within a session. You canno t unload a type or change it. If you need to change the code for a type , you must change the name or start a new Windows PowerShell session. O therwise, the command fails. The CodeDomProvider class for some languages, such as IronPython and JS harp, does not generate output. As a result, types written in these lan guages cannot be used with Add-Type. This cmdlet is based on the CodeDomProvider class. For more information about this class, see the Microsoft .NET Framework SDK. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$source = @" public class BasicTest { public static int Add(int a, int b) { return (a + b); } public int Multiply(int a, int b) { return (a * b); } } "@ C:\PS> Add-Type -TypeDefinition $source C:\PS> [BasicTest]::Add(4, 3) C:\PS> $basicTestObject = New-Object BasicTest C:\PS> $basicTestObject.Multiply(5, 2) Description ----------- These commands add the BasicTest class to the session by specifying source code that is stored in a variable. The type has a static method called Add and a non-static method called Multiply. The first command stores the source code for the class in the $source varia ble. The second command uses the Add-Type cmdlet to add the class to the session . Because it is using inline source code, the command uses the TypeDefiniti on parameter to specify the code in the $source variable. The remaining commands use the new class. The third command calls the Add static method of the BasicTest class. It us es the double-colon characters (::) to specify a static member of the class . The fourth command uses the New-Object cmdlet to instantiate an instance of the BasicTest class. It saves the new object in the $basicTestObject varia ble. The fifth command uses the Multiply method of $basicTestObject. -------------------------- EXAMPLE 2 -------------------------- C:\PS>[BasicTest] | get-member C:\PS> [BasicTest] | get-member -static C:\PS> $basicTestObject | get-member C:\PS> [BasicTest] | get-member TypeName: System.RuntimeType Name MemberType Definition ---- ---------- ---------- Clone Method System.Object Clone() Equals Method System.Boolean Equals FindInterfaces Method System.Type[] FindInt ... C:\PS> [BasicTest] | get-member -static TypeName: BasicTest Name MemberType Definition ---- ---------- ---------- Add Method static System.Int32 Add(Int32 a, Int32 b) Equals Method static System.Boolean Equals(Object objA, ReferenceEquals Method static System.Boolean ReferenceEquals(Obj C:\PS> $basicTestObject | get-member TypeName: BasicTest Name MemberType Definition ---- ---------- ---------- Equals Method System.Boolean Equals(Object obj) GetHashCode Method System.Int32 GetHashCode() GetType Method System.Type GetType() Multiply Method System.Int32 Multiply(Int32 a, Int32 b) ToString Method System.String ToString() Description ----------- These commands use the Get-Member cmdlet to examine the objects that the Ad d-Type and New-Object cmdlets created in the previous example. The first command uses the Get-Member cmdlet to get the type and members of the BasicTest class that Add-Type added to the session. The Get-Member com mand reveals that it is a System.RuntimeType object, which is derived from the System.Object class. The second command uses the Static parameter of Get-Member to get the stati c properties and methods of the BasicTest class. The output shows that the Add method is included. The third command uses Get-Member to get the members of the object stored i n the $BasicTestObject variable. This was the object instance that was crea ted by using the New-Object cmdlet with the $BasicType class. The output reveals that the value of the $basicTestObject variable is an in stance of the BasicTest class and that it includes a member called Multiply . -------------------------- EXAMPLE 3 -------------------------- C:\PS>$accType = add-type -assemblyname accessib* -passthru Description ----------- This command adds the classes from the Accessibility assembly to the curren t session. The command uses the AssemblyName parameter to specify the name of the assembly. The wildcard character allows you to get the correct assem bly even when you are not sure of the name or its spelling. The command uses the PassThru parameter to generate objects that represent the classes that are added to the session, and it saves the objects in the $accType variable. -------------------------- EXAMPLE 4 -------------------------- C:\PS>add-type -path c:\ps-test\Hello.vb [VBFromFile]::SayHello(", World") # From Hello.vb Public Class VBFromFile Public Shared Function SayHello(sourceName As String) As String Dim myValue As String = "Hello" return myValue + sourceName End Function End Class C:\PS> [VBFromFile]::SayHello(", World") Hello, World Description ----------- This example uses the Add-Type cmdlet to add the VBFromFile class that is d efined in the Hello.vb file to the current session. The text of the Hello.v b file is shown in the command output. The first command uses the Add-Type cmdlet to add the type defined in the H ello.vb file to the current session. The command uses the path parameter to specify the source file. The second command calls the SayHello function as a static method of the VB FromFile class. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$signature = @" [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); "@ $showWindowAsync = Add-Type -memberDefinition $signature -name "Win32ShowWi ndowAsync" -namespace Win32Functions -passThru # Minimize the Windows PowerShell console $showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 2) # Restore it $showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 4) Description ----------- The commands in this example demonstrate how to call native Windows APIs in Windows PowerShell. Add-Type uses the Platform Invoke (P/Invoke) mechanism to call a function in User32.dll from Windows PowerShell. The first command stores the C# signature of the ShowWindowAsync function i n the $signature variable. (For more information, see "ShowWindowAsync Func tion" in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=143643. ) To ensure that the resulting method will be visible in a Windows PowerShe ll session, the "public" keyword has been added to the standard signature. The second command uses the Add-Type cmdlet to add the ShowWindowAsync func tion to the Windows PowerShell session as a static method of a class that A dd-Type creates. The command uses the MemberDefinition parameter to specify the method definition saved in the $signature variable. The command uses the Name and Namespace parameters to specify a name and na mespace for the class. It uses the PassThru parameter to generate an object that represents the types, and it saves the object in the $showWindowAsync variable. The third and fourth commands use the new ShowWindowAsync static method. Th e method takes two parameters, the window handle, and an integer specifies how the window is to be shown. The third command calls ShowWindowAsync. It uses the Get-Process cmdlet wit h the $pid automatic variable to get the process that is hosting the curren t Windows PowerShell session. Then it uses the MainWindowHandle property of the current process and a value of "2", which represents the SW_MINIMIZE v alue. To restore the window, the fourth command use a value of "4" for the window position, which represents the SW_RESTORE value. (SW_MAXIMIZE is 3.) -------------------------- EXAMPLE 6 -------------------------- C:\PS>Add-Type -MemberDefinition $jsMethod -Name "PrintInfo" -Language JScr ipt Description ----------- This command uses the Add-Type cmdlet to add a method from inline JScript c ode to the Windows PowerShell session. It uses the MemberDefinition paramet er to submit source code stored in the $jsMethod variable. It uses the Name variable to specify a name for the class that Add-Type creates for the met hod and the Language parameter to specify the JScript language. -------------------------- EXAMPLE 7 -------------------------- C:\PS>Add-Type -Path FSharp.Compiler.CodeDom.dll C:\PS> Add-Type -Path FSharp.Compiler.CodeDom.dll C:\PS> $provider = New-Object Microsoft.FSharp.Compiler.CodeDom.FSharpCodeP rovider C:\PS> $fSharpCode = @" let rec loop n = if n <= 0 then () else begin print_endline (string_of_int n); loop (n-1) end "@ C:\PS> $fsharpType = Add-Type -TypeDefinition $fSharpCode -CodeDomProvider $provider -PassThru | where { $_.IsPublic } C:\PS> $fsharpType::loop(4) 4 3 2 1 Description ----------- This example shows how to use the Add-Type cmdlet to add an FSharp code com piler to your Windows PowerShell session. To run this example in Windows Po werShell, you must have the FSharp.Compiler.CodeDom.dll that is installed w ith the FSharp language. The first command in the example uses the Add-Type cmdlet with the Path par ameter to specify an assembly. Add-Type gets the types in the assembly. The second command uses the New-Object cmdlet to create an instance of the FSharp code provider and saves the result in the $provider variable. The third command saves the FSharp code that defines the Loop method in the $FSharpCode variable. The fourth command uses the Add-Type cmdlet to save the public types define d in $fSharpCode in the $fSharpType variable. The TypeDefinition parameter specifies the source code that defines the types. The CodeDomProvider param eter specifies the source code compiler. The PassThru parameter directs Add-Type to return a Runtime object that rep resents the types and a pipeline operator (|) sends the Runtime object to t he Where-Object cmdlet, which returns only the public types. The Where-Obje ct filter is used because the FSharp provider generates non-public types to support the resulting public type. The fifth command calls the Loop method as a static method of the type stor ed in the $fSharpType variable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135195 Add-Member New-Object Alias PROVIDER NAME Alias DRIVES Alias: SYNOPSIS Provides access to the Windows PowerShell aliases and the values that they represent. DESCRIPTION The Windows PowerShell Alias provider lets you get, add, change, clear, and delete aliases in Windows PowerShell. An alias is an alternate name for a cmdlet, function, or executable file. W indows PowerShell includes a set of built-in aliases. And, you can add your own aliases to the current session and to your Windows PowerShell profile. The Alias provider is a flat namespace that contains only the alias objects . The aliases have no child items. Each alias is an instance of the System.Management.Automation.AliasInfo cla ss. The Alias provider exposes its data store in the Alias: drive. To work with aliases, you can change your location to the Alias: drive by using the fol lowing command: set-location alias: Or, you can work from any other Windows PowerShell drive. To reference an a lias from another location, use the Alias: drive name in the path. Windows PowerShell includes a set of cmdlets that are designed to view and to change aliases: Export-Alias Get-Alias Import-Alias New-Alias Set-Alias When you use these cmdlets, you do not need to specify the Alias: drive in the name. The Alias provider supports all the cmdlets that have the Item noun except for the Invoke-Item cmdlet. And, it supports the Get-Content and Set-Conten t cmdlets. The Alias provider does not support the cmdlets that have the It emProperty noun. And, the Alias provider does not support the Filter parame ter in any cmdlet. All changes to the aliases affect the current session only. To save the cha nges, add the changes to the Windows PowerShell profile. Or, use the Export -Alias and Import-Alias cmdlets. CAPABILITIES TASKS TASK: Getting to the Alias: Drive -------------------------- EXAMPLE 1 -------------------------- This command changes the current location to the Alias: drive. You can use this command from any drive in Windows PowerShell. To return to a f ile system drive, type the drive name. For example, type "set-location c:". set-location alias: TASK: Getting Aliases -------------------------- EXAMPLE 1 -------------------------- This command gets a list of all the aliases in the current session. You can use this command in any Windows PowerShell drive. get-item -path alias: -------------------------- EXAMPLE 2 -------------------------- This command gets the "ls" alias. Because it includes the path, you can use it in any Windows PowerShell drive. get-item -path alias:ls If you are in the Alias: drive, you can omit the drive name from the pa th. -------------------------- EXAMPLE 3 -------------------------- This command gets a list of the aliases that are associated with the Ge t-ChildItem cmdlet. It uses the Definition property, which stores the c mdlet name. get-item -path alias:* | where-object {$_.Definition -eq "Get-Childitem "} When the aliased item is an executable file, the Definition contains th e fully qualified path of the file. -------------------------- EXAMPLE 4 -------------------------- This command gets the list of all the aliases when the current location is the Alias: drive. It uses a wildcard character (*) to indicate all the contents of the current location. get-item -path * In the Alias: drive, a dot (.), which represents the current location, and a wildcard character (*), which represents all items in the current location, have the same effect. For example, "get-item -path ." or "ge t-item *" produce the same result. TASK: Creating a New Alias -------------------------- EXAMPLE 1 -------------------------- This command creates the "serv" alias for the Get-Service cmdlet. Becau se the current location is in the Alias: drive, the value of the Path p arameter is a dot (.). The dot represents the current location. This command also uses the Options dynamic parameter to set the AllScop e and Constant options on the alias. The Options parameter is available in the New-Item cmdlet only when you are in the Alias: drive. new-item -path . -name serv -value Get-Service -Options "AllScope,Const ant" If you are in the Alias: drive, you can omit the drive name from the pa th. -------------------------- EXAMPLE 2 -------------------------- You can create an alias for any item that invokes a command. This comma nd creates the "np" alias for Notepad.exe. new-item -path alias:np -value c:\windows\notepad.exe -------------------------- EXAMPLE 3 -------------------------- You can create an alias for any function. You can use this feature to c reate an alias that includes both a cmdlet and its parameters. The first command creates the CD32 function, which changes the current directory to the System32 directory. The second command creates the "go " alias for the CD32 function. The semi-colon (;) is the command separa tor. When the command is complete, you can use either "CD32" or "go" to invo ke the function. function CD32 {set-location -path c:\windows\system32} set-item -path a lias:go -value CD32 TASK: Displaying the Properties and Methods of Aliases -------------------------- EXAMPLE 1 -------------------------- This command uses the Get-Item cmdlet to get all aliases. The pipeline operator (|) sends the results to the Get-Member cmdlet, which displays the methods and properties of the object. get-item -path alias:* | get-member When you pipe a collection of objects to Get-Member, such as the collec tion of aliases in the Alias: drive, Get-Member evaluates each object i n the collection separately. Then, Get-Member returns information about each object type that it finds. If all the objects are of the same typ e, it returns information about the single object type. In this case, a ll the aliases are AliasInfo objects. To get information about the collection of AliasInfo objects, use the I nputObject parameter of Get-Member. For example, use the following comm and: Get-Member -InputObject (Get-Item alias:*) When you use InputObject, Get-Member evaluates the collection, not the objects in the collection. -------------------------- EXAMPLE 2 -------------------------- This command lists the values of the properties of the "dir" alias. It uses the Get-Item cmdlet to get an object that represents the "dir" ali as. The pipeline operator (|) sends the results to the Format-List comm and. The Format-List command uses the Property parameter with a wildcar d character (*) to format and display the values of all the "dir" alias properties. get-item alias:dir | format-list -property * TASK: Changing the Properties of an Alias -------------------------- EXAMPLE 1 -------------------------- You can use the Set-Item cmdlet with the Options dynamic parameter to c hange the value of the Options property of an alias. This command sets the AllScope and ReadOnly options for the "dir" alias . The command uses the Options dynamic parameter of the Set-Item cmdlet . The Options parameter is available in Set-Item only when you use it w ith the Alias or Function provider. set-item -path alias:dir -options "AllScope,ReadOnly" -------------------------- EXAMPLE 2 -------------------------- This command uses the Set-Item cmdlet to change the "gp" alias so that it represents the Get-Process cmdlet instead of the Get-ItemProperty cm dlet. The Force parameter is required because the value of the Options property of the "gp" alias is set to ReadOnly. Because the command is s ubmitted from within the Alias: drive, the drive is not specified in th e path. set-item -path gp -value get-process -force The change affects the four properties that define the association betw een the alias and the command. To view the effect of the change, type t he following command: get-item -path gp | format-list -property * -------------------------- EXAMPLE 3 -------------------------- This command uses the Rename-Item cmdlet to change the "popd" alias to "pop". rename-item -path alias:popd -newname pop TASK: Copying an Alias -------------------------- EXAMPLE 1 -------------------------- This command copies the pushd alias so that a new push alias is created for the Push-Location cmdlet. copy-item -path alias:pushd -destination alias:push When the new alias is created, its Description property has a null valu e. And, its Option property has a value of None. If the command is issued from within the Alias: drive, you can omit the drive name from the value of the Path parameter. TASK: Deleting an Alias -------------------------- EXAMPLE 1 -------------------------- This command deletes the serv alias from the current session. You can u se this command in any Windows PowerShell drive. remove-item -path alias:serv If you are in the Alias: drive, you can omit the drive name from the pa th. -------------------------- EXAMPLE 2 -------------------------- This command deletes aliases that begin with "s". It does not delete re ad-only aliases. clear-item -path alias:s* -------------------------- EXAMPLE 3 -------------------------- This command deletes all aliases from the current session, except those with a value of Constant for their Options property. Without the Force parameter, the command does not delete aliases whose Options property has a value of ReadOnly. remove-item alias:* -force DYNAMIC PARAMETERS -Options <System.Management.Automation.ScopedItemOptions> Determines the value of the Options property of an alias. None No options. This value is the default. Constant The alias cannot be deleted and its properties cannot be change d. Constant is available only when you create an alias. You can not change the option of an existing alias to Constant. Private The alias is visible only in the current scope, not in the chil d scopes. ReadOnly The properties of the alias cannot be changed except by using t he Force parameter. You can use Remove-Item to delete the alias . AllScope The alias is copied to any new scopes that are created. Cmdlets Supported: New-Item, Set-Item NOTES RELATED LINKS about_Aliases about_Providers cd.. cd.. cd\ cd\ Certificate PROVIDER NAME Certificate DRIVES Cert: SYNOPSIS Provides access to X.509 certificate stores and certificates from within Wi ndows PowerShell. DESCRIPTION The Windows PowerShell security strategy supports the use of Authenticode s ignatures to sign scripts using X.509-encoded digital public key certificat es. The signing features of Windows PowerShell are not intended to be compl ete, but they enable users to sign scripts and enable Windows PowerShell to recognize signed and unsigned scripts and to determine whether the scripts originate on the Internet. The Windows PowerShell Certificate provider lets you navigate the certifica te namespace and view the certificate stores and certificates. It also lets you copy, move, and delete certificates and certificate stores, and it let s you open the Certificates snap-in for the Microsoft Management Console (M MC). The Certificate provider exposes the certificate namespace as the Cert: dri ve in Windows PowerShell. The Cert: drive has the following three levels: -- Store locations (Microsoft.PowerShell.Commands.X509StoreLocation), whic h are high-level containers that group the certificates for the current use r and for all users. Each system has a CurrentUser and LocalMachine (all us ers) store location. -- Certificates stores (System.Security.Cryptography.X509Certificates.X509S tore), which are physical stores in which certificates are saved and manage d. -- X.509 certificates (System.Security.Cryptography.X509Certificates.X509Ce rtificate2), each of which represent an X.509 certificate on the computer. Certificates are identified by their thumbprints. The Windows PowerShell Certificate provider supports the Set-Location, Get- Location, Get-Item, Get-ChildItem, and Invoke-Item cmdlets. In addition, the Windows PowerShell Security snap-in (Microsoft.PowerShell. Security), which includes the Certificate provider, also includes snap-ins to get and set Authenticode signatures and to get certificates. For a list of cmdlets in the Security snap-in, type "get-command -module *security". CAPABILITIES TASKS TASK: Navigating the Cert: Drive -------------------------- EXAMPLE 1 -------------------------- This command uses the Set-Location cmdlet to change the current locatio n to the Cert: drive. set-location cert: -------------------------- EXAMPLE 2 -------------------------- This command uses the Set-Location command to change the current locati on to the Root certificate store in the LocalMachine store location. Us e a backslash (\) or a forward slash (/) to indicate a level of the Cer t: drive. set-location -path LocalMachine\Root If you are not in the Cert: drive, begin the path with the drive name. TASK: Displaying the Contents of the Cert: Drive -------------------------- EXAMPLE 1 -------------------------- This command uses the Get-ChildItem cmdlet to display the certificate s tores in the CurrentUser certificate store location. get-childitem -path cert:\CurrentUser If you are in the Cert: drive, you can omit the drive name. -------------------------- EXAMPLE 2 -------------------------- This command uses the Get-ChildItem cmdlet to display the certificates in the My certificate store. get-childitem -path cert:\CurrentUser\My If you are in the Cert: drive, you can omit the drive name. -------------------------- EXAMPLE 3 -------------------------- This command uses the Get-Item cmdlet to get the "My" certificate store and the Property parameter of Format-List with a wildcard character (* ) to display all of the properties of the store. get-item -path cert:\CurrentUser\My | format-list * -------------------------- EXAMPLE 4 -------------------------- This command gets a certificate and displays all of its properties. It uses the Get-ChildItem cmdlet to get the certificate and the Property p arameter of Format-List with a wildcard character (*) to display all of the properties of the certificate. The certificate is identified by its thumbprint. get-childitem -path cert:\CurrentUser\my\6B8223358119BB08840DEE50FD8AF9 EA776CE66B | format-list -property * -------------------------- EXAMPLE 5 -------------------------- This command uses the Get-ChildItem cmdlet to get all of the certificat es on the computer and its CodeSigningCert dynamic parameter to get onl y the certificates that have code-signing authority. get-childitem -path * -codesigningcert -recurse TASK: Opening the Certificates MMC Snap-in -------------------------- EXAMPLE 1 -------------------------- This command opens the Certificates MMC snap-in to manage the specified certificate. invoke item cert:\CurrentUser\my\6B8223358119BB08840DEE50FD8AF9EA776CE6 6B DYNAMIC PARAMETERS -CodeSigningCert <System.Management.Automation.SwitchParameter> Gets only those certificates with code-signing authority. Cmdlets Supported: Get-Item, Get-ChildItem NOTES RELATED LINKS about_Providers about_Signing Get-AuthenticodeSignature Set-AuthenticodeSignature Get-PfxCertificate Checkpoint-Computer NAME Checkpoint-Computer SYNOPSIS Creates a system restore point on the local computer. SYNTAX Checkpoint-Computer [-Description] <string> [[-RestorePointType] <string>] [<CommonParameters>] DESCRIPTION The Checkpoint-Computer cmdlet creates a system restore point on the local computer. This cmdlet runs only on Windows Vista and Windows XP. PARAMETERS -Description <string> Specifies a descriptive name for the restore point. This parameter is r equired. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -RestorePointType <string> Specifies the type of restore point. The default is APPLICATION_INSTALL . Valid values are APPLICATION_INSTALL, APPLICATION_UNINSTALL, DEVICE_DRI VER_INSTALL, MODIFY_SETTINGS, and CANCELLED_OPERATION. Required? false Position? 2 Default value APPLICATION_INSTALL Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Checkpoint-Computer. OUTPUTS None This cmdlet does not generate any output. NOTES This cmdlet uses the CreateRestorePoint method of the SystemRestore cla ss with a BEGIN_SYSTEM_CHANGE event. -------------------------- EXAMPLE 1 -------------------------- C:\PS>checkpoint-computer -description "Install MyApp" Description ----------- This command creates a system restore point called "Install MyApp". It uses the default APPLICATION_INSTALL restore point type. -------------------------- EXAMPLE 2 -------------------------- C:\PS>checkpoint-computer -description "ChangeNetSettings" -RestorePointTyp e MODIFY_SETTINGS Description ----------- This command creates a MODIFY_SETTINGS system restore point called "ChangeN etSettings". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135197 Add-Computer Remove-Computer Restart-Computer Restore-Computer Stop-Computer Test-Connection Clear-Content NAME Clear-Content SYNOPSIS Deletes the contents of an item, such as deleting the text from a file, but does not delete the item. SYNTAX Clear-Content [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Excl ude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm ] [-WhatIf] [-UseTransaction] [<CommonParameters>] Clear-Content [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <st ring[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [-Wha tIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Clear-Content cmdlet deletes the contents of an item, such as deleting the text from a file, but it does not delete the item. As a result, the ite m exists, but it is empty. Clear-Content is similar to Clear-Item, but it w orks on files instead of on aliases and variables. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to clear the file contents even if the file is read-o nly. Implementation varies from provider to provider. For more informat ion, see about_Providers. Even using the Force parameter, the cmdlet ca nnot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Clears only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". W ildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies the paths to the items from which content is deleted. Unlike Path, the value of LiteralPath is used exactly as it is typed. No chara cters are interpreted as wildcards. If the path includes escape charact ers, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the paths to the items from which content is deleted. Wildcar ds are permitted. The paths must be paths to items, not to containers. For example, you must specify a path to one or more files, not a path t o a directory. Wildcards are permitted. This parameter is required, but the parameter name ("Path") is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Clear-Content. OUTPUTS None This cmdlet does not return any objects. NOTES You can also refer to Clear-Content by its built-in alias, "clc". For m ore information, see about_Aliases. If you omit the -Path parameter name, the value of Path must be the fir st parameter in the command. For example, "clear-content c:\mydir\*.txt ". If you include the parameter name, you can list the parameters in an y order. You can use Clear-Content with the Windows PowerShell File System provi der and with other providers that manipulate content. To clear items th at are not considered to be content, such as items managed by the Windo ws PowerShell Certificate or Registry providers, use Clear-Item. The Clear-Content cmdlet is designed to work with the data exposed by a ny provider. To list the providers available in your session, type "Get -PsProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>clear-content ..\SmpUsers\*\init.txt Description ----------- This command deletes all of the content from the "init.txt" files in all su bdirectories of the SmpUsers directory. The files are not deleted, but they are empty. -------------------------- EXAMPLE 2 -------------------------- C:\PS>clear-content -path * -filter *.log -force Description ----------- This command deletes the contents of all files in the current directory wit h the ".log" file name extension, including files with the read-only attrib ute. The asterisk (*) in the path represents all items in the current direc tory. The Force parameter makes the command effective on read-only files. U sing a filter to restrict the command to files with the ".log" file name ex tension instead of specifying "*.log" in the path makes the operation faste r. -------------------------- EXAMPLE 3 -------------------------- C:\PS>clear-content c:\Temp\* -Include Smp* -Exclude *2* -whatif Description ----------- This command requests a prediction of what would happen if you submitted th e command: "clear-content c:\temp\* -include smp* -exclude *2*". The result lists the files that would be cleared; in this case, files in the Temp dir ectory whose names begin with "Smp", unless the file names include a "2". T o execute the command, run it again without the Whatif parameter. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113282 about_Providers Get-Content Set-Content Add-Content Get-Item Clear-EventLog NAME Clear-EventLog SYNOPSIS Deletes all entries from specified event logs on the local or remote comput ers. SYNTAX Clear-EventLog [-LogName] <string[]> [[-ComputerName] <string[]>] [-Confirm ] [-WhatIf] [<CommonParameters>] DESCRIPTION The Clear-EventLog cmdlet deletes all of the entries from the specified eve nt logs on the local computer or on remote computers. To use Clear-EventLog , you must be a member of the Administrators group on the affected computer . The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinE vent. PARAMETERS -ComputerName <string[]> Specifies a remote computer. The default is the local computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qu alified domain name of a remote computer. To specify the local computer , type the computer name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Get-EventLog even if your computer is n ot configured to run remote commands. Required? false Position? 2 Default value Local computer Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -LogName <string[]> Specifies the event logs. Enter the log name (the value of the Log prop erty; not the LogDisplayName) of one or more event logs, separated by c ommas. Wildcard characters are not permitted. This parameter is requir ed. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Clear-EventLog. OUTPUTS None This cmdlet does not generate any output. NOTES To use Clear-EventLog on Windows Vista and later versions of Windows, s tart Windows PowerShell with the "Run as administrator" option. -------------------------- EXAMPLE 1 -------------------------- C:\PS>clear-eventlog "Windows PowerShell" Description ----------- This command deletes the entries from the "Windows PowerShell" event log on the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>clear-eventlog -logname ODiag, OSession -computername localhost, Serv er02 Description ----------- This command deletes all of the entries in the Microsoft Office Diagnostics (ODiag) and Microsoft Office Sessions (OSession) logs on the local compute r and the Server02 remote computer. -------------------------- EXAMPLE 3 -------------------------- C:\PS>clear-eventlog -log application, system -confirm Description ----------- This command prompts you for confirmation before deleting the entries in th e specified event logs. -------------------------- EXAMPLE 4 -------------------------- C:\PS>function clear-all-event-logs ($computerName="localhost") { $logs = get-eventlog -computername $computername -list | foreach {$_.Lo g} $logs | foreach {clear-eventlog -comp $computername -log $_ } get-eventlog -computername $computername -list } C:\PS> clear-all-event-logs -comp Server01 Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 15,168 0 OverwriteAsNeeded 0 Application 15,168 0 OverwriteAsNeeded 0 DFS Replication 512 7 OverwriteOlder 0 DxStudio 20,480 0 OverwriteAsNeeded 0 Hardware Events 512 7 OverwriteOlder 0 Internet Explorer 20,480 0 OverwriteAsNeeded 0 Key Management Service 16,384 0 OverwriteAsNeeded 0 Microsoft Office Diagnostics 16,384 0 OverwriteAsNeeded 0 Microsoft Office Sessions 30,016 0 OverwriteAsNeeded 1 Security 15,168 0 OverwriteAsNeeded 2 System 15,360 0 OverwriteAsNeeded 0 Windows PowerShell Description ----------- This function clears all event logs on the specified computers and then dis plays the resulting event log list. Notice that a few entries were added to the System and Security logs after the logs were cleared but before they were displayed. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135198 Get-EventLog Limit-EventLog New-EventLog Remove-EventLog Show-EventLog Write-EventLog Get-WinEvent Clear-History NAME Clear-History SYNOPSIS Deletes entries from the command history. SYNTAX Clear-History [[-Id] <Int32[]>] [[-Count] <int>] [-Newest] [-Confirm] [-Wha tIf] [<CommonParameters>] Clear-History [[-Count] <int>] [-CommandLine <string[]>] [-Newest] [-Confir m] [-WhatIf] [<CommonParameters>] DESCRIPTION The Clear-History cmdlet deletes commands from the command history, that is , the list of commands entered during the current session. Without parameters, Clear-History deletes all commands from the session his tory, but you can use the parameters of Clear-History to delete selected co mmands. PARAMETERS -CommandLine <string[]> Deletes commands with the specified text strings. If you enter more tha n one string, Clear-History deletes commands with any of the strings. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -Count <int> Clears the specified number of history entries, beginning with the old est entry in the history. If you use the Count and Id parameters in the same command, the cmdlet clears the number of entries specified by the Count parameter, beginnin g with the entry specified by the Id parameter. For example, if Count is 10 and Id is 30, Clear-History clears items 21 through 30 inclusive. If you use the Count and CommandLine parameters in the same command, Cl ear-History clears the number of entries specified by the Count paramet er, beginning with the entry specified by the CommandLine parameter. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Id <Int32[]> Deletes commands with the specified history IDs. To find the history ID of a command, use Get-History. Required? false Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -Newest [<SwitchParameter>] Deletes the newest entries in the history. By default, Clear-History de letes the oldest entries in the history. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Clear-History. OUTPUTS None This cmdlet does not generate any output. NOTES The session history is a list of the commands entered during the sessio n. You can view the history, add and delete commands, and run commands from the history. For more information, see about_History. Deleting a command from the history does not change the history IDs of the remaining items in the command history. -------------------------- EXAMPLE 1 -------------------------- C:\PS>clear-history Description ----------- Deletes all commands from the session history. -------------------------- EXAMPLE 2 -------------------------- C:\PS>clear-history -id 23, 25 Description ----------- Deletes the commands with history IDs 23 and 25. -------------------------- EXAMPLE 3 -------------------------- C:\PS>clear-history -command *help*, *command Description ----------- Deletes commands that include "help" or end in "command". -------------------------- EXAMPLE 4 -------------------------- C:\PS>clear-history -count 10 -newest Description ----------- Deletes the 10 newest commands from the history. -------------------------- EXAMPLE 5 -------------------------- C:\PS>clear-history -id 10 -count 3 Description ----------- Deletes the three oldest commands, beginning with the entry with ID 10. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135199 about_History Get-History Add-History Invoke-History Clear-Host Clear-Host Clear-Item NAME Clear-Item SYNOPSIS Deletes the contents of an item, but does not delete the item. SYNTAX Clear-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [ -WhatIf] [-UseTransaction] [<CommonParameters>] Clear-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <strin g[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Confirm] [-WhatIf ] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Clear-Item cmdlet deletes the value of an item, but it does not delete the item. For example, Clear-Item can delete the value of a variable, but i t does not delete the variable. The value that used to represent a cleared item is defined by each Windows PowerShell provider. Clear-Item is similar to Clear-Content, but it works on aliases and variables, instead of files. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to clear items that cannot otherwise be changed, such as read- only aliases. The cmdlet cannot clear constants. Implementati on varies from provider to provider. For more information, see about_Pr oviders. Even using the Force parameter, the cmdlet cannot override sec urity restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Clears only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". W ildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies the path to the items being cleared. Unlike Path, the value o f LiteralPath is used exactly as it is typed. No characters are interpr eted as wildcards. If the path includes escape characters, enclose it i n single quotation marks. Single quotation marks tell Windows PowerShel l not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the path to the items being cleared. Wildcards are permitted. This parameter is required, but the parameter name ("Path") is optiona l. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a path string to Clear-Item. OUTPUTS None This cmdlet does not return any objects. NOTES The Clear-Item cmdlet is supported only by several Windows PowerShell p roviders, including the Alias, Environment, Function, Registry, and Var iable providers. As such, you can use Clear-Item to delete the content of items in the provider namespaces. You cannot use Clear-Item to delete the contents of a file, because the Windows PowerShell FileSystem provider does not support this cmdlet. T o clear files, use Clear-Content. You can also refer to Clear-Item by its built-in alias, "cli". For more information, type "get-help about_Aliases". The Clear-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-Ps Provider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>clear-item Variable:TestVar1 Description ----------- This command deletes the value of the variable, Testvar1. The variable rema ins and is valid, but its value is set to null. The variable name is prefixed with "Variable:" to indicate the Windows Powe rShell Variable provider. To get the same result, you can switch to the Win dows PowerShell Variable provider namespace first and then perform the Clea r-Item command. PS C:> Set-location Variable: PS Variable:\> clear-item Testvar1 -------------------------- EXAMPLE 2 -------------------------- C:\PS>clear-item Alias:log* -include *1* -exclude *3* -whatif What if: Performing operation "Clear Item" on Target "Item: log1". Description ----------- This command asks Windows PowerShell what would happen if you executed the command, "clear-item alias:log* -include *1* -exclude *3". In response, Win dows PowerShell explains that it would delete the value of the log1 alias. This command would not have any effect on the log, log2, or log13 aliases. Because the Alias provider does not permit an alias without a value, when y ou clear an alias, you also delete the alias. -------------------------- EXAMPLE 3 -------------------------- C:\PS>clear-item registry::HKLM\Software\MyCompany\MyKey -confirm Description ----------- This command deletes all registry entries in the MyKey subkey, but only aft er prompting you to confirm your intent. It does not delete the MyKey subke y or affect any other registry keys or entries. You can use the Include and Exclude parameters to identify particular registry keys, but you cannot us e them to identify registry entries. To delete particular registry entries, use Remove-ItemProperty. To delete the value of a registry entry, use Clea r-ItemProperty. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113283 about_Providers Copy-Item Get-Item Invoke-Item Move-Item Set-Item New-Item Remove-Item Rename-Item Clear-ItemProperty NAME Clear-ItemProperty SYNOPSIS Deletes the value of a property but does not delete the property. SYNTAX Clear-ItemProperty [-LiteralPath] <string[]> [-Name] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonPar ameters>] Clear-ItemProperty [-Path] <string[]> [-Name] <string> [-Credential <PSCred ential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <strin g[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters >] DESCRIPTION The Clear-ItemProperty cmdlet deletes the value of a property, but it does not delete the property. You can use this cmdlet to delete the data from a registry value. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt" or "s*". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to delete properties from items that cannot otherwis e be accessed by the user. Implementation varies from provider to provi der. For more information, see about_Providers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Clears only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". W ildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies the path to the property being cleared. Unlike Path, the valu e of LiteralPath is used exactly as it is typed. No characters are inte rpreted as wildcards. If the path includes escape characters, enclose i t in single quotation marks. Single quotation marks tell Windows PowerS hell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies the name of the property to be cleared, such as the name of a registry value. Wildcards are not permitted. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the cleared item's property. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the property being cleared. Wildcards are permitt ed. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a path string to Clear-ItemProperty. OUTPUTS None or System.Management.Automation.PSCustomObject When you use the PassThru parameter, Clear-ItemProperty generates a PSC ustomObject object that represents the cleared item property. Otherwise , this cmdlet does not generate any output. NOTES You can use Clear-ItemProperty to delete the data in registry values wi thout deleting the value. If the data type of the value is Binary or DW ORD, clearing the data sets the value to zero. Otherwise, the value is empty. You can also refer to Clear-ItemProperty by its built-in alias, "clp". For more information, see about_Aliases. The Clear-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>clear-itemproperty -path HKLM:\Software\MyCompany\MyApp -name Options Description ----------- This command deletes the data in the Options registry value in the MyApp su bkey of HKEY_LOCAL_MACHINE\Software\MyCompany. Because the command is being issued from a file system drive (C:), it uses the fully qualified path to the HKLM: drive and the Software\MyCompany\MyAp p subkey. It uses the Name parameter to specify the Options value. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113284 about_Providers Copy-ItemProperty New-ItemProperty Move-ItemProperty Rename-ItemProperty Get-ItemProperty New-ItemProperty Clear-Variable NAME Clear-Variable SYNOPSIS Deletes the value of a variable. SYNTAX Clear-Variable [-Name] <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonPara meters>] DESCRIPTION The Clear-Variable cmdlet deletes the data stored in a variable, but it doe s not delete the variable. As a result, the value of the variable is NULL ( empty). If the variable has a specified data or object type, Clear-Variable preserves the type of the object stored in the variable. PARAMETERS -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Na me parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to clear a variable even if it is read-only. Even usi ng the Force parameter, the cmdlet cannot clear constants. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Clears only the specified items. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wild cards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the name of the variable to be cleared. Wildcards are permitt ed. This parameter is required, but the parameter name ("Name") is opti onal. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the cleared variable. By default, this c mdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Scope <string> Specifies the scope in which this alias is valid. Valid values are "Glo bal", "Local", or "Script", or a number relative to the current scope ( 0 through the number of scopes, where 0 is the current scope and 1 is i ts parent). "Local" is the default. For more information, see about_Sco pes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Clear-Variable. OUTPUTS None or System.Management.Automation.PSVariable When you use the PassThru parameter, Clear-Variable generates a System. Management.Automation.PSVariable object representing the cleared variab le. Otherwise, this cmdlet does not generate any output. NOTES To delete a variable, along with its value, use Remove-Variable or Remo ve-Item. Clear-Variable will not delete the values of variables that are set as constants or owned by the system, even if you use the -Force parameter. If the variable that you are clearing does not exist, the cmdlet has no effect. It does not create a variable with a null value. You can also refer to Clear-Variable by its built-in alias, "clv". For more information, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>clear-variable my* -global Description ----------- This command deletes the value of the global variables that begin with "my" . -------------------------- EXAMPLE 2 -------------------------- C:\PS>$a=3 C:\PS>&{ clear-variable a } C:\PS>$a 3 Description ----------- These commands demonstrate that clearing a variable in a child scope does n ot clear the value in the parent scope. The first command sets the value of the variable $a to "3". The second command uses the invoke operator (&) to run a Clear-Variable command in a new scope. The variable is cleared in th e child scope (although it did not exist), but it is not cleared in the loc al scope. The third command, which gets the value of $a, shows that the val ue "3" is unaffected. -------------------------- EXAMPLE 3 -------------------------- C:\PS>clear-variable -name processes Description ----------- This command deletes the value of the $processes variable. The $processes v ariable still exists, but the value is null. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113285 Get-Variable Set-Variable New-Variable Remove-Variable Compare-Object NAME Compare-Object SYNOPSIS Compares two sets of objects. SYNTAX Compare-Object [-ReferenceObject] <PSObject[]> [-DifferenceObject] <PSObjec t[]> [-CaseSensitive] [-Culture <string>] [-ExcludeDifferent] [-IncludeEqua l] [-PassThru] [-Property <Object[]>] [-SyncWindow <int>] [<CommonParameter s>] DESCRIPTION The Compare-Object cmdlet compares two sets of objects. One set of objects is the Reference set, and the other set is the Difference set. The result of the comparison indicates whether a property value appeared on ly in the object from the Reference set (indicated by the <= symbol), only in the object from the Difference set (indicated by the => symbol) or, if t he IncludeEqual parameter is specified, in both objects (indicated by the = = symbol). PARAMETERS -CaseSensitive [<SwitchParameter>] Indicates that comparisons should be case-sensitive. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Culture <string> Specifies the culture to use for comparisons. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DifferenceObject <PSObject[]> Specifies the objects that are compared to the reference objects. Required? true Position? 2 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -ExcludeDifferent [<SwitchParameter>] Displays only the characteristics of compared objects that are equal. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -IncludeEqual [<SwitchParameter>] Displays characteristics of compared objects that are equal. By default , only characteristics that differ between the reference and difference objects are displayed. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Passes the objects that differed to the pipeline. By default, this cmdl et does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Property <Object[]> Specifies the properties of the reference and difference objects to com pare. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ReferenceObject <PSObject[]> Objects used as a reference for comparison. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -SyncWindow <int> Defines a search region in which an attempt is made to re-synchronize t he order if there is no match. The default value is [Int32]::MaxValue. Required? false Position? named Default value [Int32]::MaxValue Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe a DifferenceObject object to Compare-Object. OUTPUTS None, or the objects that are different When you use the PassThru parameter, Compare-Object returns the objects that differed. Otherwise, this cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>compare-object -referenceobject $(get-content C:\test\testfile1.txt) -differenceobject $(get-content C:\test\testfile2.txt) Description ----------- This command compares the contents of two text files. It displays only the lines that appear in one file or in the other file, not lines that appear i n both files. -------------------------- EXAMPLE 2 -------------------------- C:\PS>compare-object -referenceobject $(get-content C:\Test\testfile1.txt) -differenceobject $(get-content C:\Test\testfile2.txt) -includeequal Description ----------- This command compares each line of content in two text files. It displays a ll lines of content from both files, indicating whether each line appears i n only Textfile1.txt or Textfile2.txt or whether each line appears in both files. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$processes_before = get-process C:\PS> notepad C:\PS> $processes_after = get-process C:\PS> compare-object -referenceobject $processes_before -differenceobject $processes_after Description ----------- These commands compare two sets of process objects. The first command uses the Get-Process cmdlet to get the processes on the c omputer. It stores them in the $processes_before variable. The second command starts Notepad. The third command uses the Get-Process cmdlet again and stores the resultin g processes in the $processes_after variable. The fourth command uses the Compare-Object cmdlet to compare the two sets o f process objects. It displaysthe differences between them, which include t he new instance of Notepad. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113286 Group-Object Measure-Object Sort-Object ForEach-Object New-Object Select-Object Tee-Object Where-Object Complete-Transaction NAME Complete-Transaction SYNOPSIS Commits the active transaction. SYNTAX Complete-Transaction [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Complete-Transaction cmdlet commits an active transaction. When you com mit a transaction, the commands in the transaction are finalized and the da ta affected by the commands is changed. If the transaction includes multiple subscribers, to commit the transaction , you must enter one Complete-Transaction command for every Start-Transacti on command. The Complete-Transaction cmdlet is one of a set of cmdlets that support the transactions feature in Windows PowerShell. For more information, see abou t_Transactions. PARAMETERS -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Complete-Transaction. OUTPUTS None This cmdlet does not return any objects. NOTES You cannot roll back a transaction that has been committed, or commit a transaction that has been rolled back. You cannot roll back any transaction other than the active transaction. To roll back a different transaction, you must first commit or roll ba ck the active transaction. By default, if any part of a transaction cannot be committed, such as w hen a command in the transaction results in an error, the entire transa ction is rolled back. -------------------------- EXAMPLE 1 -------------------------- C:\PS>cd hkcu:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item MyCompany -UseTransaction PS HKCU:\software> dir m* Hive: HKEY_CURRENT_USER\software SKC VC Name Property --- -- ---- -------- 82 1 Microsoft {(default)} PS HKCU:\software> complete-transaction PS HKCU:\software> dir m* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 82 1 Microsoft {(default)} 0 0 MyCompany {} Description ----------- This example shows the effect of using the Complete-Transaction cmdlet to c ommit a transaction. The Start-Transaction command starts the transaction. The New-Item command uses the UseTransaction parameter to include the command in the transaction . The first "dir" (Get-ChildItem) command shows that the new item has not yet been added to the registry. The Complete-Transaction command commits the transaction, which makes the r egistry change effective. As a result, the second "dir" command shows that the registry is changed. -------------------------- EXAMPLE 2 -------------------------- C:\PS>cd hkcu:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item MyCompany -UseTransaction Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 0 0 MyCompany {} PS HKCU:\software> start-transaction PS HKCU:\Software> Get-Transaction RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 2 Active PS HKCU:\software> new-itemproperty -path MyCompany -name MyKey -value -Use Transaction MyKey ----- 123 PS HKCU:\software> complete-transaction PS HKCU:\software> get-transaction RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active PS HKCU:\software> dir m* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 82 1 Microsoft {(default)} PS HKCU:\software> complete-transaction PS HKCU:\software> dir m* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 82 1 Microsoft {(default)} 0 1 MyCompany {MyKey} Description ----------- This example shows how to use Complete-Transaction to commit a transaction that has more than one subscriber. To commit a multi-subscriber transaction, you must enter one Complete-Trans action command for every Start-Transaction command. The data is changed onl y when the final Complete-Transaction command is submitted. For demonstration purposes, this example shows a series of commands entered at the command line. In practice, transactions are likely to be run in scr ipts, with the secondary transaction being run by a function or helper scri pt that is called by the main script. In this example, a Start-Transaction command starts the transaction. A New- Item command with the UseTransaction parameter adds the MyCompany key to th e Software key. Although the New-Item command returns a key object, the dat a in the registry is not yet changed. A second Start-Transaction command adds a second subscriber to the existing transaction. The Get-Transaction command confirms that the subscriber coun t is 2. A New-ItemProperty command with the UseTransaction parameter adds a registry entry to the new MyCompany key. Again, the command returns a valu e, but the registry is not changed. The first Complete-Transaction command reduces the subscriber count by 1. T his is confirmed by a Get-Transaction command. However, no data is changed, as evidenced by a "dir m*" (Get-ChildItem) command. The second Complete-Transaction command commits the entire transaction and changes the data in the registry. This is confirmed by a second "dir m*" co mmand, which shows the changes. -------------------------- EXAMPLE 3 -------------------------- C:\PS>cd hkcu:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item MyCompany -UseTransaction PS HKCU:\software> dir m* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 82 1 Microsoft {(default)} PS HKCU:\software> dir m* -UseTransaction Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 82 1 Microsoft {(default)} 0 0 MyCompany {} PS HKCU:\software> complete-transaction Description ----------- This example shows the value of using Get-* commands, and other commands th at do not change data, in a transaction. When a Get-* command is used in a transaction, it gets the objects that are part of the transaction. This all ows you to preview the changes in the transaction before the changes are co mmitted. In this example, a transaction is started. A New-Item command with the UseT ransaction parameter adds a new key to the registry as part of the transact ion. Because the new registry key is not added to the registry until the Complet e-Transaction command is run, a simple "dir" (Get-ChildItem) command shows the registry without the new key. However, when you add the UseTransaction parameter to the "dir" command, th e command becomes part of the transaction, and it gets the items in the tra nsaction even if they are not yet added to the data. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135200 about_Transactions Start-Transaction Get-Transaction Undo-Transaction Use-Transaction Connect-WSMan NAME Connect-WSMan SYNOPSIS Connects to the WinRM service on a remote computer. SYNTAX Connect-WSMan [-ApplicationName <string>] [-ComputerName <string>] [-Port int>] [-UseSSL] [-Authentication <Authentication>] [-ComputerName <string>] [-Credential <PSCredential>] [-Port <int>] [-SessionOption <hashtable>] [ CommonParameters>] Connect-WSMan [-ConnectionURI <Uri>] [-Authentication <Authentication>] [-C omputerName <string>] [-Credential <PSCredential>] [-Port <int>] [-SessionO ption <hashtable>] [<CommonParameters>] DESCRIPTION The Connect-WSMan cmdlet connects to the WinRM service on a remote computer , and it establishes a persistent connection to the remote computer. You ca n use this cmdlet within the context of the WS-Management provider to conne ct to the WinRM service on a remote computer. However, you can also use thi s cmdlet to connect to the WinRM service on a remote computer before you ch ange to the WS-Management provider. The remote computer will appear in the root directory of the WS-Management provider. For more information about how to disconnect from the WinRM service on a re mote computer, see Disconnect-WSMan. PARAMETERS -ApplicationName <string> Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for t he remote endpoint is in the following format: <transport>://<server>:<port>/ For example: http://server01:8080/WSMAN Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is desi gned to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hos ts Web Services for Management (WS-Management) for efficiency. Required? false Position? named Default value wsman Accept pipeline input? false Accept wildcard characters? false -Authentication <Authentication> Specifies the authentication mechanism to be used at the server. Possib le values are: - Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - Default : Use the authentication method implemented by the WS-Managem ent protocol. This is the default. - Digest: Digest is a challenge-response scheme that uses a server-spec ified data string for the challenge. - Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates. - Negotiate: Negotiate is a challenge-response scheme that negotiates w ith the server or proxy to determine the scheme to use for authenticati on. For example, this parameter value allows negotiation to determine w hether the Kerberos protocol or NTLM is used. - CredSSP: Use Credential Security Service Provider (CredSSP) authentic ation, which allows the user to delegate credentials. This option is de signed for commands that run on one remote computer but collect data fr om or run additional commands on other remote computers. Caution: CredSSP delegates the user's credentials from the local comput er to a remote computer. This practice increases the security risk of t he remote operation. If the remote computer is compromised, when creden tials are passed to it, the credentials can be used to control the netw ork session. Required? false Position? named Default value Default Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name must be used. You can pipe a v alue for this parameter to the cmdlet. Required? false Position? named Default value localhost Accept pipeline input? false Accept wildcard characters? false -ConnectionURI <Uri> Specifies the connection endpoint. The format of this string is: <Transport>://<Server>:<Port>/ The following string is a properly formatted value for this parameter: http://Server01:8080/WSMAN. The URI must be fully qualified . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or "User@Domain.com". Or, enter a PSCredential object, s uch as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -OptionSet <hashtable> Passes a set of switches to the service to modify or refine the nature of the request. These are similar to switches used in command-line she lls in that they are service specific. Any number of options can be spe cified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: -OptionSet @{a=1;b=2;c=3} Required? Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Port <int> Specifies the port to use when the client connects to the WinRM service . When the transport is HTTP, the default port is 80. When the transpor t is HTTPS, the default port is 443. When you use HTTPS as the transpor t, the value of the ComputerName parameter must match the server's cert ificate common name (CN). However, if the SkipCNCheck parameter is spec ified as part of the SessionOption parameter, then the certificate comm on name of the server does not have to match the host name of the serve r. The SkipCNCheck parameter should be used only for trusted computers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SessionOption <hashtable> Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOpt ion cmdlet. For more information about the options that are available, see New-WSManSessionOption. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Specifies that the Secure Sockets Layer (SSL) protocol should be used t o establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is tran smitted over the network. The UseSSL parameter lets you specify the add itional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this paramete r, the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES You can run management commands or query management data on a remote co mputer without creating a WS-Management session. You can do this by usi ng the ComputerName parameters of Invoke-WSManAction and Get-WSManInsta nce. When you use the ComputerName parameter, Windows PowerShell create s a temporary connection that is used for the single command. After the command runs, the connection is closed. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Connect-WSMan -computer server01 PS C:\Users\testuser> cd wsman: PS WSMan:\> PS WSMan:\> dir WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container Description ----------- This command creates a connection to the remote server01 computer. The Connect-WSMan cmdlet is generally used within the context of the WS-Man agement provider to connect to a remote computer, in this case the server01 computer. However, you can use the cmdlet to establish connections to remo te computers before you change to the WS-Management provider. Those connect ions will appear in the ComputerName list. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$cred = Get-Credential Administrator Connect-WSMan -computer server01 -credential $cred PS C:\Users\testuser> cd wsman: PS WSMan:\> PS WSMan:\> dir WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container Description ----------- This command creates a connection to the remote system server01 using the A dministrator account credentials. The first command uses the Get-Credential cmdlet to get the Administrator c redentials and then stores them in the $cred variable. The Get-Credential cmdlet prompts the user for a password of username and password. Users are prompted throught a dialog box or at the command line, depending on system registry settings. The second command uses the Credential parameter to pass the credentials st ored in $cred to Connect-WSMan. Connect-WSMan then connects to the remote s ystem server01 using the Administrator credentials. The Connect-WSMan cmdlet is generally used within the context of the WS-Man agement provider to connect to a remote computer, in this case server01. Ho wever, the cmdlet can be used establish connections to remote computers bef ore changing to the WS-Management provider and those connections will show up in the ComputerName list. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Connect-WSMan -computer server01 -port 80 PS C:\Users\testuser> cd wsman: PS WSMan:\> PS WSMan:\> dir WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container Description ----------- This command creates a connection to the remote server01 computer over port 80. The Connect-WSMan cmdlet is generally used within the context of the WS-Man agement provider to connect to a remote computer, in this case the server01 computer. However, you can use the cmdlet to establish connections to remo te computers before you change to the WS-Management provider. Those connect ions will appear in the ComputerName list. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$a = New-WSManSessionOption -operationtimeout 30000 Connect-WSMan -computer server01 -sessionoption $a PS C:\Users\testuser> cd wsman: PS WSMan:\> PS WSMan:\> dir WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container Description ----------- This command creates a connection to the remote server01 computer by using the connection options that are defined in the New-WSManSessionOption comma nd. The first command uses the New-WSManSessionOption cmdlet to store a set of connection setting options in the $a variable. In this case, the session op tions set a connection time out of 30 seconds (30,000 milliseconds). The second command uses the SessionOption parameter to pass the credentials that are stored in the $a variable to Connect-WSMan. Then, Connect-WSMan c onnects to the remote server01 computer by using the specified session opti ons. The Connect-WSMan cmdlet is generally used within the context of the WS-Man agement provider to connect to a remote computer, in this case the server01 computer. However, you can use the cmdlet to establish connections to remo te computers before you change to the WS-Management provider. Those connect ions will appear in the ComputerName list. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141437 Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan Convert-Path NAME Convert-Path SYNOPSIS Converts a path from a Windows PowerShell path to a Windows PowerShell prov ider path. SYNTAX Convert-Path [-LiteralPath] <string[]> [-UseTransaction] [<CommonParameters >] Convert-Path [-Path] <string[]> [-UseTransaction] [<CommonParameters>] DESCRIPTION The Convert-Path cmdlet converts a path from a Windows PowerShell path to a Windows PowerShell provider path. PARAMETERS -LiteralPath <string[]> Specifies the path to be converted. The value of the LiteralPath parame ter is used exactly as it is typed. No characters are interpreted as wi ldcards. If the path includes escape characters, enclose it in single q uotation marks. Single quotation marks tell Windows PowerShell not to i nterpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the Windows PowerShell path to be converted. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a path (but not a literal path) to Convert-Path. OUTPUTS System.String Convert-Path returns a string that contains the converted path. NOTES The cmdlets that contain the Path noun (the Path cmdlets) manipulate pa th names and return the names in a concise format that all Windows Powe rShell providers can interpret. They are designed for use in programs a nd scripts where you want to display all or part of a path name in a pa rticular format. Use them like you would use Dirname, Normpath, Realpat h, Join, or other path manipulators. You can use the path cmdlets with several providers, including the File System, Registry, and Certificate providers. The Convert-Path cmdlet is designed to work with the data exposed by an y provider. To list the providers available in your session, type "Get- PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>convert-path ~ Description ----------- This command expands the current working directory. -------------------------- EXAMPLE 2 -------------------------- C:\PS>convert-path HKLM:\software\microsoft Description ----------- This command converts the Windows PowerShell provider path to a standard re gistry path. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113289 about_Providers Test-Path Split-Path Resolve-Path Join-Path ConvertFrom-CSV NAME ConvertFrom-CSV SYNOPSIS Converts object properties in comma-separated value (CSV) format into CSV v ersions of the original objects. SYNTAX ConvertFrom-CSV [[-Delimiter] <char>] [-InputObject] <PSObject[]> [-Header <string[]>] [<CommonParameters>] ConvertFrom-CSV -UseCulture [-InputObject] <PSObject[]> [-Header <string[]> ] [<CommonParameters>] DESCRIPTION The ConvertFrom-CSV cmdlet creates objects from CSV variable-length strings that are generated by the ConvertTo-CSV cmdlet. You can use the parameters of the ConvertFrom-CSV cmdlet to specify the col umn header row, which determines the property names of the resulting object s, to specify the item delimiter, or to direct ConvertFrom-CSV to use the l ist separator for the current culture as the delimiter. The objects that ConvertFrom-CSV creates are CSV versions of the original o bjects. The property values of the CSV objects are string versions of the p roperty values of the original objects. The CSV versions of the objects do not have any methods. You can also use the Export-CSV and Import-CSV cmdlets to convert objects t o CSV strings in a file (and back). These cmdlets are the same as the Conve rtTo-CSV and ConvertFrom-CSV cmdlets, except that they save the CSV strings in a file. PARAMETERS -Delimiter <char> Specifies the delimiter that separates the property values in the CSV s trings. The default is a comma (,). Enter a character, such as a colon (:). To specify a semicolon (;), enclose it in quotation marks. If you specify a character other than the delimiter used in the CSV str ings, ConvertFrom-CSV cannot create objects from the CSV strings. Inste ad, it returns the strings. Required? false Position? 2 Default value ',' Accept pipeline input? false Accept wildcard characters? false -Header <string[]> Specifies an alternate column header row for the imported string. The c olumn header determines the names of the properties of the object that ConvertFrom-CSV creates. Enter a comma-separated list of the column headers. Enclose each item i n quotation marks (single or double). Do not enclose the header string in quotation marks. If you enter fewer column headers than there are co lumns, the remaining columns will have no headers. If you enter more he aders than there are columns, the extra headers are ignored. When using the Header parameter, omit the column header string from the CSV strings. Otherwise, ConvertFrom-CSV creates an extra object from t he items in the header row. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <PSObject[]> Specifies the CSV strings to be converted to objects. Enter a variable that contains the CSV strings or type a command or expression that gets the CSV strings. You can also pipe the CSV strings to ConvertFrom-CSV. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -UseCulture [<SwitchParameter>] Use the list separator for the current culture as the string delimiter. The default is a comma (,). To find the list separator for a culture, use the following command: (G et-Culture).TextInfo.ListSeparator. If you specify a character other th an the delimiter used in the CSV strings, ConvertFrom-CSV cannot create objects from the CSV strings. Instead, it returns the strings. Required? true Position? named Default value Comma Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe CSV strings to ConvertFrom-CSV. OUTPUTS System.Management.Automation.PSObject ConvertFrom-CSV returns the objects described by the properties in the CSV strings. NOTES Because the imported objects are CSV versions of the object type, they are not recognized and formatted by the Windows PowerShell type formatt ing entries that format the non-CSV versions of the object type. In CSV format, each object is represented by a comma-separated list of the property values of the object. The property values are converted to strings (by using the ToString() method of the object), so they are ge nerally represented by the name of the property value. ConvertTo-Csv do es not export the methods of the object. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$p = get-process | convertto-csv C:\PS> $p | convertfrom-csv Description ----------- These commands convert the processes on the local computer into CSV format and then restore them to object form. The first command uses the Get-Process cmdlet to get the processes on the l ocal computer. A pipeline operator (|) sends them to the ConvertTo-CSV cmdl et, which converts the process object to CSV format. The CSV strings are sa ved in the $p variable. The second command uses a pipeline operator to send the CSV strings in the $p variable to the ConvertFrom-CSV cmdlet. The cmdlet converts the CSV stri ngs into CSV versions of the original process objects. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$date = get-date | convertto-csv -delimiter ";" C:\PS> convertfrom-csv -inputobject $date -delimiter ";" Description ----------- These commands convert a data object to CSV format and then to CSV object f ormat. The first command uses the Get-Date cmdlet to get the current date and time . A pipeline object (|) sends the date to the ConvertTo-CSV cmdlets, which converts the date object to a series of CSV strings. The command uses the D elimiter parameter to specify a semicolon delimiter. The strings are saved in the $date variable. The second command uses the ConvertFrom-CSV cmdlet to convert the CSV strin gs in the $date variable back to object format. The command uses the InputO bject parameter to specify the CSV strings and the Delimiter parameter to s pecify the semicolon delimiter. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$j = start-job -scriptblock { get-process } | convertto-csv C:\PS> $header = "MoreData","StatusMessage","Location","Command","State","F inished","InstanceId","SessionId","Name","ChildJobs","Output","Error","Prog ress","Verbose","Debug","Warning","StateChanged" # Delete header from $j C:\PS> $j = $j[0], $j[2..($j.count - 1)] $j | convertfrom-csv -header $header MoreData : True StatusMessage : Location : localhost Command : get-process State : Running Finished : System.Threading.ManualResetEvent InstanceId : 6fcb6578-7f42-4d93-9f23-9937f6aac1a2 SessionId : 1 Name : Job1 ChildJobs : System.Collections.Generic.List`1[System.Management.Automat ion.Job] Output : System.Management.Automation.PSDataCollection`1[System.Mana gement.Automation.PSObject] Error : System.Management.Automation.PSDataCollection`1[System.Mana gement.Automation.ErrorRecord] Progress : System.Management.Automation.PSDataCollection`1[System.Mana gement.Automation.ProgressRecord] Verbose : System.Management.Automation.PSDataCollection`1[System.Stri ng] Debug : System.Management.Automation.PSDataCollection`1[System.Stri ng] Warning : System.Management.Automation.PSDataCollection`1[System.Stri ng] StateChanged : Description ----------- This example shows how to use the Header parameter of ConvertFrom-Csv to ch ange the names of properties in the resulting imported object. The first command uses the Start-Job cmdlet to start a background job that runs a Get-Process command on the local computer. A pipeline operator (|) s ends the resulting job object to the ConvertTo-CSV cmdlet, which converts t he job object to CSV format. An assignment operator (=) saves the resulting CSV in the $j variable. The second command saves a header in the $header variable. Unlike the defau lt header, this header uses "MoreData" instead of "HasMoreData" and "State" instead of "JobStateInfo". The third command deletes the original header (the second line) from the CS V strings and returns it to the $j variable. The fourth command uses the ConvertFrom-CSV cmdlet to convert the CSV strin gs to a CSV version of the job object. The command uses a pipeline operator to send the content in $j to ConvertFrom-CSV. The resulting object has "Mo reData" and "State" properties, as specified by the header. -------------------------- EXAMPLE 4 -------------------------- C:\PS>(get-culture).textinfo.listseparator C:\PS> ConvertFrom-Csv -inputobject $services -UseCulture Description ----------- The command uses the ConvertFrom-CSV cmdlet to convert CSV strings of servi ce objects that had been converted by the ConvertTo-CSV cmdlet. The command uses the UseCulture parameter to direct ConvertFrom-CSV to use the delimit er (list separator) of the current culture. When using the UseCulture parameter, be sure that the list separator of the current culture matches the delimiter used in the CSV strings. Otherwise, ConvertFrom-CSV cannot generate objects from the CSV strings. In this example, a Get-Culture command was used to verify the list separato r, before the ConvertFrom-CSV command was used. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135201 ConvertTo-CSV Export-CSV Import-CSV ConvertFrom-SecureString NAME ConvertFrom-SecureString SYNOPSIS Converts a secure string into an encrypted standard string. SYNTAX ConvertFrom-SecureString [-Key <Byte[]>] [-SecureString] <SecureString> [<C ommonParameters>] ConvertFrom-SecureString [[-SecureKey] <SecureString>] [-SecureString] <Sec ureString> [<CommonParameters>] DESCRIPTION The ConvertFrom-SecureString cmdlet converts a secure string (System.Securi ty.SecureString) into an encrypted standard string (System.String). Unlike a secure string, an encrypted standard string can be saved in a file for la ter use. The encrypted standard string can be converted back to its secure string format by using the ConvertTo-SecureString cmdlet. If an encryption key is specified by using the Key or SecureKey parameters, the Rijndael enc ryption algorithm is used. The specified key must have a length of 128, 192 , or 256 bits because those are the key lengths supported by the Rijndael e ncryption algorithm. If no key is specified, the Windows Data Protection AP I (DPAPI) is used to encrypt the standard string representation. PARAMETERS -Key <Byte[]> Specifies the encryption key as a byte array. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SecureKey <SecureString> Specifies the encryption key as a secure string. The secure string valu e is converted to a byte array before being used as the key. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -SecureString <SecureString> Specifies the secure string to convert to an encrypted standard string. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Security.SecureString You can pipe a SecureString object to ConvertFrom-SecureString. OUTPUTS System.String ConvertFrom-SecureString returns a standard string object. NOTES To create a secure string from characters that are typed at the command prompt, use the AsSecureString parameter of the Read-Host cmdlet. When you use the Key or SecureKey parameters to specify a key, the key length must be correct. For example, a key of 128 bits can be specified as a byte array of 16 digits. Similarly, 192-bit and 256-bit keys corr espond to byte arrays of 24 and 32 digits, respectively. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$securestring = read-host -assecurestring Description ----------- This command creates a secure string from characters that you type at the c ommand prompt. After entering the command, type the string you want to stor e as a secure string. An asterisk (*) will be displayed to represent each c haracter that you type. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$standardstring = convertfrom-securestring $securestring Description ----------- This command converts the secure string in the $securestring variable to an encrypted standard string. The resulting encrypted standard string is stor ed in the $standardstring variable. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,4 3) C:\PS> $standardstring = convertfrom-securestring $securestring -key $key Description ----------- These commands use the Rijndael algorithm to convert the secure string stor ed in the $securestring variable to an encrypted standard string with a 192 -bit key. The resulting encrypted standard string is stored in the $standar dstring variable. The first command stores a key in the $key variable. The key is an array of 24 digits, all of which are less than 256. Because each digit represents a byte (8 bits), the key has 24 digits for a total of 192 bits (8 x 24). This is a valid key length for the Rijndael alg orithm. Each individual value is less than 256, which is the maximum value that can be stored in an unsigned byte. The second command uses the key in the $key variable to convert the secure string to an encrypted standard string. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113287 ConvertTo-SecureString Read-Host ConvertFrom-StringData NAME ConvertFrom-StringData SYNOPSIS Converts a string containing one or more key/value pairs to a hash table. SYNTAX ConvertFrom-StringData [-StringData] <string> [<CommonParameters>] DESCRIPTION The ConvertFrom-StringData cmdlet converts a string that contains one or mo re key/value pairs into a hash table. Because each key/value pair must be on a separate line, here-strings are often used as the input format. The ConvertFrom-StringData cmdlet is considered to be a safe cmdlet that ca n be used in the DATA section of a script or function. When used in a DATA section, the contents of the string must conform to the rules for a DATA se ction. For more information, see about_Data_Sections. PARAMETERS -StringData <string> Specifies the string to be converted. You can use this parameter or pip e a string to ConvertFrom-StringData. The parameter name is optional. The value of this parameter must be a string that is enclosed in single quotation marks (a single-quoted string) or a string that is enclosed in double quotation marks (a double-quoted string) or a here-string con taining one or more key/value pairs. Each key/value pair must be on a s eparate line, or each pair must be separated by newline characters (`n) . You can include comments in the string, but the comments cannot be on t he same line as a key/value pair. The comments are not included in the hash table. A here-string is a string consisting of one or more lines within which quotation marks are interpreted literally. For more information, see ab out_Quoting_Rules. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string containing a key/value pair to ConvertFrom-String Data. OUTPUTS System.Collections.Hashtable ConvertFrom-StringData returns a hash table that it creates from the ke y/value pairs. NOTES A here-string is a string consisting of one or more lines within which quotation marks are interpreted literally. For more information, see ab out_Quoting_Rules. ConvertFrom-StringData can be useful in scripts that display user messa ges in multiple spoken languages. You can use the dictionary-style hash tables to isolate text strings from code, such as in resource files, a nd to format the text strings for use in translation tools. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$here = @' Msg1 = The string parameter is required. Msg2 = Credentials are required for this command. Msg3 = The specified variable does not exist. '@ C:\PS> convertfrom-stringdata -stringdata $here Name Value ---- ----- Msg3 The specified variable does not exist. Msg2 Credentials are required for this command. Msg1 The string parameter is required. Description ----------- These commands convert a single-quoted here-string of user messages into a hash table. In a single-quoted string, values are not substituted for varia bles and expressions are not evaluated. The first command creates a here-string and saves it in the $here variable. The second command uses the ConvertFrom-StringData cmdlet to convert the he re-string in the $here variable to a hash table. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$p = @" ISE = Windows PowerShell Integrated Scripting Environment "@ C:\PS> $p | get-member TypeName: System.String Name MemberType Definition ---- ---------- ---------- Clone Method System.Object Clone() ... C:\PS> $hash = convertfrom-stringdata -stringdata $p C:\PS> $hash | get-member TypeName: System.Collections.Hashtable Name MemberType Definition ---- ---------- ---------- Add Method System.Void Add(Object key, Object ... Description ----------- These commands demonstrate that ConvertFrom-StringData actually converts a here-string to a hash table. The first command creates a double-quoted here-string that includes one key /value" pair and saves it in the $p variable. The second command uses a pipeline operator (|) to send the $p variable to the Get-Member cmdlet. The result shows that $p is a string (System.String) . The third command uses the ConvertFrom-StringData cmdlet to convert the her e-string in $p to a hash table. The command stores the result in the $hash variable. The final command uses a pipeline operator (|) to send the $hash variable t o the Get-Member cmdlet. The result shows that the content of the $hash var iable is a hash table (System.Collections.Hashtable). -------------------------- EXAMPLE 3 -------------------------- C:\PS>convertfrom-stringdata -stringdata @' Name = Disks.ps1 # Category is optional. Category = Storage Cost = Free '@ Name Value ---- ----- Cost Free Category Storage Name Disks.ps1 Description ----------- This command converts a single-quoted here-string that contains multiple ke y/value pairs into a hash table. In this command, the value of the StringData parameter is a here-string, in stead of a variable that contains a here-string. Either format is valid. The here-string includes a comment about one of the strings. Comments are v alid in strings, provided that the comment is on a different line than a ke y/value pair. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$a = convertfrom-stringdata -stringdata "Top = Red `n Bottom = Blue" C:\PS> "Top = " + $a.Top Top = Red C:\PS> "Bottom = " + $a.Bottom Bottom = Blue Description ----------- This example converts a regular double-quoted string (not a here-string) in to a hash table and saves it in the $a variable. To satisfy the condition that each key/value pair must be on a separate lin e, it uses the Windows PowerShell newline character (`n) to separate the pa irs. The result is a hash table of the input. The remaining commands display the output. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$TextMsgs = DATA { ConvertFrom-StringData @' Text001 = The $Notebook variable contains the name of the user's sy stem notebook. Text002 = The $MyNotebook variable contains the name of the user's private notebook. '@ } C:\PS> $TextMsgs.Text001 The $Notebook variable contains the name of the user's system notebook. C:\PS> $TextMsgs.Text002 The $MyNotebook variable contains the name of the user's private notebook. Description ----------- This example shows a ConvertFrom-StringData command used in the DATA sectio n of a script. The statements below the DATA section display the text to th e user. Because the text includes variable names, it must be enclosed in a single-q uoted string so that the variables are interpreted literally and not expand ed. Variables are not permitted in the DATA section. -------------------------- EXAMPLE 6 -------------------------- C:\PS>$here = @' Msg1 = The string parameter is required. Msg2 = Credentials are required for this command. Msg3 = The specified variable does not exist. '@ C:\PS> $hash = $here | convertfrom-stringdata C:\PS> $hash Name Value ---- ----- Msg3 The specified variable does not exist. Msg2 Credentials are required for this command. Msg1 The string parameter is required. Description ----------- This example shows that you can use a pipeline operator (|) to send a strin g to ConvertFrom-StringData. The first command saves a here-string in the $here variable. The second com mand uses a pipeline operator (|) to send the $here variable to ConvertFrom -StringData. The command saves the result in the $hash variable. The final command displays the contents of the $hash variable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113288 about_Data_Sections about_Quoting_Rules about_Script_Internationalization ConvertTo-CSV NAME ConvertTo-CSV SYNOPSIS Converts Microsoft .NET Framework objects into a series of comma-separated value (CSV) variable-length strings. SYNTAX ConvertTo-CSV [[-Delimiter] <char>] [-InputObject] <psobject> [-NoTypeInfor mation] [<CommonParameters>] ConvertTo-CSV [-UseCulture] [-InputObject] <psobject> [-NoTypeInformation] [<CommonParameters>] DESCRIPTION The ConvertTo-CSV cmdlet returns a series of comma-separated, variable-leng th (CSV) strings that represents the objects that you submit. You can then use the ConvertFrom-CSV cmdlet to re-create objects from the CSV strings. T he resulting objects are CSV versions of the original objects that consist of string representations of the property values and no methods. You can also use the Export-CSV and Import-CSV cmdlets to convert .NET Fram ework objects to CSV strings (and back). Export-CSV is the same as ConvertT o-CSV, except that it saves the CSV strings in a file. You can use the parameters of the ConvertTo-CSV cmdlet to specify a delimit er other than a comma or to direct ConvertTo-CSV to use the default delimit er for the current culture. For more information, see Export-CSV, and see the Notes section. PARAMETERS -Delimiter <char> Specifies a delimiter to separate the property values. The default is a comma (,). Enter a character, such as a colon (:). To specify a semicolon (;), enclose it in quotation marks. Otherwise, i t will be interpreted as the command delimiter. Required? false Position? 2 Default value , (comma) Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to export as CSV strings. Enter a variable that c ontains the objects or type a command or expression that gets the objec ts. You can also pipe objects to ConvertTo-CSV. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -NoTypeInformation [<SwitchParameter>] Omits the type information header from the output. By default, the stri ng in the output contains "#TYPE " followed by the fully-qualified name of the type of the .NET Framework object. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseCulture [<SwitchParameter>] Uses the list separator for the current culture as the data delimiter. The default is a comma (,). This parameter is very useful in scripts that are being distributed to users worldwide. To find the list separator for a culture, use the foll owing command: (Get-Culture).TextInfo.ListSeparator. Required? false Position? named Default value Comma Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any .NET Framework object to ConvertTo-CSV. OUTPUTS System.String The CSV output is returned as a collection of strings. NOTES In CSV format, each object is represented by a comma-separated list of its property value. The property values are converted to strings (by us ing the ToString() method of the object), so they are generally represe nted by the name of the property value. ConvertTo-CSV does not export t he methods of the object. The format of the resulting CSV strings is as follows: -- The first string consists of '#TYPE ' followed by the fully-qualifie d name of the .NET Framework type of the object, such as #TYPE System.D iagnostics.Process. To suppress this string, use the NoTypeInformation parameter. -- The next string represents the column headers. It contains a comma-s eparated list of the names of all the properties of the first object. -- The remaining strings consist of comma-separated lists of the proper ty values of each object. When you submit multiple objects to ConvertTo-CSV, ConvertTo-CSV orders the strings based on the properties of the first object that you submi t. If the remaining objects do not have one of the specified properties , the property value of that object is null, as represented by two cons ecutive commas. If the remaining objects have additional properties, th ose property values are ignored. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process powershell | convertto-csv #TYPE System.Diagnostics.Process "__NounName","Name","Handles","VM","WS","PM","NPM","Path","Company","CPU"," FileVersion","ProductVersion","Description", "Product","BasePriority","ExitCode","HasExited","ExitTime","Handle","Handle Count","Id","MachineName","MainWindowHandle" ,"MainWindowTitle","MainModule","MaxWorkingSet","MinWorkingSet","Modules"," NonpagedSystemMemorySize","NonpagedSystemMem orySize64","PagedMemorySize","PagedMemorySize64","PagedSystemMemorySize","P agedSystemMemorySize64","PeakPagedMemorySize ","PeakPagedMemorySize64","PeakWorkingSet","PeakWorkingSet64","PeakVirtualM emorySize","PeakVirtualMemorySize64","Priori tyBoostEnabled","PriorityClass","PrivateMemorySize","PrivateMemorySize64"," PrivilegedProcessorTime","ProcessName","Proc essorAffinity","Responding","SessionId","StartInfo","StartTime","Synchroniz ingObject","Threads","TotalProcessorTime","U serProcessorTime","VirtualMemorySize","VirtualMemorySize64","EnableRaisingE vents","StandardInput","StandardOutput","Sta ndardError","WorkingSet","WorkingSet64","Site","Container" "Process","powershell","216","597544960","60399616","63197184","21692","C:\ WINDOWS\system32\WindowsPowerShell\v1.0\powe rshell.exe","Microsoft Corporation","3.4788223","6.1.6587.1 (fbl_srv_powers hell(nigels).070711-0102)","6.1.6587.1","Win dows PowerShell","Microsoft© Windows© Operating System","8",,"False",,"860" ,"216","5132",".","5636936","Windows PowerSh ell 2.0 (04/17/2008 00:10:40)","System.Diagnostics.ProcessModule (powershel l.exe)","1413120","204800","System.Diagnosti cs.ProcessModuleCollection","21692","21692","63197184","63197184","320080", "320080","63868928","63868928","60715008","6 0715008","598642688","598642688","True","Normal","63197184","63197184","00: 00:00.2028013","powershell","15","True","1", "System.Diagnostics.ProcessStartInfo","4/21/2008 3:49:19 PM",,"System.Diagn ostics.ProcessThreadCollection","00:00:03.51 00225","00:00:03.3072212","597544960","597544960","False",,,,"60399616","60 399616",, Description ----------- This command converts a single process object to CSV format. The command us es the Get-Process cmdlet to get the PowerShell process on the local comput er. It uses a pipeline operator (|) to send the command to the ConvertTo-CS V cmdlet, which converts it to a series of comma-separated strings. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$date = get-date C:\PS> convertto-csv -inputobject $date -delimiter ";" -notypeinformation Description ----------- This example converts a date object to CSV format. The first command uses the Get-Date cmdlet to get the current date. It save s it in the $date variable. The second command uses the ConvertTo-CSV cmdlet to convert the DateTime ob ject in the $date variable to CSV format. The command uses the InputObject parameter to specify the object to be converted. It uses the Delimiter para meter to specify the delimiter that separates the object properties. It use s the NoTypeInformation parameter to suppress the #TYPE string. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-eventlog -log "windows powershell" | convertto-csv -useculture Description ----------- This command converts the Windows PowerShell event log on the local compute r to a series of CSV strings. The command uses the Get-EventLog cmdlet to get the events in the Windows P owerShell log. A pipeline operator (|) sends the events to the ConvertTo-CS V cmdlet, which converts the events to CSV format. The command uses the Use Culture parameter, which uses the list separator for the current culture as the delimiter. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135203 Import-CSV Export-CSV ConvertFrom-CSV ConvertTo-Html NAME ConvertTo-Html SYNOPSIS Converts Microsoft .NET Framework objects into HTML that can be displayed i n a Web browser. SYNTAX ConvertTo-Html [[-Head] <string[]>] [[-Title] <string>] [[-Body] <string[]> ] [-CssUri <Uri>] [[-Property] <Object[]>] [-As <string>] [-InputObject object>] [-PostContent <string[]>] [-PreContent <string[]>] [<CommonParamet ers>] ConvertTo-Html [-Fragment] [[-Property] <Object[]>] [-As <string>] [-InputO bject <psobject>] [-PostContent <string[]>] [-PreContent <string[]>] [ onParameters>] DESCRIPTION The ConvertTo-Html cmdlet converts .NET Framework objects into HTML that ca n be displayed in a Web browser. You can use this cmdlet to display the out put of a command in a Web page. You can use the parameters of ConvertTo-Html to select object properties, t o specify a table or list format, to specify the HTML page title, to add te xt before and after the object, and to return only the table or list fragme nt, instead of a strict DTD page. When you submit multiple objects to ConvertTo-Html, Windows PowerShell crea tes the table (or list) based on the properties of the first object that yo u submit. If the remaining objects do not have one of the specified propert ies, the property value of that object is an empty cell. If the remaining o bjects have additional properties, those property values are not included i n the file. PARAMETERS -As <string> Determines whether the object is formatted as a table or a list. Valid values are TABLE and LIST. The default value is TABLE. The TABLE value generates an HTML table that resembles the Windows Powe rShell table format. The header row displays the property names. Each t able row represents an object and displays the object's values for each property. The LIST value generates a two-column HTML table for each object that r esembles the Windows PowerShell list format. The first column displays the property name; the second column displays the property value. Required? false Position? named Default value Table Accept pipeline input? false Accept wildcard characters? false -Body <string[]> Specifies the text to add after the opening <BODY> tag. By default, the re is no text in that position. Required? false Position? 4 Default value No text. Accept pipeline input? false Accept wildcard characters? false -CssUri <Uri> Specifies the Uniform Resource Identifier (URI) of the cascading style sheet (CSS) that is applied to the HTML file. The URI is included in a style sheet link in the output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Fragment [<SwitchParameter>] Generates only an HTML table. The HTML, HEAD, TITLE, and BODY tags are omitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Head <string[]> Specifies the content of the <HEAD> tag. The default is "<title>HTML TA BLE</title>". If you use the Head parameter, the Title parameter is ig nored. Required? false Position? 2 Default value <title>HTML TABLE</title> Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be represented in HTML. Enter a variable that contains the objects or type a command or expression that gets the obje cts. If you use this parameter to submit multiple objects, such as all of th e services on a computer, ConvertTo-Html creates a table that displays the properties of a collection or of an array of objects (System.Object []). To create a table of the individual objects, use the pipeline oper ator to pipe the objects to ConvertTo-Html. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -PostContent <string[]> Specifies text to add after the closing </TABLE> tag. By default, there is no text in that position. Required? false Position? named Default value No text Accept pipeline input? false Accept wildcard characters? false -PreContent <string[]> Specifies text to add before the opening <TABLE> tag. By default, there is no text in that position. Required? false Position? named Default value No text Accept pipeline input? false Accept wildcard characters? false -Property <Object[]> Includes the specified properties of the objects in the HTML. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Title <string> Specifies a title for the HTML file, that is, the text that appears bet ween the <TITLE> tags. Required? false Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any .NET object to ConvertTo-Html. OUTPUTS System.String ConvertTo-Html returns series of strings that comprise valid HTML. NOTES To use this cmdlet, pipe one or more objects to the cmdlet or use the I nputObject parameter to specify the object. When the input consists of multiple objects, the output of these two methods is quite different. -- When you pipe multiple objects to a cmdlet, Windows PowerShell send s the objects to the cmdlet one at a time. As a result, ConvertTo-Html creates a table that displays the individual objects. For example, if y ou pipe the processes on a computer to ConvertTo-Html, the resulting ta ble displays all of the processes. -- When you use the InputObject parameter to submit multiple objects, ConvertTo-Html receives these objects as a collection or as an array. A s a result, it creates a table that displays the array and its properti es, not the items in the array. For example, if you use InputObject to submit the processes on a computer to ConvertTo-Html, the resulting tab le displays an object array (System.Object[]) and its properties. To comply with the XHTML Strict DTD,the DOCTYPE tag is modified accordi ngly: (</ /www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">) -------------------------- EXAMPLE 1 -------------------------- C:\PS>convertto-html -inputobject (get-date) Description ----------- This command creates an HTML page that displays the properties of the curre nt date. It uses the InputObject parameter to submit the results of a Get-D ate command to the ConvertTo-Html cmdlet. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-alias | convertto-html > aliases.htm C:\PS> invoke-item aliases.htm Description ----------- This command creates an HTML page that lists the Windows PowerShell aliases in the current console. The command uses the Get-Alias cmdlet to get the aliases. It uses the pipel ine operator (|) to send the aliases to the ConvertTo-Html cmdlet, which cr eates the HTML page. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-eventlog -logname "Windows PowerShell | convertto-html > pslog.ht m Description ----------- This command creates an HTML page called pslog.htm that displays the events in the Windows PowerShell event log on the local computer. It uses the Get-EventLog cmdlet to get the events in the Windows PowerShell log and then uses the pipeline operator (|) to send the events to the Conv ertTo-Html cmdlet. The command also uses the redirection operator (>) to send the HTML code to the pslog.htm file. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-process | convertto-html -property Name, Path, Company -title "Pr ocess Information" > proc.htm; ii proc.htm Description ----------- These commands create and open an HTML page that lists the name, path, and company of the processes on the local computer. The first command uses the Get-Process cmdlet to get objects that represent the processes running on the computer. The command uses the pipeline opera tor (|) to send the process objects to the ConvertTo-Html cmdlet. The command uses the Property parameter to select three properties of the p rocess objects to be included in the table. The command uses the Title para meter to specify a title for the HTML page. The command also uses the redir ection operator (>) to send the resulting HTML to a file named Proc.htm. The second command uses the Invoke-Item cmdlet (alias = ii) to open the Pro c.htm in the default browser. The two commands are separated by a semicolon (;). -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-service | convertto-html -CssUri "test.css" <//www. w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>HTML TABLE</title> <link rel="stylesheet" type="text/css" href="test.css" /> ... Description ----------- This command creates an HTML page of the service objects that the Get-Servi ce cmdlet returns. The command uses the CssUri parameter to specify a casca ding style sheet for the HTML page. The CssUri parameter adds an additional "<link rel="stylesheet" type="text/ css" tag to the resulting HTML. The HREF attribute in the tag contains the name of the style sheet. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-service | convertto-html -as LIST > services.htm Description ----------- This command creates an HTML page of the service objects that the Get-Servi ce cmdlet returns. The command uses the As parameter to specify a list form at. The redirection operator (>) sends the resulting HTML to the Services.h tm file. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-date | cth -fragment <table> <colgroup>...</colgroup> <tr><th>DisplayHint</th> Week</th><th>DayOfYear</th> Kind</th><th>Millisecond</th> h>Ticks</th><th>TimeOfDay</th> /tr> <tr><td>DateTime</td> 12:00:00 AM</td><td>5</td> >126</td><td>10</td> d><td>633455808041237213</td><td>10:40:04.12 37213</td><td>2008</td> </table> Description ----------- This command uses ConvertTo-Html to generate an HTML table of the current d ate. The command uses the Get-Date cmdlet to get the current date. It uses a pipeline operator (|) to send the results to the ConvertTo-Html cmdlet (a liased as "cth"). The ConvertTo-Html command includes the Fragment parameter, which limits th e output to an HTML table. As a result, the other elements of an HTML page, such as the <HEAD> and <BODY> tags, are omitted. -------------------------- EXAMPLE 8 -------------------------- C:\PS>get-eventlog -log "Windows PowerShell" | convertto-html -property id, level, task Description ----------- This command uses the Get-EventLog cmdlet to get events from the "Windows P owerShell" event log. It uses a pipeline operator (|) to send the events to the ConvertTo-Html cm dlet, which converts the events to HTML format. The ConvertTo-Html command uses the Property parameter to select only the I D, Level, and Task properties of the event. -------------------------- EXAMPLE 9 -------------------------- C:\PS>get-service A* | ConvertTo-Html -title "Windows Services: Server01" - body (get-date) -pre "<P>Generated by Corporate IT</P >" -post "For details, contact Corporate IT." > services.htm; ii services.h tm Description ----------- This command creates and opens a Web page that displays the services on the computer that begin with "A". It uses the Title, Body, PreContent, and Pos tContent parameters of ConvertTo-Html to customize the output. The first part of the command uses the Get-Service cmdlet to get the servic es on the computer that begin with "A". The command uses a pipeline operato r (|) to send the results to the ConvertTo-Html cmdlet. The command uses a redirection operator (>) to send the output to the Services.htm file. A semicolon (;) ends the first command and starts a second command, which u ses the Invoke-Item cmdlet (alias = "ii") to open the Services.htm file in the default browser. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113290 ConvertTo-CSV ConvertTo-Xml ConvertTo-SecureString NAME ConvertTo-SecureString SYNOPSIS Converts encrypted standard strings to secure strings. It can also convert plain text to secure strings. It is used with ConvertFrom-SecureString and Read-Host. SYNTAX ConvertTo-SecureString [-Key <Byte[]>] [-String] <string> [<CommonParameter s>] ConvertTo-SecureString [[-AsPlainText]] [[-Force]] [-String] <string> [<Com monParameters>] ConvertTo-SecureString [[-SecureKey] <SecureString>] [-String] <string> [<C ommonParameters>] DESCRIPTION The ConvertTo-SecureString cmdlet converts encrypted standard strings into secure strings. It can also convert plain text to secure strings. It is use d with ConvertFrom-SecureString and Read-Host. The secure string created by the cmdlet can be used with cmdlets or functions that require a parameter of type SecureString. The secure string can be converted back to an encrypt ed, standard string using the ConvertFrom-SecureString cmdlet. This enables it to be stored in a file for later use. If the standard string being converted was encrypted with ConvertFrom-Secur eString using a specified key, that same key must be provided as the value of the Key or SecureKey parameter of the ConvertTo-SecureString cmdlet. PARAMETERS -AsPlainText [<SwitchParameter>] Specifies a plain text string to convert to a secure string. The secure string cmdlets help protect confidential text. The text is encrypted for privacy and is deleted from computer memory after it is used. If yo u use this parameter to provide plain text as input, the system cannot protect that input in this manner. To use this parameter, you must al so specify the Force parameter. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Confirms that you understand the implications of using the AsPlainText parameter and still want to use it. Required? false Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false -Key <Byte[]> Specifies the encryption key to use when converting a secure string int o an encrypted standard string. Valid key lengths are 16, 24, and 32 by tes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SecureKey <SecureString> Specifies the encryption key to use when converting a secure string int o an encrypted standard string. The key must be provided in the format of a secure string. The secure string is converted to a byte array befo re being used as the key. Valid key lengths are 16, 24, and 32 bytes. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -String <string> Specifies the string to convert to a secure string. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a standard encrypted string to ConvertTo-SecureString. OUTPUTS System.Security.SecureString ConvertTo-SecureString returns a SecureString object. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$secure = read-host -assecurestring C:\PS> $secure System.Security.SecureString C:\PS> $encrypted = convertfrom-securestring -securestring $secure C:\PS> $encrypted 01000000d08c9ddf0115d1118c7a00c04fc297eb010000001a114d45b8dd3f4aa11ad7c0abd ae9800000000002000000000003660000a8000000100000005df63cea84bfb7d70bd6842e7 efa79820000000004800000a000000010000000f10cd0f4a99a8d5814d94e0687d7430b1000 00008bf11f1960158405b2779613e9352c6d14000000e6b7bf46a9d485ff211b9b2a2df3bd 6eb67aae41 C:\PS> $secure2 = convertto-securestring -string $encrypted C:\PS> $secure2 System.Security.SecureString Description ----------- This example shows how to create a secure string from user input, convert t he secure string to an encrypted standard string, and then convert the encr ypted standard string back to a secure string. The first command uses the AsSecureString parameter of the Read-Host cmdlet to create a secure string. After you enter the command, any characters tha t you type are converted into a secure string and then saved in the $secure variable. The second command displays the contents of the $secure variable. Because t he $secure variable contains a secure string, Windows PowerShell displays o nly the System.Security.SecureString type. The third command uses the ConvertFrom-SecureString cmdlet to convert the s ecure string in the $secure variable into an encrypted standard string. It saves the result in the $encrypted variable. The fourth command displays th e encrypted string in the value of the $encrypted variable. The fifth command uses the ConvertTo-SecureString cmdlet to convert the enc rypted standard string in the $encrypted variable back into a secure string . It saves the result in the $secure2 variable. The sixth command displays the value of the $secure2 variable. The SecureString type indicates that th e command was successful. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$secure = read-host -assecurestring C:\PS> $encrypted = convertfrom-securestring -secureString $secure -key (1. .16) C:\PS> $encrypted | set-content encrypted.txt C:\PS> $secure2 = get-content encrypted.txt | convertto-securestring -key ( 1..16) Description ----------- This example shows how to create a secure string from an encrypted standard string that is saved in a file. The first command uses the AsSecureString parameter of the Read-Host cmdlet to create a secure string. After you enter the command, any characters tha t you type are converted into a secure string and then saved in the $secure variable. The second command uses the ConvertFrom-SecureString cmdlet to convert the secure string in the $secure variable into an encrypted standard string by using the specified key. The contents are saved in the $encrypted variable. The third command uses a pipeline operator (|) to send the value of the $en crypted variable to the Set-Content cmdlet, which saves the value in the En crypted.txt file. The fourth command uses the Get-Content cmdlet to get the encrypted standar d string in the Encrypted.txt file. The command uses a pipeline operator to send the encrypted string to the ConvertTo-SecureString cmdlet, which conv erts it to a secure string by using the specified key. The results are save d in the $secure2 variable. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$secure_string_pwd = convertto-securestring "P@ssW0rD" -asplaintext -force Description ----------- This command converts the plain text string "P@ssW0rD" into a secure strin g and stores the result in the $secure_string_pwd variable. To use the AsPl ainText parameter, the Force parameter must also be included in the command . RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113291 ConvertFrom-SecureString Read-Host ConvertTo-XML NAME ConvertTo-XML SYNOPSIS Creates an XML-based representation of an object. SYNTAX ConvertTo-XML [-InputObject] <psobject> [-As <string>] [-Depth <int>] [-NoT ypeInformation] [<CommonParameters>] DESCRIPTION The ConvertTo-Xml cmdlet creates an XML-based representation of one or more Microsoft .NET Framework objects. To use this cmdlet, pipe one or more obj ects to the cmdlet, or use the InputObject parameter to specify the object. When you pipe multiple objects to ConvertTo-XML or use the InputObject para meter to submit multiple objects, ConvertTo-XML returns a single XML docume nt that includes representations of all of the objects. This cmdlet is similar to Export-Clixml except that Export-Clixml stores th e resulting XML in a file. ConvertTo-XML returns the XML, so you can contin ue to process it in Windows PowerShell. PARAMETERS -As <string> Determines the output format. Valid values are: -- String: Returns a single string. -- Stream: Returns an array of strings. -- Document: Returns an XmlDocument object. Stream is the default. Required? false Position? named Default value Stream Accept pipeline input? false Accept wildcard characters? false -Depth <int> Specifies how many levels of contained objects are included in the XML representation. The default value is 1. For example, if the object's properties also contain objects, to save a n XML representation of the properties of the contained objects, you mu st specify a depth of 2. The default value can be overridden for the object type in the Types.ps 1xml files. For more information, see about_Types.ps1xml. Required? false Position? named Default value 1 Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the object to be converted. Enter a variable that contains th e objects, or type a command or expression that gets the objects. You c an also pipe objects to ConvertTo-XML. Required? true Position? 1 Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? true -NoTypeInformation [<SwitchParameter>] Omits the Type attribute from the object nodes. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to ConvertTo-XML. OUTPUTS System.String or System.Xml.XmlDocument The value of the As parameter determines the type of object that Conver tTo-XML returns. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-date | convertto-xml Description ----------- This command converts the current date (a DateTime object) to XML. -------------------------- EXAMPLE 2 -------------------------- C:\PS>convertto-xml -as Document -inputObject (get-process) -depth 3 Description ----------- This command converts the process objects that represent all of the process es on the computer into an XML document. The objects are expanded to a dept h of three levels. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135204 Export-Clixml Import-Clixml ConvertTo-Html ConvertTo-Csv Copy-Item NAME Copy-Item SYNOPSIS Copies an item from one location to another within a namespace. SYNTAX Copy-Item [-LiteralPath] <string[]> [[-Destination] <string>] [-Container] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-For ce] [-Include <string[]>] [-PassThru] [-Recurse] [-Confirm] [-WhatIf] [-Use Transaction] [<CommonParameters>] Copy-Item [-Path] <string[]> [[-Destination] <string>] [-Container] [-Crede ntial <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-I nclude <string[]>] [-PassThru] [-Recurse] [-Confirm] [-WhatIf] [-UseTransac tion] [<CommonParameters>] DESCRIPTION The Copy-Item cmdlet copies an item from one location to another in a names pace. Copy-Item does not delete the items being copied. The particular item s that the cmdlet can copy depend on the Windows PowerShell providers avail able. For example, when used with the FileSystem provider, it can copy file s and directories and when used with the Registry provider, it can copy reg istry keys and entries. PARAMETERS -Container [<SwitchParameter>] Preserves container objects during the copy operation. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Destination <string> Specifies the path to the location where the items are to be copied. Required? false Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to copy items that cannot otherwise be changed, such as copying over a read-only file or alias. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Specifies only those items upon which the cmdlet will act, excluding al l others. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the item. The value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcard s. If the path includes escape characters, enclose it in single quotati on marks. Single quotation marks tell Windows PowerShell not to interpr et any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing each copied item. By default, this cmdle t does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the items to copy. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Recurse [<SwitchParameter>] Specifies a recursive copy. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Copy-ItemProperty. OUTPUTS None or an object representing the copied item. When you use the PassThru parameter, Copy-Item returns an object that r epresents the copied item. Otherwise, this cmdlet does not generate any output. NOTES Copy-Item is like the 'cp' or 'copy' commands in other shells. The Copy-Item cmdlet is designed to work with the data exposed by any p rovider. To list the providers available in your session, type "Get-PsP rovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>copy-item C:\Wabash\Logfiles\mar1604.log.txt -destination C:\Presenta tion Description ----------- This command will copy the file mar1604.log.txt to the C:\Presentation dire ctory. The command does not delete the original file. -------------------------- EXAMPLE 2 -------------------------- C:\PS>copy-item C:\Logfiles -destination C:\Drawings -recurse Description ----------- This command copies the entire contents of the Logfiles directory into the Drawings directory. If the source directory contains files in subdirectorie s, those subdirectories will be copied with their file trees intact. The Co ntainer parameter is set to true by default. This preserves the directory s tructure. -------------------------- EXAMPLE 3 -------------------------- C:\PS>copy-item C:\Logfiles -destination C:\Drawings\Logs -recurse Description ----------- This command copies the contents of the C:\Logfiles directory to the C:\Dra wings\Logs directory. It will create the subdirectory \Logs if it does not already exist. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113292 about_Providers Clear-Item Get-Item Invoke-Item Move-Item Set-Item New-Item Remove-Item Rename-Item Copy-ItemProperty NAME Copy-ItemProperty SYNOPSIS Copies a property and value from a specified location to another location. SYNTAX Copy-ItemProperty [-LiteralPath] <string[]> [-Destination] <string> [-Name] <string> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter ng>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseT ransaction] [<CommonParameters>] Copy-ItemProperty [-Path] <string[]> [-Destination] <string> [-Name] <strin g> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [- Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransact ion] [<CommonParameters>] DESCRIPTION The Copy-ItemProperty cmdlet copies a property and value from a specified l ocation to another location. For example, you can use Copy-ItemProperty to copy one or more registry entries from one registry key to another registry key. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Destination <string> Specifies the path to the destination location. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to override restrictions such as renaming existing fi les as long as security is not compromised. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Specifies only those items upon which the cmdlet will act, excluding al l others. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation ma rks. Single quotation marks tell Windows PowerShell not to interpret an y characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies the name of the property to be copied. Required? true Position? 3 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the copied item property. By default, th is cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the property to be copied. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Copy-ItemProperty. OUTPUTS None or System.Management.Automation.PSCustomObject When you use the Passthru parameter, Copy-ItemProperty generates a PsCu stomObject representing the copied item property. Otherwise, this cmdle t does not generate any output. NOTES The Copy-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>copy-itemproperty -path MyApplication -destination HKLM:\Software\MyA pplicationRev2 -name MyProperty Description ----------- This command copies the property named MyProperty from the MyApplication re gistry key to the MyApplicationRev2 registry key. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113293 about_Providers Clear-ItemProperty New-ItemProperty Move-ItemProperty Rename-ItemProperty Get-ItemProperty Set-ItemProperty Debug-Process NAME Debug-Process SYNOPSIS Debugs one or more processes running on the local computer. SYNTAX Debug-Process [-Name] <string[]> [-Confirm] [-WhatIf] [<CommonParameters>] Debug-Process [-Id] <Int32[]> [-Confirm] [-WhatIf] [<CommonParameters>] Debug-Process -InputObject <Process[]> [-Confirm] [-WhatIf] [<CommonParamet ers>] DESCRIPTION The Debug-Process cmdlet attaches a debugger to one or more running process es on a local computer. You can specify the processes by their process name or process ID (PID), or you can pipe process objects to Debug-Process. Debug-Process attaches the debugger that is currently registered for the pr ocess. Before using this cmdlet, verify that a debugger is downloaded and c orrectly configured. PARAMETERS -Id <Int32[]> Specifies the process IDs of the processes to be debugged. The paramete r name ("-Id") is optional. To find the process ID of a process, type "get-process". Required? true Position? 1 Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InputObject <Process[]> Specifies the process objects that represent processes to be debugged. Enter a variable that contains the process objects or a command that ge ts the process objects, such as a Get-Process command. You can also pip e process objects to Debug-Process. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the names of the processes to be debugged. If there is more t han one process with the same name, Debug-Process attaches a debugger t o all processes with that name. The parameter name ("Name") is optiona l. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Int32, System.Diagnostics.Process, System.String You can pipe a process ID (Int32), a process object (System.Diagnostics .Process), or a process name (String) to Debug-Process. OUTPUTS None This cmdlet does not generate any output. NOTES This cmdlet uses the AttachDebugger method of the Windows Management In strumentation (WMI) Win32_Process class. For more information about thi s method, see "AttachDebugger Method" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143640. -------------------------- EXAMPLE 1 -------------------------- C:\PS>debug-process -name powershell Description ----------- This command attaches a debugger to the PowerShell process on the computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>debug-process -name sql* Description ----------- This command attaches a debugger to all processes that have names that begi n with "sql". -------------------------- EXAMPLE 3 -------------------------- C:\PS>debug-process winlogon, explorer, outlook Description ----------- This command attaches a debugger to the Winlogon, Explorer, and Outlook pro cesses. -------------------------- EXAMPLE 4 -------------------------- C:\PS>debug-process -id 1132, 2028 Description ----------- This command attaches a debugger to the processes that have process IDs 113 2 and 2028. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-process powershell | debug-process Description ----------- This command attaches a debugger to the PowerShell processes on the compute r. It uses the Get-Process cmdlet to get the PowerShell processes on the co mputer, and it uses a pipeline operator (|) to send the processes to the De bug-Process cmdlet. To specify a particular PowerShell process, use the ID parameter of Get-Pro cess. -------------------------- EXAMPLE 6 -------------------------- C:\PS>$pid | debug-process Description ----------- This command attaches a debugger to the current PowerShell processes on the computer. It uses the $pid automatic variable, which contains the process ID of the c urrent PowerShell process. Then, it uses a pipeline operator (|) to send th e process ID to the Debug-Process cmdlet. For more information about the $pid automatic variable, see about_Automatic _Variables. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-process -computername Server01, Server02 -name MyApp | debug-proc ess Description ----------- This command attaches a debugger to the MyApp processes on the Server01 and Server02 computers. It uses the Get-Process cmdlet to get the MyApp processes on the Server01 a nd Server02 computers. It uses a pipeline operator to send the processes to the Debug-Process cmdlet, which attaches the debuggers. -------------------------- EXAMPLE 8 -------------------------- C:\PS>$p = get-process powershell C:\PS> debug-process -inputobject $p Description ----------- This command attaches a debugger to the PowerShell processes on the local c omputer. The first command uses the Get-Process cmdlet to get the PowerShell process es on the computer. It saves the resulting process object in the $p variabl e. The second command uses the InputObject parameter of Debug-Process to submi t the process object in the $p variable to Debug-Process. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135206 Get-Process Start-Process Stop-Process Wait-Process Debug-Process Disable-ComputerRestore NAME Disable-ComputerRestore SYNOPSIS Disables the System Restore feature on the specified file system drive. SYNTAX Disable-ComputerRestore [-Drive] <string[]> [-Confirm] [-WhatIf] [<CommonPa rameters>] DESCRIPTION The Disable-ComputerRestore cmdlet turns off the System Restore feature on one or more file system drives. As a result, attempts to restore the comput er do not affect the specified drive. To disable System Restore on any drive, it must be disabled on the system d rive, either first or concurrently. To re-enable System Restore, use the Enable-ComputerRestore cmdlet. To find the state of System Restore for each drive, use Rstrui.exe. PARAMETERS -Drive <string[]> Specifies the file system drives. Enter one or more file system drive l etters, each followed by a colon and a backslash and enclosed in quotat ion marks, such as "C:\" or "D:\". This parameter is required. You cannot use this cmdlet to disable System Restore on a remote networ k drive, even if the drive is mapped to the local computer, and you can not disable System Restore on drives that are not eligible for System R estore, such as external drives. To disable System Restore on any drive, System Restore must be disabled on the system drive, either before or concurrently. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not generate any output. NOTES Disable-ComputerRestore and Enable-ComputerRestore work only on client operating systems, such as Windows Vista and Windows XP. To run a Disable-ComputerRestore command on Windows Vista and later ver sions of Windows, open Windows PowerShell with the "Run as administrato r" option. To find the file system drives that are eligible for system restore, in System in Control Panel, see the System Protection tab. To open this t ab in Windows PowerShell, type "SystemPropertiesProtection". This cmdlet uses the Windows Management Instrumentation (WMI) SystemRes tore class. -------------------------- EXAMPLE 1 -------------------------- C:\PS>disable-computerrestore -drive "C:\" Description ----------- This command disables System Restore on the C: drive. -------------------------- EXAMPLE 2 -------------------------- C:\PS>disable-computerrestore "C:\", "D:\" Description ----------- This command disables System Restore on the C: and D: drives. The command u ses the Drive parameter, but it the omits the optional parameter name. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135207 Enable-ComputerRestore Get-ComputerRestorePoint Restore-Computer Restart-Computer Disable-PSBreakpoint NAME Disable-PSBreakpoint SYNOPSIS Disables the breakpoints in the current console. SYNTAX Disable-PSBreakpoint [-Id] <Int32[]> [-PassThru] [-Confirm] [-WhatIf] [<Com monParameters>] Disable-PSBreakpoint [-Breakpoint] <Breakpoint[]> [-PassThru] [-Confirm] [- WhatIf] [<CommonParameters>] DESCRIPTION The Disable-PSBreakpoint cmdlet disables breakpoints, which assures that th ey are not hit when the script runs. You can use it to disable all breakpoi nts, or you can specify breakpoints by submitting breakpoint objects or bre akpoint IDs. Technically, this cmdlet changes the value of the Enabled property of a bre akpoint object to False. To re-enable a breakpoint, use the Enable-PSBreakp oint cmdlet. Breakpoints are enabled by default when you create them by usi ng the Set-PSBreakpoint cmdlet. A breakpoint is a point in a script where execution stops temporarily so th at you can examine the instructions in the script. Disable-PSBreakpoint is one of several cmdlets designed for debugging Windows PowerShell scripts. F or more information about the Windows PowerShell debugger, see about_Debugg ers. PARAMETERS -Breakpoint <Breakpoint[]> Specifies the breakpoints to disable. Enter a variable that contains br eakpoint objects or a command that gets breakpoint objects, such as a G et-PSBreakpoint command. You can also pipe breakpoint objects to the Di sable-PSBreakpoint cmdlet. Required? true Position? 1 Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? false -Id <Int32[]> Disables the breakpoints with the specified breakpoint IDs. Enter the I Ds or a variable that contains the IDs. You cannot pipe IDs to Disable- PSBreakpoint. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the enabled breakpoints. By default, thi s cmdlet does not generate any output. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.Breakpoint You can pipe a breakpoint object to Disable-PSBreakpoint. OUTPUTS None or System.Management.Automation.Breakpoint When you use the PassThru parameter, Disable-PSBreakpoint returns an ob ject that represents the disabled breakpoint. Otherwise, this cmdlet do es not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$b = set-psbreakpoint -script sample.ps1 -variable name C:\PS> $b | disable-psbreakpoint Description ----------- These commands disable a newly-created breakpoint. The first command uses the Set-PSBreakpoint cmdlet to create a breakpoint o n the Name variable in the Sample.ps1 script. Then, it saves the breakpoint object in the $b variable. The second command uses the Disable-PSBreakpoint cmdlet to disable the new breakpoint. It uses a pipeline operator (|) to send the breakpoint object i n $b to the Disable-PSBreakpoint cmdlet. As a result of this command, the value of the Enabled property of the break point object in $b is False. -------------------------- EXAMPLE 2 -------------------------- C:\PS>disable-psbreakpoint -id 0 Description ----------- This command disables the breakpoint with breakpoint ID 0. -------------------------- EXAMPLE 3 -------------------------- C:\PS>disable-psbreakpoint -breakpoint ($b = set-psbreakpoint -script sampl e.ps1 -line 5) C:\PS> $b Description ----------- This command creates a new breakpoint that is disabled until you enable it. It uses the Disable-PSBreakpoint cmdlet to disable the breakpoint. The valu e of the Breakpoint parameter is a Set-PSBreakpoint command that sets a new breakpoint, generates a breakpoint object, and saves the object in the $b variable. Cmdlet parameters that take objects as their values can accept a variable t hat contains the object or a command that gets or generates the object. In this case, because Set-PSBreakpoint generates a breakpoint object, it can b e used as the value of the Breakpoint parameter. The second command displays the breakpoint object in the value of the $b va riable. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-psbreakpoint | disable-psbreakpoint Description ----------- This command disables all breakpoints in the current console. You can abbre viate this command as: "gbp | dbp". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113294 about_Debuggers Set-PSBreakpoint Get-PSBreakpoint Enable-PSBreakpoint Remove-PSBreakpoint Get-PSCallStack Disable-PSRemoting NAME Disable-PSRemoting SYNOPSIS Prevents the computer from receiving remote Windows PowerShell commands. SYNTAX Disable-PSRemoting [-Force] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Disable-PSRemoting function disables all session configurations on the local computer by adding a "deny all" entry to their security descriptors. This prevents the local computer from receiving remote commands. Disable-PSRemoting does not stop the WinRM service and it does not prevent users of the local computer from establishing sessions that connect to remo te computers or sending commands to other computers. To re-enable the session configurations, use the Enable-PSRemoting or Enabl e-PSSessionConfiguration cmdlets. To run this function on Windows Vista, Windows Server 2008, and later versi ons of Windows, you must open Windows PowerShell with the "Run as administr ator" option. PARAMETERS -Force [<SwitchParameter>] Suppresses all user prompts. By default, you are prompted to confirm ea ch operation. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not return any object. NOTES A session configuration is a group of settings that define the environm ent for a session. The session configurations are located on the remote computer and are used by local and remote sessions that connect to the computer. Every session that connects to the computer must use one of the session configurations that are registered on the computer. This includes pers istent sessions that you create by using New-PSSession or Enter-PSSessi on cmdlets, and the temporary sessions that Windows PowerShell creates when you use the ComputerName parameter of a cmdlet that uses WS-Manage ment remoting technology, such as Invoke-Command. By denying access to all session configurations, you effectively prevent all users from est ablishing sessions that connect to the computer. Disable-PSRemoting is the equivalent of "Disable-PSSessionConfiguration -name *. -------------------------- EXAMPLE 1 -------------------------- C:\PS>disable-psremoting Description ----------- This command disables all session configurations on the computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>disable-psremoting -force Description ----------- This command disables all session configurations on the computer without pr ompting. -------------------------- EXAMPLE 3 -------------------------- C:\PS>disable-psremoting -force C:\PS> new-pssession -computername localhost [localhost] Connecting to remote server failed with the following error message : Access is denied. For more information, see the about_Remote_Trou b leshooting Help topic. + CategoryInfo : OpenError: (System.Manageme....RemoteRunspace :RemoteRunspace) [], PSRemotingTransportException + FullyQualifiedErrorId : PSSessionOpenFailed C:\PS> new-pssession -computername Server01 Id Name ComputerName State Configuration Availability -- ---- ------------ ----- ------------- ------------ 1 Session1 Server01... Opened Microsoft.PowerShell Available C:\PS> enable-pssessionConfiguration -name * -force C:\PS> new-pssession -computername localhost Id Name ComputerName State Configuration Availability -- ---- ------------ ----- ------------- ------------ 1 Session1 localhost Opened Microsoft.PowerShell Available Description ----------- This example shows the effect of using Disable-PSRemoting. The first command uses Disable-PSRemoting to disable all registered session configurations on the local computer. The second command uses the New-PSSession to create a remote session to the local computer (also known as a "loopback"). Because the session configura tions that session requires are disabled, the command fails. The third command uses the New-PSSession cmdlet to create a session from th e local computer to the Server01 remote computer. This command, which uses the session configurations on the remote computer, succeeds. The fourth command uses the Enable-PSSessionConfiguration cmdlet to re-enab le all of the session configurations on the local computer. The command use s a value of * (all) in the Name parameter. The fifth command attempts again to establish a loopback session by using t he New-PSSession cmdlet. This time the command succeeds, because the sessio n configuration that requires are enabled. -------------------------- EXAMPLE 4 -------------------------- C:\PS>disable-psremoting -force C:\PS> get-psSessionConfiguration | format-table -property name, permission -auto Name Permission ---- ---------- microsoft.powershell Everyone AccessDenied, BUILTIN\Administrators Access Allowed microsoft.powershell32 Everyone AccessDenied, BUILTIN\Administrators Access Allowed C:\PS> enable-psremoting -force WinRM already is set up to receive requests on this machine. WinRM already is set up for remote management on this machine. C:\PS>> Get-PSSessionConfiguration | ft name, Permission -auto Name Permission ---- ---------- microsoft.powershell BUILTIN\Administrators AccessAllowed microsoft.powershell32 BUILTIN\Administrators AccessAllowed Description ----------- This example shows the effect on the session configurations of using Disabl e-PSRemoting and Enable-PSRemoting. The first command uses the Disable-PSRemoting function to disable all regis tered session configurations. The force parameter suppresses all user promp ts. The second command uses the Get-PSSessionConfiguration cmdlet to display th e registered session configurations on the computer. The command uses a pip eline operator to send the results to a Format-Table command, which display s only the Name and Permission properties of the configurations in a table. The resulting table shows that everyone is denied permission to the configu rations. The third command uses the Enable-PSRemoting cmdlet to re-enable all of the session configurations on the computer. You can also use an "Enable-PsSess ionConfiguration -name *" command. The command uses the Force parameter to suppress all user prompts and to restart the WinRM service without promptin g. The fourth command uses Get-PSSessionConfiguration and Format-Table to disp lay the names and permissions of the session configurations. The results sh ow that members of the Administrators group now have access to the session configurations. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144298 Enable-PSRemoting Disable-PSSessionConfiguration Get-PSSessionConfiguration Register-PSSessionConfiguration Set-PSSessionConfiguration Unregister-PSSessionConfiguration WS-Management Provider Disable-PSSessionConfiguration NAME Disable-PSSessionConfiguration SYNOPSIS Denies access to the session configurations on the local computer. SYNTAX Disable-PSSessionConfiguration [[-Name] <string[]>] [-Force] [-Confirm] [-W hatIf] [<CommonParameters>] DESCRIPTION The Disable-PSSessionConfiguration cmdlet prevents all users of the compute r from using the session configuration in a session. This is an advanced cm dlet that is designed to be used by system administrators to manage customi zed session configurations for their users. The Disable-PSSessionConfiguration cmdlet adds a "deny all" setting to the security descriptor of one or more registered session configurations. As a result, you can unregister, view, and change the configurations, but you ca nnot use them in a session. Without parameters, Disable-PSSessionConfiguration disables the Microsoft.P owerShell configuration, which is the default configuration that is used fo r sessions. Unless the user specifies a different configuration, both local and remote users are effectively prevented from creating any sessions that connect to the computer. To disable all session configurations on the computer, use Disable-PSRemoti ng. PARAMETERS -Force [<SwitchParameter>] Suppresses all user prompts. By default, you are prompted to confirm ea ch operation. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the names of session configurations to disable. Enter one or more configuration names. Wildcards are permitted. You can also pipe a string that contains a configuration name or a session configuration ob ject to Disable-PSSessionConfiguration. If you omit this parameter, Disable-PSSessionConfiguration disables the Microsoft.PowerShell session configuration. Required? false Position? 1 Default value Microsoft.PowerShell Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfi guration, System.String You can pipe a session configuration object or a string that contains t he name of a session configuration to Disable-PSSessionConfiguration. OUTPUTS None This cmdlet does not return any objects. NOTES To run this cmdlet on Windows Vista, Windows Server 2008, and later ver sions of Windows, you must start Windows PowerShell with the "Run as ad ministrator" option. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Disable-PSSessionConfiguration Description ----------- This command disables the Microsoft.PowerShell session configuration. -------------------------- EXAMPLE 2 -------------------------- C:\PS>disable-pssessionConfiguration -name * Description ----------- This command disables all registered session configurations on the computer . -------------------------- EXAMPLE 3 -------------------------- C:\PS>disable-pssessionConfiguration -name Microsoft* -force Description ----------- This command disables all session configurations that have names that begin with "Microsoft". The command uses the Force parameter to suppress all use r prompts from the command. -------------------------- EXAMPLE 4 -------------------------- C:\PS>Get-PSSessionConfiguration -name MaintenanceShell, AdminShell | Disab le-PSSessionConfiguration Description ----------- This command disables the MaintenanceShell and AdminShell session configura tions. The command uses a pipeline operator (|) to send the results of a Get-PSSes sionConfiguration command to Disable-PSSessionConfiguration. -------------------------- EXAMPLE 5 -------------------------- C:\PS>Get-PSSessionConfiguration | format-table -property Name, Permission -auto Name Permission ---- ---------- MaintenanceShell BUILTIN\Administrators AccessAllowed microsoft.powershell BUILTIN\Administrators AccessAllowed microsoft.powershell32 BUILTIN\Administrators AccessAllowed C:\PS> Disable-PSSessionConfiguration -name MaintenanceShell -force C:\PS> Get-PSSessionConfiguration | format-table -property Name, Permission -auto Name Permission ---- ---------- MaintenanceShell Everyone AccessDenied, BUILTIN\Administrators Access Allowed microsoft.powershell BUILTIN\Administrators AccessAllowed microsoft.powershell32 BUILTIN\Administrators AccessAllowed C:\PS> Set-PSSessionConfiguration -name MaintenanceShell -MaximumReceivedDa taSizePerCommandMB 60 ParamName ParamValue --------- ---------- psmaximumreceived... 60 "Restart WinRM service" WinRM service need to be restarted to make the changes effective. Do you wa nt to run the command "restart-service winrm"? [Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y C:\PS> new-pssession -computername localhost -configurationName Maintenance Shell [localhost] Connecting to remote server failed with the following error mes sage : Access is denied. For more information, see the about_Remote_Troubl eshooting Help topic. + CategoryInfo : OpenError: (System.Manageme....RemoteRunspace :RemoteRunspace) [], PSRemotingTransportException + FullyQualifiedErrorId : PSSessionOpenFailed Description ----------- This example shows the effect of disabling a session configuration. The first command uses the Get-SessionConfiguration and Format-Table cmdlet s to display only the Name and Permission properties of the session configu ration objects. This table format makes it easier to see the values of the objects. The results show that members of the Administrators group are perm itted to use the session configurations. The second command uses the Disable-PSSessionConfiguration cmdlet to disabl e the MaintenanceShell session configuration. The command uses the Force pa rameter to suppress all user prompts. The third command repeats the first command. The results show that you can still get the object that represents the MaintenanceShell session configura tion even though everyone is denied access to it. The "AccessDenied" entry takes precedence over all other entries in the security descriptor. The fourth command uses the Set-PSSessionConfiguration cmdlet to increase t he MaximumDataSizePerCommandMB setting on the MaintenanceShell session conf iguration to 60. The results show that the command was successful even thou gh everyone is denied access to the configuration. The fifth command attempts to use the MaintenanceShell session configuratio n in a session. It uses the New-PSSession cmdlet to create a new session an d the ConfigurationName parameter to specify the MaintenanceShell configura tion. The results show that the New-PSSession command fails because the us er is denied access to the configuration. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144299 about_Session_Configurations Enable-PSSessionConfiguration Get-PSSessionConfiguration Register-PSSessionConfiguration Set-PSSessionConfiguration Unregister-PSSessionConfiguration WS-Management Provider Disable-WSManCredSSP NAME Disable-WSManCredSSP SYNOPSIS Disables Credential Security Service Provider (CredSSP) authentication on a client computer. SYNTAX Disable-WSManCredSSP [-Role] <string> [<CommonParameters>] DESCRIPTION The Disable-WSManCredSPP cmdlet disables CredSSP authentication on a client or on a server computer. When CredSSP authentication is used, the user's c redentials are passed to a remote computer to be authenticated. This type o f authentication is designed for commands that create a remote session from within another remote session. For example, you use this type of authentic ation if you want to run a background job on a remote computer. The cmdlet is used to disable CredSSP on the client by specifying Client in the Role parameter. The cmdlet then performs the following: - Disables CredSSP on the client. The WS-Management setting <localhost| computername>\Client\Auth\CredSSP is set to false. - Removes any WSMan/* setting from the Windows CredSSP policy AllowFres hCredentials on the client. The cmdlet is used to disable CredSSP on the server by specifying Server in the Role parameter. The cmdlet then performs the following: - Disables CredSSP on the server. The WS-Management setting <localhost|c omputername>\Service\Auth\CredSSP is set to false. Caution: CredSSP authentication delegates the user's credentials from the l ocal computer to a remote computer. This practice increases the security ri sk of the remote operation. If the remote computer is compromised, when cre dentials are passed to it, the credentials can be used to control the netwo rk session. To disable CredSSP authentication, use the Disable-WSManCredSSP cmdlet. PARAMETERS -Role <string> Accepts one of two possible values: Client or Server. These values spe cify whether CredSSP should be disabled as a client or as a server. If the cmdlet is used to disable CredSSP on the client by specifying Cl ient in the Role parameter, then the cmdlet performs the following: - Disables CredSSP on the client. The WS-Management setting <localh ost|computername>\Client\Auth\CredSSP is set to false. - Removes any WSMan/* setting from the Windows CredSSP policy Allow FreshCredentials on the client. If the cmdlet is used to disable CredSSP on the server by specifying Se rver in the Role parameter, the cmdlet performs the following: - Disables CredSSP on the server. The WS-Management setting <localho st|computername>\Service\Auth\CredSSP is set to false. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES To enable CredSSP authentication, use the Enable-WSManCredSSP cmdlet. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Disable-WSManCredSSP -Role Client Description ----------- This command disables CredSSP on the client, which prevents delegation to s ervers. -------------------------- EXAMPLE 2 -------------------------- C:\PS>Disable-WSManCredSSP -Role Server Description ----------- This command disables CredSSP on the server, which prevents delegation from clients. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141438 Connect-WSMan Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan Disconnect-WSMan NAME Disconnect-WSMan SYNOPSIS Disconnects the client from the WinRM service on a remote computer. SYNTAX Disconnect-WSMan [-ComputerName <string>] [<CommonParameters>] DESCRIPTION The Disconnect-WSMan cmdlet disconnects the client from the WinRM service o n a remote computer. If you saved the WS-Management session in a variable, the session object remains in the variable, but the state of the WS-Managem ent session is "Closed". You can use this cmdlet within the context of the WS-Management provider to disconnect the client from the WinRM service on a remote computer. However, you can also use this cmdlet to disconnect from the WinRM service on remote computers before you change to the WS-Managemen t provider. For more information about how to connect to the WinRM service on a remote computer, see Connect-WSMan. PARAMETERS -ComputerName <string> Specifies the computer from which you want to disconnect. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Us e the local computer name, use localhost, or use a dot (.) to specify t he local computer. The local computer is the default. When the remote c omputer is in a different domain from the user, you must use a fully qu alified domain name must be used. You can pipe a value for this paramet er to the cmdlet. Note: You cannot disconnect from the local host (the default connection to the local computer). However, if a separate connection is made to t he local computer (for example, by using the computer name), you can re move that connection by using the Disconnect-WSMan cmdlet . Required? false Position? named Default value localhost Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>Disconnect-WSMan -computer server01 C:\PS> cd WSMan: PS WSMan:\> PS WSMan:\> dir WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container Description ----------- This command deletes the connection to the remote server01 computer. This cmdlet is generally used within the context of the WS-Management provi der to disconnect from a remote computer, in this case the server01 compute r. However, you can also use the Disconnect-WSMan cmdlet to remove connecti ons to remote computers before you change to the WSMan provider. Those con nections will not appear in the ComputerName list. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141439 Connect-WSMan Disable-WSManCredSSP Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan Enable-ComputerRestore NAME Enable-ComputerRestore SYNOPSIS Enables the System Restore feature on the specified file system drive. SYNTAX Enable-ComputerRestore [-Drive] <string[]> [-Confirm] [-WhatIf] [<CommonPar ameters>] DESCRIPTION The Enable-ComputerRestore cmdlet turns on the System Restore feature on on e or more file system drives. As a result, you can use tools, such as the R estore-Computer cmdlet, to restore the computer to a previous state. By default, System Restore is enabled on all eligible drives, but you can d isable it, such as by using the Disable-ComputerRestore cmdlet. To enable ( or re-enable) System Restore on any drive, it must be enabled on the system drive, either first or concurrently. To find the state of System Restore for each drive, use Rstrui.exe. PARAMETERS -Drive <string[]> Specifies the file system drives. Enter one or more file system drive l etters, each followed by a colon and a backslash and enclosed in quotat ion marks, such as "C:\" or "D:\". This parameter is required. You cannot use this cmdlet to enable System Restore on a remote network drive, even if the drive is mapped to the local computer, and you cann ot enable System Restore on drives that are not eligible for System Res tore, such as external drives. To enable System Restore on any drive, System Restore must be enabled o n the system drive, either before or concurrently. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS None This cmdlet does not generate any output. NOTES Disable-ComputerRestore and Enable-ComputerRestore work only on client operating systems, such as Windows Vista and Windows XP. To run an Enable-ComputerRestore command on Windows Vista and later ver sions of Windows, open Windows PowerShell with the "Run as administrato r" option. To find the file system drives that are eligible for system restore, in System in Control Panel, see the System Protection tab. To open this t ab in Windows PowerShell, type "SystemPropertiesProtection". This cmdlet uses the Windows Management Instrumentation (WMI) SystemRes tore class. -------------------------- EXAMPLE 1 -------------------------- C:\PS>enable-computerrestore -drive "C:\" Description ----------- This command enables System Restore on the C: drive of the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>enable-computerrestore -drive "C:\", "D:\" Description ----------- This command enables System Restore on the C: and D: drives of the local co mputer. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135209 Disable-ComputerRestore Get-ComputerRestorePoint Restore-Computer Restart-Computer Enable-PSBreakpoint NAME Enable-PSBreakpoint SYNOPSIS Enables the breakpoints in the current console. SYNTAX Enable-PSBreakpoint [-Id] <Int32[]> [-PassThru] [-Confirm] [-WhatIf] [<Comm onParameters>] Enable-PSBreakpoint [-Breakpoint] <Breakpoint[]> [-PassThru] [-Confirm] [-W hatIf] [<CommonParameters>] DESCRIPTION The Enable-PSBreakpoint cmdlet re-enables disabled breakpoints. You can use it to enable all breakpoints, or you can specify breakpoints by submitting breakpoint objects or breakpoint IDs. A breakpoint is a point in a script where execution stops temporarily so th at you can examine the instructions in the script. Newly created breakpoint s are automatically enabled, but you can disable them by using the Disable- PSBreakpoint cmdlet. Technically, this cmdlet changes the value of the Enabled property of a bre akpoint object to True. Enable-PSBreakpoint is one of several cmdlets designed for debugging Window s PowerShell scripts. For more information about the Windows PowerShell deb ugger, see about_Debuggers. PARAMETERS -Breakpoint <Breakpoint[]> Specifies the breakpoints to enable. Enter a variable that contains bre akpoint objects or a command that gets breakpoint objects, such as a Ge t-PSBreakpoint command. You can also pipe breakpoint objects to Enable- PSBreakpoint. Required? true Position? 1 Default value None. Accept pipeline input? true (ByValue) Accept wildcard characters? false -Id <Int32[]> Enables breakpoints that have the specified breakpoint IDs. The default value is all breakpoints. Enter the IDs or a variable that contains th e IDs. (You cannot pipe IDs to Enable-PSBreakpoint.) To find the ID of a breakpoint, use the Get-PSBreakpoint cmdlet. Required? true Position? 1 Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the enabled breakpoint. By default, this cmdlet does not generate any output. Required? false Position? named Default value No output Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.Breakpoint You can pipe a breakpoint object to Enable-PSBreakpoint. OUTPUTS None or System.Management.Automation.Breakpoint When you use the PassThru parameter, Enable-PSBreakpoint returns a brea kpoint object that represent that breakpoint that was enabled. Otherwis e, this cmdlet does not generate any output. NOTES The Enable-PSBreakpoint cmdlet does not generate an error if you try to enable a breakpoint that is already enabled. As such, you can enable a ll breakpoints without error, even when only a few are disabled. Breakpoints are enabled when you create them by using the Set-PSBreakpo int cmdlet. You do not need to enable newly created breakpoints. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-psbreakpoint | enable-psbreakpoint Description ----------- This command enables all breakpoints in the current console. You can abbrev iate the command as "gbp | ebp". -------------------------- EXAMPLE 2 -------------------------- C:\PS>enable-psbreakpoint -id 0, 1, 5 Description ----------- This command enables breakpoints with breakpoint IDs 0, 1, and 5. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$b = set-psbreakpoint -script sample.ps1 -variable Name C:\PS> $b | disable-psbreakpoint -passthru AccessMode : Write Variable : Name Action : Enabled : False HitCount : 0 Id : 0 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 C:\PS> $b | enable-psbreakpoint -passthru AccessMode : Write Variable : Name Action : Enabled : True HitCount : 0 Id : 0 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Description ----------- These commands re-enable a breakpoint that has been disabled. The first command uses the Set-PSBreakpoint cmdlet to create a breakpoint o n the "Name" variable in the Sample.ps1 script. Then, it saves the breakpoi nt object in the $b variable. The second command uses the Disable-PSBreakpoint cmdlet to disable the new breakpoint. It uses a pipeline operator (|) to send the breakpoint object i n $b to the Disable-PSBreakpoint cmdlet, and it uses the PassThru parameter of Disable-PSBreakpoint to display the disabled breakpoint object. This le ts you verify that the value of the Enabled property of the breakpoint obje ct is False. The third command uses the Enable-PSBreakpoint cmdlet to re-enable the brea kpoint. It uses a pipeline operator (|) to send the breakpoint object in $b to the Enable-PSBreakpoint cmdlet, and it uses the PassThru parameter of E nable-PSBreakpoint to display the breakpoint object. This lets you verify t hat the value of the Enabled property of the breakpoint object is True. The results are shown in the following sample output. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$b = get-psbreakpoint -id 3, 5 C:\PS> enable-psbreakpoint -breakpoint $b Description ----------- These commands enable a set of breakpoints by specifying their breakpoint o bjects. The first command uses the Get-PSBreakpoint cmdlet to get the breakpoints a nd saves them in the $b variable. The second command uses the Enable-PSBreakpoint cmdlet and its Breakpoint p arameter to enable the breakpoints. This command is the equivalent of "enable-psbreakpoint -id 3, 5". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113295 about_Debuggers Set-PSBreakpoint Disable-PSBreakpoint Get-PSBreakpoint Remove-PSBreakpoint Get-PSCallStack Enable-PSRemoting NAME Enable-PSRemoting SYNOPSIS Configures the computer to receive remote commands. SYNTAX Enable-PSRemoting [-Force] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Enable-PSRemoting cmdlet configures the computer to receive Windows Pow erShell remote commands that are sent by using the WS-Management technology . You need to run this command only once on each computer that will receive c ommands. You do not need to run it on computers that only send commands. Be cause the configuration activates listeners, it is prudent to run it only w here it is needed. The Enable-PSRemoting cmdlet performs the following operations: -- Runs the Set-WSManQuickConfig cmdlet, which performs the following tasks : ----- Starts the WinRM service. ----- Sets the startup type on the WinRM service to Automatic. ----- Creates a listener to accept requests on any IP address. ----- Enables a firewall exception for WS-Management communications. -- Enables all registered Windows PowerShell session configurations to rece ive instructions from a remote computer. ----- Registers the "Microsoft.PowerShell" session configuration, if it is not already registered. ----- Registers the "Microsoft.PowerShell32" session configuration on 64-bi t computers, if it is not already registered. ----- Removes the "Deny Everyone" setting from the security descriptor for all the registered session configurations. ----- Restarts the WinRM service to make the preceding changes effective. To run this cmdlet on Windows Vista, Windows Server 2008, and later version s of Windows, you must start Windows PowerShell with the "Run as administra tor" option. PARAMETERS -Force [<SwitchParameter>] Suppresses all user prompts. By default, you are prompted to confirm ea ch operation. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.String Enable-PSRemoting returns strings that describe its results. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>enable-psremoting Description ----------- This command configures the computer to receive remote commands. -------------------------- EXAMPLE 2 -------------------------- C:\PS>enable-psremoting -force Description ----------- This command configures the computer to receive remote commands. It uses th e Force parameter to suppress the user prompts. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144300 about_Remote about_Session_Configurations Disable-PSRemoting Get-PSSessionConfiguration Enable-PSSessionConfiguration Disable-PSSessionConfiguration Register-PSSessionConfiguration Set-PSSessionConfiguration WS-Management Provider Enable-PSSessionConfiguration NAME Enable-PSSessionConfiguration SYNOPSIS Enables the session configurations on the local computer. SYNTAX Enable-PSSessionConfiguration [[-Name] <string[]>] [-Force] [-SecurityDescr iptorSDDL <string>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Enable-PSSessionConfiguration cmdlet re-enables registered session conf igurations that have been disabled by using the Disable-PSSessionConfigurat ion cmdlet. This is an advanced cmdlet that is designed to be used by syste m administrators to manage customized session configurations for their user s. Without parameters, Enable-PSSessionConfiguration re-enables the Microsoft. PowerShell configuration, which is the default configuration that is used f or sessions. This cmdlet performs the following operations for each enabled configuratio n: -- Removes the "deny all" setting from the security descriptor of the conf iguration or replaces the security descriptor with one that you specify. -- Turns on the listener that accepts requests on any IP address. -- Restarts the WinRM service. The Enable-PSSessionConfiguration cmdlet calls the Set-WSManQuickConfig cmd let. However, it should not be used to enable remoting on the computer. Ins tead, use the more comprehensive cmdlet, Enable-PSRemoting. PARAMETERS -Force [<SwitchParameter>] Suppresses all user prompts, and restarts the WinRM service without pro mpting. Restarting the service makes the configuration change effective . To prevent a restart and suppress the restart prompt, use the NoService Restart parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the names of session configurations to enable. Enter one or m ore configuration names. Wildcards are permitted. You can also pipe a string that contains a configuration name or a sess ion configuration object to Enable-PSSessionConfiguration. If you omit this parameter, Enable-PSSessionConfiguration enables the M icrosoft.PowerShell session configuration. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true -SecurityDescriptorSDDL <string> Replaces the security descriptor on the session configuration with the specified security descriptor. If you omit this parameter, Enable-PSSessionConfiguration just deletes the "deny all" item from the security descriptor. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfi guration, System.String You can pipe a session configuration object or a string that contains t he name of a session configuration to Enable-PSSessionConfiguration. OUTPUTS None This cmdlet does not return any objects. NOTES To run this cmdlet on Windows Vista, Windows Server 2008, and later ver sions of Windows, you must start Windows PowerShell with the "Run as ad ministrator" option. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Enable-PSSessionConfiguration Description ----------- This command re-enables the Microsoft.PowerShell default session configurat ion on the computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>Enable-PSSessionConfiguration -name MaintenanceShell, AdminShell Description ----------- This command re-enables the MaintenanceShell and AdminShell session configu rations on the computer. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Enable-PSSessionConfiguration -name * C:\PS> Get-PSSessionConfiguration | Enable-PSSessionConfiguration Description ----------- These commands re-enable all session configurations on the computer. The co mmands are equivalent, so you can use either one. Enable-PSSessionConfiguration does not generate an error if you enable a se ssion configuration that is already enabled. -------------------------- EXAMPLE 4 -------------------------- C:\PS>Enable-PSSessionConfiguration -name MaintenanceShell -securityDescrip torSDDL "O:NSG:BAD:P(A;;GXGWGR;;;BA)(A;;GAGR;;;S-1-5-21-123456789-188441444 -3100496)S:P" Description ----------- This command re-enables the MaintenanceShell session configuration and spec ifies a new security descriptor for the configuration. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144301 about_Session_Configurations Disable-PSSessionConfiguration Get-PSSessionConfiguration Register-PSSessionConfiguration Set-PSSessionConfiguration Unregister-PSSessionConfiguration WS-Management Provider Enable-WSManCredSSP NAME Enable-WSManCredSSP SYNOPSIS Enables Credential Security Service Provider (CredSSP) authentication on a client computer. SYNTAX Enable-WSManCredSSP [-Role] <string> [[-DelegateComputer] <string>] [<Commo nParameters>] DESCRIPTION The Enable-WSManCredSPP cmdlet enables CredSSP authentication on a client o r on a server computer. When CredSSP authentication is used, the user's cre dentials are passed to a remote computer to be authenticated. This type of authentication is designed for commands that create a remote session from w ithin another remote session. For example, you use this type of authenticat ion if you want to run a background job on a remote computer. This cmdlet is used to enable CredSSP on the client by specifying Client in the Role parameter. The cmdlet then performs the following: - Enables CredSSP on the client. The WS-Management setting <localhost|c omputername>\Client\Auth\CredSSP is set to true. - Sets the Windows CredSSP policy AllowFreshCredentials to WSMan/Delega te on the client. - Note: These settings allow the client to delegate explicit credential s to a server when server authentication is achieved. This cmdlet is used to enable CredSSP on the server by specifying Server in the Role parameter. The cmdlet then performs the following: - Enables CredSSP on the server. The WS-Management setting <localhost|co mputername>\Service\Auth\CredSSP is set to true. - Note: This policy setting allows the server to act as a delegate for c lients. Caution: CredSSP authentication delegates the user's credentials from the l ocal computer to a remote computer. This practice increases the security ri sk of the remote operation. If the remote computer is compromised, when cre dentials are passed to it, the credentials can be used to control the netwo rk session. To disable CredSSP authentication, use the Disable-WSManCredSSP cmdlet. PARAMETERS -DelegateComputer <string> Allows the client credentials to be delegated to the server or servers that are specified by this parameter. The value of this parameter shoul d be a fully qualified domain name. If the Role parameter specifies Client, the DelegateComputer parameter is mandatory. If the Role parameter specifies Server, the DelegateComputer parameter is not allowed. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Role <string> Accepts one of two possible values: Client or Server. These values spe cify whether CredSSP should be enabled as a client or as a server. If the Role parameter specifies Client, the cmdlet performs the followi ng: - Enables CredSSP on the client. The WS-Management setting <localho st|computername>\Client\Auth\CredSSP is set to true. - Sets the Windows CredSSP policy AllowFreshCredentials to WSMan/De legate on the client. - Note: These settings allow the client to delegate explicit creden tials to a server when server authentication is achieved. If the Role parameter specifies the Server, the cmdlet performs the fol lowing: - Enables CredSSP on the server. The WS-Management setting <localhos t|computername>\Service\Auth\CredSSP is set to true. - Note: This policy setting allows the server to act as a delegate f or clients. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS System.Xml.XmlElement If CredSSP authentication is successfully enabled, this cmdlet generate s an XMLElement object. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>enable-wsmancredssp -role client -delegatecomputer server02.accountin g.fabrikam.com cfg : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth lang : en-US Basic : true Digest : true Kerberos : true Negotiate : true Certificate : true CredSSP : true Description ----------- This command allows the client credentials to be delegated to the server02 computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>enable-wsmancredssp -role client -delegatecomputer *.accounting.fabri kam.com cfg : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth lang : en-US Basic : true Digest : true Kerberos : true Negotiate : true Certificate : true CredSSP : true Description ----------- This command allows the client credentials to be delegated to all the compu ters in the accounting.fabrikam.com domain. -------------------------- EXAMPLE 3 -------------------------- C:\PS>enable-wsmancredssp -role client -delegatecomputer server02.accountin g.fabrikam.com, server03.accounting.fabrikam.com, server04.accounting.fabri kam.com cfg : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth lang : en-US Basic : true Digest : true Kerberos : true Negotiate : true Certificate : true CredSSP : true Description ----------- This command allows the client credentials to be delegated to multiple comp uters. -------------------------- EXAMPLE 4 -------------------------- C:\PS>enable-wsmancredssp -role server Description ----------- This command allows a computer to act as a delegate for another. The Enable -WSManCredSSP cmdlet (shown in the earlier examples) only enables CredSSP a uthentication on the client, and specifies the remote computers that can ac t on it's behalf. In order for the remote computer to act as a delegate for the client, the CredSSP item in the Service node of WSMan must be set to t rue. -------------------------- EXAMPLE 5 -------------------------- C:\PS>connect-wsman server02 set-item wsman:\server02\service\auth\credSSP -value $true Description ----------- This command allows a computer to act as a delegate for another computer. T he Enable-WSManCredSSP commands that are shown in the earlier examples enab le CredSSP authentication only on the client computer, and they specify the remote computers that can act on behalf of the client computer. For the re mote computer to act as a delegate for the client computer, the CredSSP ite m in the Service directory of the WSMan provider must be set to true. In this example, the first command creates a connection to the remote serve r02 computer. The second command sets the credSSP value on the remote server02 computer, which allows the remote computer to act as a delegate. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141442 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan Enter-PSSession NAME Enter-PSSession SYNOPSIS Starts an interactive session with a remote computer. SYNTAX Enter-PSSession [-ComputerName] <string> [-ApplicationName <string>] [-Auth entication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>] [-Configur ationName <string>] [-Credential <PSCredential>] [-Port <int>] [-SessionOpt ion <PSSessionOption>] [-UseSSL] [<CommonParameters>] Enter-PSSession [[-Id] <int>] [<CommonParameters>] Enter-PSSession [-InstanceId <Guid>] [<CommonParameters>] Enter-PSSession [-Name <string>] [<CommonParameters>] Enter-PSSession [[-Session] <PSSession>] [<CommonParameters>] Enter-PSSession [[-ConnectionURI] <Uri>] [-AllowRedirection] [-Authenticati on {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>] [-ConfigurationNam e <string>] [-Credential <PSCredential>] [-SessionOption <PSSessionOption>] [<CommonParameters>] DESCRIPTION The Enter-PSSession cmdlet starts an interactive session with a single remo te computer. During the session, the commands that you type run on the remo te computer, just as though you were typing directly on the remote computer . You can have only one interactive session at a time. Typically, you use the ComputerName parameter to specify the name of the re mote computer. However, you can also use a session that you create by using New-PSSession for the interactive session. To end the interactive session and disconnect from the remote computer, use the Exit-PSSession cmdlet, or type "exit". PARAMETERS -AllowRedirection [<SwitchParameter>] Allows redirection of this connection to an alternate Uniform Resource Identifier (URI). When you use the ConnectionURI parameter, the remote destination can re turn an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use this paramet er to allow it to redirect the connection. Allows redirection of this connection to an alternate URI. When you use the ConnectionURI parameter, the remote destination can re turn an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use the AllowRed irection parameter to allow it to redirect the connection. You can also limit the number of times that the connection is redirecte d by setting the MaximumConnectionRedirectionCount property of the $PSS essionOption preference variable, or the MaximumConnectionRedirectionCo unt property of the value of the SessionOption parameter. The default v alue is 5. For more information, see the description of the SessionOpti on parameter, and see New-PSSessionOption. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -ApplicationName <string> Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the Co nnectionURI parameter in the command. The default value is the value of the $PSSessionApplicationName prefere nce variable on the local computer. If this preference variable is not defined, the default value is WSMAN. This value is appropriate for most uses. For more information, see about_Preference_Variables. The WinRM service uses the application name to select a listener to ser vice the connection request. The value of this parameter should match t he value of the URLPrefix property of a listener on the remote computer . Required? false Position? named Default value WSMAN Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Authentication <AuthenticationMechanism> Specifies the mechanism that is used to authenticate the user's credent ials. Valid values are "Default", "Basic", "Credssp", "Digest", "Kerb eros", "Negotiate", and "NegotiateWithImplicitCredential". The default value is "Default". CredSSP authentication is available only in Windows Vista, Windows Serv er 2008, and later versions of Windows. For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in the MSDN (Microsoft Developer Network) library at http:/ /go.microsoft.com/fwlink/?LinkId=144382. Caution: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the r emote computer is compromised, the credentials that are passed to it ca n be used to control the network session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -CertificateThumbprint <string> Specifies the digital public key certificate (X509) of a user account t hat has permission to perform this action. Enter the certificate thumbp rint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the Get-Item or Get-ChildItem comm and in the Windows PowerShell Cert: drive. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Starts an interactive session with the specified remote computer. Enter only one computer name. The default is the local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more remote computers. You can also pipe a computer name to E nter-PSSession. To use an IP address in the value of the ComputerName parameter, the co mmand must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote compute r must be included in the WinRM TrustedHosts list on the local computer . For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_ Troubleshooting. Note: In Windows Vista and later versions of Windows, to include the l ocal computer in the value of the ComputerName parameter, you must star t Windows PowerShell with the "Run as administrator" option. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -ConfigurationName <string> Specifies the session configuration that is used for the interactive se ssion. Enter a configuration name or the fully qualified resource URI for a se ssion configuration. If you specify only the configuration name, the fo llowing schema URI is prepended: http://schemas.microsoft.com/powershe ll. The session configuration for a session is located on the remote comput er. If the specified session configuration does not exist on the remote computer, the command fails. The default value is the value of the $PSSessionConfigurationName prefe rence variable on the local computer. If this preference variable is no t set, the default is Microsoft.PowerShell. For more information, see a bout_Preference_Variables. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -ConnectionURI <Uri> Specifies a Uniform Resource Identifier (URI) that defines the connecti on endpoint for the interactive session. The URI must be fully qualifie d. The format of this string is as follows: <Transport>://<ComputerName>:<Port>/ The default value is as follows: http://localhost:80/WSMAN Valid values for the Transport segment of the URI are HTTP and HTTPS. I f you do not specify a ConnectionURI, you can use the UseSSL, ComputerN ame, Port, and ApplicationName parameters to specify the URI values. If the destination computer redirects the connection to a different URI , Windows PowerShell prevents the redirection unless you use the AllowR edirection parameter in the command. Required? false Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Domain. com", or enter a PSCredential object, such as one returned by the Get-C redential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Current user Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Id <int> Specifies the ID of an existing session. Enter-PSSession uses the speci fied session for the interactive session. To find the ID of a session, use the Get-PSSession cmdlet. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InstanceId <Guid> Specifies the instance ID of an existing session. Enter-PSSession uses the specified session for the interactive session. The instance ID is a GUID. To find the instance ID of a session, use th e Get-PSSession cmdlet. You can also use the Session, Name, or ID param eters to specify an existing session. Or, you can use the ComputerName parameter to start a temporary session. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies the friendly name of an existing session. Enter-PSSession use s the specified session for the interactive session. If the name that you specify matches more than one session, the command fails. You can also use the Session, InstanceID, or ID parameters to s pecify an existing session. Or, you can use the ComputerName parameter to start a temporary session. To establish a friendly name for a session, use the Name parameter of t he New-PSSession cmdlet. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Port <int> Specifies the network port on the remote computer used for this comman d. The default is port 80 (the HTTP port). Before using an alternate port, you must configure the WinRM listener o n the remote computer to listen at that port. Use the following command s to configure the listener: 1. winrm delete winrm/config/listener?Address=*+Transport=HTTP 2. winrm create winrm/config/listener?Address=*+Transport=HTTP @{Port=" <port-number>"} Do not use the Port parameter unless you must. The port setting in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on al l computers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Session <PSSession> Specifies a Windows PowerShell session (PSSession) to use for the inter active session. This parameter takes a session object. You can also use the Name, InstanceID, or ID parameters to specify a PSSession. Enter a variable that contains a session object or a command that creat es or gets a session object, such as a New-PSSession or Get-PSSession c ommand. You can also pipe a session object to Enter-PSSession. You can submit only one PSSession with this parameter. If you enter a variable that contains more than one PSSession, the command fails. When you use Exit-PSSession or the EXIT keyword, the interactive sessio n ends, but the PSSession that you created remains open and available f or use. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true -SessionOption <PSSessionOption> Sets advanced options for the session. Enter a SessionOption object tha t you create by using the New-PSSessionOption cmdlet. The default values for the options are determined by the value of the $ PSSessionOption preference variable, if it is set. Otherwise, the sessi on uses the system defaults. For a description of the session options, including the default values, see New-PSSessionOption. For information about the $PSSessionOption pr eference variable, see about_Preference_Variables. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all Windows PowerShell content transmitted over the network. UseSSL is an additional protection that sends the data acr oss an HTTPS connection instead of an HTTP connection. If you use this parameter, but SSL is not available on the port used fo r the command, the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String or System.Management.Automation.Runspaces.PSSession You can pipe a computer name (a string) or a session object to Enter-PS Session. OUTPUTS None The cmdlet does not return any output. NOTES -- To connect to a remote computer, you must be a member of the Adminis trators group on the remote computer. -- In Windows Vista and later versions of Windows, to start an interact ive session on the local computer, you must start Windows PowerShell wi th the "Run as administrator" option. -- When you use Enter-PSSession, your user profile on the remote comput er is used for the interactive session. The commands in the remote user profile, including commands to add Windows PowerShell snap-ins and to change the command prompt, run before the remote prompt is displayed. -- Enter-PSSession uses the UI culture setting on the local computer fo r the interactive session. To find the local UI culture, use the $UICul ture automatic variable. -- Enter-PSSession requires the Get-Command, Out-Default, and Exit-PSSe ssion cmdlets. If these cmdlets are not included in the session configu ration on the remote computer, the Enter-PSSession commands fails. -- Unlike Invoke-Command, which parses and interprets the commands befo re sending them to the remote computer, Enter-PSSession sends the comma nds directly to the remote computer without interpretation. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Enter-PSSession LocalHost\PS> Description ----------- This command starts an interactive session on the local computer. The comma nd prompt changes to indicate that you are now running commands in a differ ent session. The commands that you enter run in the new session, and the results are ret urned to the default session as text. -------------------------- EXAMPLE 2 -------------------------- C:\PS>enter-pssession -computer Server01 Server01\PS> get-process powershell > C:\ps-test\process.txt Server01\PS> exit-pssession C:\PS> C:\PS> dir C:\ps-test\process.txt Get-ChildItem : Cannot find path 'C:\ps-test\process.txt' because it does n ot exist. At line:1 char:4 + dir < c:\ps-test\process.txt Description ----------- This command shows how to work in an interactive session with a remote comp uter. The first command uses the Enter-PSSession cmdlet to start an interactive s ession with Server01, a remote computer. When the session starts, the comma nd prompt changes to include the computer name. The second command gets the PowerShell process and redirects the output to the Process.txt file. The command is submitted to the remote computer, and the file is saved on the remote computer. The third command uses the Exit keyword to end the interactive session and close the connection. The fourth command confirms that the Process.txt file is on the remote comp uter. A Get-ChildItem ("dir") command on the local computer cannot find the file. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$s = new-pssession -computername Server01 C:\PS> Enter-PSSession -session $s Server01\PS> Description ----------- These commands use the Session parameter of Enter-PSSession to run the inte ractive session in an existing Windows PowerShell session (PSSession). -------------------------- EXAMPLE 4 -------------------------- C:\PS>Enter-PSSession -computername Server01 -port 90 -credential domain01\ user01 Server01\PS> Description ----------- This command starts an interactive session with the Server01 computer. It u ses the Port parameter to specify the port and the Credential parameter to specify the account of a user with permission to connect to the remote comp uter. -------------------------- EXAMPLE 5 -------------------------- C:\PS>Enter-PSSession -computername Server01 Server01:\PS> Exit-PSSession C:\PS> Description ----------- This example shows how to start and stop an interactive session. The first command uses the Enter-PSSession cmdlet to start an interactive session wit h the Server01 computer. The second command uses the Exit-PSSession cmdlet to end the session. You c an also use the Exit keyword to end the interactive session. Exit-PSSession and Exit have the same effect. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135210 about_PSSessions about_Remote New-PSSession Get-PSSession Exit-PSSession Remove-PSSession Invoke-Command Environment PROVIDER NAME Environment DRIVES Env: SYNOPSIS Provides access to the Windows environment variables. DESCRIPTION The Windows PowerShell Environment provider lets you get, add, change, clea r, and delete Windows environment variables in Windows PowerShell. The Environment provider is a flat namespace that contains only objects tha t represent the environment variables. The variables have no child items. Each environment variable is an instance of the System.Collections.Dictiona ryEntry class. The name of the variable is the dictionary key. The value of the environment variable is the dictionary value. The Environment provider exposes its data store in the Env: drive. To work with environment variables, change your location to the Env: drive ("set-lo cation env:"), or work from another Windows PowerShell drive. To reference an environment variable from another location, use the Env: drive name in t he path. The environment variable provider supports all the cmdlets that contain the Item noun except for Invoke-Item. And, it supports the Get-Content and Set -Content cmdlets. However, it does not support the cmdlets that contain the ItemProperty noun, and it does not support the Filter parameter in any cmd let. Environment variables must conform to the usual naming standards. Additiona lly, the name cannot include the equal sign (=). Changes to the environment variables affect the current session only. To sa ve the changes, add the changes to the Windows PowerShell profile, or use E xport-Console to save the current session. CAPABILITIES TASKS TASK: Getting to the Env: Drive -------------------------- EXAMPLE 1 -------------------------- This command changes the current location to the Env: drive: set-location env: You can use this command from any drive in Windows PowerShell. To retur n to a file system drive, type the drive name. For example, type: set-location c: TASK: Getting Environment Variables -------------------------- EXAMPLE 1 -------------------------- This command lists all the environment variables in the current session : get-childitem -path env: You can use this command from any Windows PowerShell drive. -------------------------- EXAMPLE 2 -------------------------- This command gets the WINDIR environment variable: get-childitem -path env:windir -------------------------- EXAMPLE 3 -------------------------- This command gets a list of all the environment variables in the curren t session and then sorts them by name: get-childitem | sort-object -property name By default, the environment variables appear in the order that Windows PowerShell discovers them. This command is submitted in the Env: drive. When you run this command from another drive, add the Path parameter wi th a value of Env:. TASK: Creating a New Environment Variable -------------------------- EXAMPLE 1 -------------------------- This command creates the USERMODE environment variable with a value of Non-Admin: new-item -path . -name USERMODE -value Non-Admin Because the current location is in the Env: drive, the value of the Pat h parameter is a dot (.). The dot represents the current location. If you are not in the Env: drive, the value of the Path parameter would be Env:. TASK: Displaying the Properties and Methods of Environment Variables -------------------------- EXAMPLE 1 -------------------------- This command uses the Get-ChildItem cmdlet to get all the environment v ariables: get-childitem -path env: | get-member The pipeline operator (|) sends the results to Get-Member, which displa ys the methods and properties of the object. When you pipe a collection of objects to Get-Member, such as the collec tion of environment variables in the Env: drive, Get-Member evaluates e ach object in the collection separately. Get-Member then returns inform ation about each object type that it finds. If all the objects are of t he same type, it returns information about the single object type. In t his case, all the environment variables are DictionaryEntry objects. To get information about the collection of DictionaryEntry objects, use the InputObject parameter of Get-Member. For example, type: get-member -inputobject (get-childitem env:) When you use the InputObject parameter, Get-Member evaluates the collec tion, not the objects in the collection. -------------------------- EXAMPLE 2 -------------------------- This command lists the values of the properties of the WINDIR environme nt variable: get-item env:windir | format-list -property * It uses the Get-Item cmdlet to get an object that represents the WINDIR environment variable. The pipeline operator (|) sends the results to t he Format-List command. It uses the Property parameter with a wildcard character (*) to format and display the values of all the properties of the WINDIR environment variable. TASK: Changing the Properties of an Environment Variable -------------------------- EXAMPLE 1 -------------------------- This command uses the Rename-Item cmdlet to change the name of the USER MODE environment variable that you created to USERROLE: rename-item -path env:USERMODE -newname USERROLE This change affects the Name, Key, and PSPath properties of the Diction aryEntry object. Do not change the name of an environment variable that the system uses. Although these changes affect only the current session, they might cau se the system or a program to operate incorrectly. -------------------------- EXAMPLE 2 -------------------------- This command uses the Set-Item cmdlet to change the value of the USERRO LE environment variable to Administrator: set-item -path env:USERROLE -value Administrator TASK: Copying an Environment Variable -------------------------- EXAMPLE 1 -------------------------- This command copies the value of the USERROLE environment variable to t he USERROLE2 environment variable: copy-item -path env:USERROLE -destination env:USERROLE2 TASK: Deleting an environment variable -------------------------- EXAMPLE 1 -------------------------- This command deletes the USERROLE2 environment variable from the curren t session: remove-item -path env:USERROLE2 You can use this command in any Windows PowerShell drive. If you are in the Env: drive, you can omit the drive name from the path. -------------------------- EXAMPLE 2 -------------------------- This command deletes the USERROLE environment variable. clear-item -path env:USERROLE DYNAMIC PARAMETERS NOTES The Environment provider does not support any dynamic parameters. RELATED LINKS about_Providers Exit-PSSession NAME Exit-PSSession SYNOPSIS Ends an interactive session with a remote computer. SYNTAX Exit-PSSession [<CommonParameters>] DESCRIPTION The Exit-PSSession cmdlet ends interactive sessions that you started by usi ng Enter-PSSession. You can also use the Exit keyword to end an interactive session. The effect is the same as using Exit-PSSession. PARAMETERS <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Exit-PSSession. OUTPUTS None This cmdlet does not return any output. NOTES This cmdlet takes only the common parameters. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Enter-PSSession -computername Server01 Server01\PS> Exit-PSSession C:\PS> Description ----------- These commands start and then stop an interactive session with the Server01 remote computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$s = new-pssession -computername Server01 C:\PS> Enter-PSSession -session $s Server01\PS> Exit-PSSession C:\PS> $s Id Name ComputerName State ConfigurationName -- ---- ------------ ----- ----------------- 1 Session1 Server01 Opened Microsoft.PowerShell Description ----------- These commands start and stop an interactive session with the Server01 comp uter that uses a Windows PowerShell session (PSSession). Because the interactive session was started by using a Windows PowerShell s ession (PSSession), the PSSession is still available when the interactive s ession ends. If you use the ComputerName parameter, Enter-PSSession creates a temporary session that it closes when the interactive session ends. The first command uses the New-PSSession cmdlet to create a PSSession on th e Server01 computer. The command saves the PSSession in the $s variable. The second command uses the Enter-PSSession cmdlet to start an interactive session using the PSSession in $s. The third command uses the Exit-PSSession cmdlet to stop the interactive se ssion. The final command displays the PSSession in the $s variable. The State prop erty shows the PSSession is still open and available for use. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Enter-PSSession -computername Server01 Server01\PS> exit C:\PS> Description ----------- This command uses the Exit keyword to stop an interactive session started b y using the Enter-PSSession cmdlet. The Exit keyword has the same effect as using Exit-PSSession. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135212 about_PSSessions about_Remote Enter-PSSession New-PSSession Get-PSSession Remove-PSSession Invoke-Command Export-Alias NAME Export-Alias SYNOPSIS Exports information about currently defined aliases to a file. SYNTAX Export-Alias [-Path] <string> [[-Name] <string[]>] [-Append] [-As {Csv | Sc ript}] [-Description <string>] [-Force] [-NoClobber] [-PassThru] [-Scope <s tring>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Export-Alias cmdlet exports the aliases in the current session to a fil e. If the output file does not exist, the cmdlet will create it. Export-Alias can export the aliases in a particular scope or all scopes, it can generate the data in CSV format or as a series of Set-Alias commands t hat you can add to a session or to a Windows PowerShell profile. PARAMETERS -Append [<SwitchParameter>] Appends the output to the specified file, rather than overwriting the e xisting contents of that file. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -As <ExportAliasFormat> Determines the output format. CSV is the default. Valid values are: -- CSV: Comma-separated value (CSV) format. -- Script: Creates a Set-Alias command for each exported alias. If you name the output file with a .ps1 file name extension, you can run it as a script to add the aliases to any session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Description <string> Adds a description to the exported file. The description appears as a c omment at the top of the file, following the header information. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Overwrites the output file, even if the read-only attribute is set on t he file. By default, Export-Alias overwrites files without warning, unless the r ead-only or hidden attribute is set or the NoClobber parameter is used in the command. The NoClobber parameter takes precedence over the Force parameter when both are used in a command. The Force parameter cannot force Export-Alias to overwrite files with t he hidden attribute. Required? false Position? named Default value Does not overwrite read-only files. Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the names of the aliases to export. Wildcards are permitted. By default, Export-Alias exports all aliases in the session or scope. Required? false Position? 2 Default value Export all aliases Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -NoClobber [<SwitchParameter>] Prevents Export-Alias from overwriting any files, even if the Force par ameter is used in the command. If the NoClobber parameter is omitted, Export-Alias will overwrite an e xisting file without warning, unless the read-only attribute is set on the file. NoClobber takes precedence over the Force parameter, which pe rmits Export-Alias to overwrite a file with the read-only attribute. NoClobber does not prevent the Append parameter from adding content to an existing file. Required? false Position? named Default value Overwrites read-write files. Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns objects that represent the aliases that were exported. By defau lt, this cmdlet does not generate any output. Required? false Position? named Default value No output Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the path to the output file. Wildcards are permitted, but the resulting path value must resolve to a single file name. This paramete r is required. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -Scope <string> Specifies the scope from which the aliases should be exported. Valid values are "Global", "Local", or "Script", or a number relative t o the current scope (0 through the number of scopes where 0 is the curr ent scope and 1 is its parent). "Local" is the default. For more inform ation, see about_Scopes. Required? false Position? named Default value Local Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None. You cannot pipe objects to this cmdlet. OUTPUTS None or System.Management.Automation.AliasInfo When you use the Passthru parameter, Export-Alias returns a System.Mana gement.Automation.AliasInfo object that represents the alias. Otherwise , this cmdlet does not generate any output. NOTES You can only Export-Aliases to a file. -------------------------- EXAMPLE 1 -------------------------- C:\PS>export-alias -path alias.csv Description ----------- This command exports current alias information to a file named Alias.csv in the current directory. -------------------------- EXAMPLE 2 -------------------------- C:\PS>export-alias -path alias.csv -noclobber Description ----------- This command exports the aliases in the current session to an Alias.csv fil e. Because the NoClobber parameter is specified, the command will fail if an A lias.csv file already exists in the current directory. -------------------------- EXAMPLE 3 -------------------------- C:\PS>export-alias -path alias.csv -append -description "Appended Aliases" -force Description ----------- This command appends the aliases in the current session to the Alias.csv fi le. The command uses the Description parameter to add a description to the comm ents at the top of the file. The command also uses the Force parameter to overwrite any existing Alias.c sv files, even if they have the read-only attribute. -------------------------- EXAMPLE 4 -------------------------- C:\PS>export-alias -path alias.ps1 -as script C:\PS> add-content -path $profile -value (get-content alias.ps1) C:\PS> $s = new-pssession -computername Server01 C:\PS> invoke-command -session $s -filepath .\alias.ps1 Description ----------- This example shows how to use the script file format that Export-Alias gene rates. The first command exports the aliases in the session to the Alias.ps1 file. It uses the As parameter with a value of Script to generate a file that co ntains a Set-Alias command for each alias. The second command adds the aliases in the Alias.ps1 file to the CurrentUse r-CurrentHost profile. (The path to the profile is saved in the $profile va riable.) The command uses the Get-Content cmdlet to get the aliases from th e Alias.ps1 file and the Add-Content cmdlet to add them to the profile. For more information, see about_Profiles. The third and fourth commands add the aliases in the Alias.ps1 file to a r emote session on the Server01 computer. The third command uses the New-PSSe ssion cmdlet to create the session. The fourth command uses the FilePath pa rameter of the Invoke-Command cmdlet to run the Alias.ps1 file in the new s ession. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113296 Import-Alias Get-Alias New-Alias Set-Alias Export-Clixml NAME Export-Clixml SYNOPSIS Creates an XML-based representation of an object or objects and stores it i n a file. SYNTAX Export-Clixml [-Path] <string> -InputObject <psobject> [-Depth <int>] [-Enc oding <string>] [-Force] [-NoClobber] [-Confirm] [-WhatIf] [<CommonParamete rs>] DESCRIPTION The Export-Clixml cmdlet creates an XML-based representation of an object o r objects and stores it in a file. You can then use the Import-CLIXML cmdle t to re-create the saved object based on the contents of that file. This cmdlet is similar to ConvertTo-XML, except that Export-Clixml stores t he resulting XML in a file. ConvertTo-XML returns the XML, so you can conti nue to process it in Windows PowerShell. PARAMETERS -Depth <int> Specifies how many levels of contained objects are included in the XML representation. The default value is 2. The default value can be overridden for the object type in the Types.ps 1xml files. For more information, see about_Types.ps1xml. Required? false Position? named Default value 2 Accept pipeline input? false Accept wildcard characters? false -Encoding <string> Specifies the type of encoding for the target file. Valid values are AS CII, UTF8, UTF7, UTF32, Unicode, BigEndianUnicode, Default, and OEM. UT F8 is the default. Required? false Position? named Default value UTF8 Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Causes the cmdlet to clear the read-only attribute of the output file i f necessary. The cmdlet will attempt to reset the read-only attribute when the command completes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the object to be converted. Enter a variable that contains th e objects, or type a command or expression that gets the objects. You c an also pipe objects to Export-Clixml. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -NoClobber [<SwitchParameter>] Ensures that the cmdlet does not overwrite the contents of an existing file. By default, if a file exists in the specified path, Export-Clixml overwrites the file without warning. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the path to the file where the XML representation of the obje ct will be stored. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Export-Clixml. OUTPUTS System.IO.FileInfo Export-Clixml creates a file that contains the XML. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>"This is a test" | export-clixml sample.xml Description ----------- This command creates an XML file that stores a representation of the string , "This is a test". -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-acl C:\test.txt | export-clixml -Path fileacl.xml C:\PS> $fileacl = import-clixml fileacl.xml Description ----------- This example shows how to export an object to an XML file and then create a n object by importing the XML from the file. The first command uses the Get-ACL cmdlet to get the security descriptor of the Test.txt file. It uses a pipeline operator to pass the security descri ptor to Export-Clixml, which stores an XML-based representation of the obje ct in a file named FileACL.xml. The second command uses the Import-Clixml cmdlet to create an object from t he XML in the FileACL.xml file. Then, it saves the object in the $FileAcl v ariable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113297 Import-Clixml ConvertTo-XML Export-Csv ConvertTo-Html Export-Console NAME Export-Console SYNOPSIS Exports the names of snap-ins in the current session to a console file. SYNTAX Export-Console [[-Path] <string>] [-Force] [-NoClobber] [-Confirm] [-WhatIf ] [<CommonParameters>] DESCRIPTION The Export-Console cmdlet exports the names of the Windows PowerShell snap- ins in the current session to a Windows PowerShell console file (.psc1). Yo u can use this cmdlet to save the snap-ins for use in future sessions. To add the snap-ins in the .psc1 console file to a session, start Windows P owerShell (Powershell.exe) at the command line by using Cmd.exe or another Windows PowerShell session, and then use the PSConsoleFile parameter of Pow ershell.exe to specify the console file. For more information about Windows PowerShell snap-ins, see about_PSSnapins . PARAMETERS -Force [<SwitchParameter>] Overwrites the data in a console file without warning, even if the file has the read-only attribute. The read-only attribute is changed and is not reset when the command completes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -NoClobber [<SwitchParameter>] Will not overwrite (replace the contents of) an existing console file. By default, if a file exists in the specified path, Export-Console over writes the file without warning. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies a path and file name for the console file (*.psc1). Enter a p ath (optional) and name. Wildcards are not permitted. If you type only a file name, Export-Console creates a file with that n ame and the ".psc1" file name extension in the current directory. This parameter is required unless you have opened Windows PowerShell wi th the PSConsoleFile parameter or exported a console file during the cu rrent session. It is also required when you use the NoClobber parameter to prevent the current console file from being overwritten. If you omit this parameter, Export-Console overwrites (replaces the con tent of) the console file that was used most recently in this session. The path to the most recently used console file is stored in the value of the $ConsoleFileName automatic variable. For more information, see a bout_Automatic_Variables. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a path string to Export-Console. OUTPUTS System.IO.FileInfo Export-Console creates a file that contains the exported aliases. NOTES When a console file (.psc1) is used to start the session, the name of t he console file is automatically stored in the $ConsoleFileName automat ic variable. The value of $ConsoleFileName is updated when you use the Path parameter of Export-Console to specify a new console file. When n o console file is used, $ConsoleFileName has no value ($null). To use a Windows PowerShell console file in a new session, use the foll owing syntax to start Windows PowerShell: "powershell.exe -PsConsoleFile <ConsoleFile>.psc1". You can also save Windows PowerShell snap-ins for future sessions by ad ding an Add-PSSnapin command to your Windows PowerShell profile. For mo re information, see about_Profiles. -------------------------- EXAMPLE 1 -------------------------- C:\PS>export-console -path $pshome\Consoles\ConsoleS1.psc1 Description ----------- This command exports the names of Windows PowerShell snap-ins in the curren t session to the ConsoleS1.psc1 file in the Consoles subdirectory of the Wi ndows PowerShell installation directory, $pshome. -------------------------- EXAMPLE 2 -------------------------- C:\PS>export-console Description ----------- This command exports the names of Windows PowerShell snap-ins from current session to the Windows PowerShell console file that was most recently used in the current session. It overwrites the previous file contents. If you have not exported a console file during the current session, you are prompted for permission to continue and then prompted for a file name. -------------------------- EXAMPLE 3 -------------------------- C:\PS>add-pssnapin NewPSSnapin C:\PS> export-console -path NewPSSnapinConsole.psc1 C:\PS> powershell.exe -PsConsoleFile NewPsSnapinConsole.psc1 Description ----------- These commands add the NewPSSnapin Windows PowerShell snap-in to the curren t session, export the names of Windows PowerShell snap-ins in the current s ession to a console file, and then start a Windows PowerShell session with the console file. The first command uses the Add-PSSnapin cmdlet to add the NewPSSnapin snap- in to the current session. You can only add Windows PowerShell snap-ins tha t are registered on your system. The second command exports the Windows PowerShell snap-in names to the NewP SSnapinConsole.psc1 file. The third command starts Windows PowerShell with the NewPSSnapinConsole.psc 1 file. Because the console file includes the Windows PowerShell snap-in na me, the cmdlets and providers in the snap-in are available in the current s ession. -------------------------- EXAMPLE 4 -------------------------- C:\PS>export-console -path Console01 C:\PS> notepad console01.psc1 <?xml version="1.0" encoding="utf-8"?> <PSConsoleFile ConsoleSchemaVersion="1.0"> <PSVersion>2.0</PSVersion> <PSSnapIns> <PSSnapIn Name="NewPSSnapin" /> </PSSnapIns> </PSConsoleFile> Description ----------- This command exports the names of the Windows PowerShell snap-ins in the cu rrent session to the Console01.psc1 file in the current directory. The second command displays the contents of the Console01.psc1 file in Note pad. -------------------------- EXAMPLE 5 -------------------------- C:\PS>powershell.exe -PSConsoleFile Console01.psc1 C:\PS> add-pssnapin MySnapin C:\PS> export-console NewConsole.psc1 C:\PS> $consolefilename C:\PS> add-pssnapin SnapIn03 C:\PS> export-console Description ----------- This example shows how to use the $ConsoleFileName automatic variable to de termine the console file that will be updated if you use Export-Console wit hout a Path parameter value. The first command uses the PSConsoleFile parameter of PowerShell.exe to ope n Windows PowerShell with the Console01.psc1 file. The second command uses the Add-PSSnapin cmdlet to add the MySnapin Windows PowerShell snap-in to the current session. The third command uses the Export-Console cmdlet to export the names of all the Windows PowerShell snap-ins in the session to the NewConsole.psc1 file . The fourth command uses the $ConsoleFileName parameter to display the most recently used console file. The sample output shows that NewConsole.ps1 is the most recently used file. The fifth command adds SnapIn03 to the current console. The sixth command uses the ExportConsole cmdlet without a Path parameter. T his command exports the names of all the Windows PowerShell snap-ins in the current session to the most recently used file, NewConsole.psc1. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113298 Add-PSSnapin Get-PSSnapin Remove-PSSnapin Export-Counter NAME Export-Counter SYNOPSIS The Export-Counter cmdlet takes PerformanceCounterSampleSet objects and exp orts them as counter log files. SYNTAX Export-Counter [-Path] <string> -InputObject <PerformanceCounterSampleSet[] > [-Circular <switch>] [-FileFormat <string>] [-Force <switch>] [-MaxSize int>] [<CommonParameters>] DESCRIPTION The Export-Counter cmdlet exports performance counter data (PerformanceCoun terSampleSet objects) to log files in binary performance log (.blg), comma- separated value (.csv), or tab-separated value (.tsv) format. You can use this cmdlet to log or relog performance counter data. Export-Counter is designed to export data that is returned by the Get-Count er and Import-Counter cmdlets. Note: Export-Counter runs only on Windows 7, Windows Server 2008 R2, and la ter versions of Windows. PARAMETERS -Circular <switch> Indicates that output file should be a circular log with first in, firs t out (FIFO) format. When you include this parameter, the MaxSize param eter is required. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -FileFormat <string> Specifies the output format of the output log file. Valid values are C SV, TSV, and BLG. The default value is BLG. Required? false Position? named Default value BLG Accept pipeline input? false Accept wildcard characters? false -Force <switch> Overwrites and replaces an existing file if one exists in the location specified by the Path parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <PerformanceCounterSampleSet[]> Specifies the counter data to export. Enter a variable that contains th e data or a command that gets the data, such as a Get-Counter or Import -Counter command. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -MaxSize <int> Specifies the maximum size of the output file. If the Circular parameter is specified, then when the log file reaches the specified maximum size, the oldest entries are deleted as newer one s are added. If the Circular parameter is not specified, then when the log file reaches the specified maximum size, no new data is added and t he cmdlet generates a non-terminating error. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the path and file name of the output file. Enter a relative o r absolute path on the local computer, or a Uniform Naming Convention ( UNC) path to a remote computer, such as \\Computer\Share\file.blg. This parameter is required. Note: The file format is determined by the value of the FileFormat para meter, not by the file name extension in the path. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet You can pipe performance counter data from Get-Counter or Import-Counte r to Export-Counter. OUTPUTS None NOTES The log file generator expects that all input objects have the same cou nter path and that the objects are arranged in ascending time order. The counter type and path of the first input object determines the prop erties recorded in the log file. If other input objects do not have a v alue for a recorded property, the property field is empty. If the objec ts have property values that were not recorded, the extra property valu es are ignored. Performance Monitor might not be able to read all logs that Export-Coun ter generates. For example, Performance Monitor requires that all objec ts have the same path and that all objects are separated by the same ti me interval. The Import-Counter cmdlet does not have a ComputerName parameter. Howev er, if the computer is configured for Windows PowerShell remoting, you can use the Invoke-Command cmdlet to run an Import-Counter command on a remote computer. -------------------------- EXAMPLE 1 -------------------------- C:\PS># Export-Counter Description ----------- This command exports counter data to a .blg file. The command uses the Get-Counter cmdlet to collect processor time data. It uses a pipeline operator (|) to send the data to the Export-Counter cmdlet. The Export-Counter command uses the Path variable to specify the output fi le. C:\PS> get-counter "\Processor(*)\% Processor Time" -max 50 | export-counte r -path $home\counters.blg Because the data set might be very large, this command sends the data to Ex port-Counter through the pipeline. If the data were saved in a variable, th e command might use a disproportionate amount of memory. -------------------------- EXAMPLE 2 -------------------------- C:\PS># Export-Counter Description ----------- These commands convert a CSV file to a counter data BLG format. The first command uses the built-in Windows PowerShell conversion feature t o store the value of 1 gigabyte (GB) in bytes in the $1GBinBytes variable. When you type a value followed by K (kilobyte), MB (megabyte), or GB, Windo ws PowerShell returns the value in bytes. C:\PS> $1GBinBytes = 1GB The second command uses the Import-Counter cmdlet to import performance cou nter data from the Threads.csv file. The example presumes that this file wa s previously exported by using the Export-Counter cmdlet. A pipeline operator (|) sends the imported data to the Export-Counter cmdle t. The command uses the Path parameter to specify the location of the outpu t file. It uses the Circular and MaxSize parameters to direct Export-Counte r to create a circular log that wraps at 1 GB. C:\PS> import-counter threads.csv | export-counter -path threadtest.blg -ci rcular -maxsize $1GBinBytes -------------------------- EXAMPLE 3 -------------------------- C:\PS># Export-Counter Description ----------- This example shows how to get performance counter data from a remote comput er and save the data in a file on the remote computer. The first command uses the Get-Counter cmdlet to collect working set counte r data from Server01, a remote computer. The command saves the data in the $c variable. C:\PS> $c = get-counter -computername Server01 -counter "\Process(*)\Workin g Set - Private" -maxSamples 20 The second command uses a pipeline operator (|) to send the data in $c to t he Export-Counter cmdlet, which saves it in the Workingset.blg file in the Perf share on the Server01 computer. C:\PS> $c | export-counter -path \\Server01\Perf\WorkingSet.blg -------------------------- EXAMPLE 4 -------------------------- C:\PS># Export-Counter Description ----------- This example shows how to use the Import-Counter and Export-Counter cmdlets to relog existing data. The first command uses the Import-Counter cmdlet to import performance coun ter data from the DiskSpace.blg log. It saves the data in the $all variable . This file contains samples of the "LogicalDisk\% Free Space" counter on m ore than 200 remote computers in the enterprise. C:\PS> $all = import-counter DiskSpace.blg The second command uses the CounterSamples property of the sample set objec t in $all and the Where-Object cmdlet (alias = "where") to select objects w ith CookedValues of less than 15 (percent). The command saves the results i n the $lowSpace variable. C:\PS> $lowSpace = $all.countersamples | where {$_.cookedvalues -lt 15} The third command uses a pipeline operator (|) to send the data in the $low Space variable to the Export-Counter cmdlet. The command uses the path vari able to indicate that the selected data should be logged in the LowDiskSpac e.blg file. C:\PS> $lowSpace | export-counter -path LowDiskSpace.blg RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=138337 Get-Counter Import-Counter Export-CSV NAME Export-CSV SYNOPSIS Converts Microsoft .NET Framework objects into a series of comma-separated value (CSV) variable-length strings and saves the strings in a CSV file. SYNTAX Export-CSV [[-Delimiter] <char>] [-Path] <string> -InputObject <psobject> [ -Encoding <string>] [-Force] [-NoClobber] [-NoTypeInformation] [-Confirm] [ -WhatIf] [<CommonParameters>] Export-CSV [-UseCulture] [-Path] <string> -InputObject <psobject> [-Encodin g <string>] [-Force] [-NoClobber] [-NoTypeInformation] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Export-CSV cmdlet creates a CSV variable-length file that represents th e objects that you submit. You can then use the Import-CSV cmdlet to re-create objects from the CSV st rings in the files. The resulting objects are CSV versions of the original objects that consist of string representations of the property values and n o methods. You can also use the ConvertTo-CSV and ConvertFrom-CSV cmdlets to convert . NET Framework objects to CSV strings (and back). Export-CSV is the same as ConvertTo-CSV, except that it saves the CSV strings in a file. You can use the parameters of the Export-CSV cmdlet to specify a delimiter other than a comma or to direct Export-CSV to use the default delimiter for the current culture. When you submit multiple objects to Export-CSV, Export-CSV organizes the fi le based on the properties of the first object that you submit. If the rema ining objects do not have one of the specified properties, the property val ue of that object is null, as represented by two consecutive commas. If the remaining objects have additional properties, those property values are no t included in the file. For more information, see Export-CSV, and see the Notes section. PARAMETERS -Delimiter <char> Specifies a delimiter to separate the property values. The default is a comma (,). Enter a character, such as a colon (:). To specify a semico lon (;), enclose it in quotation marks. Required? false Position? 2 Default value , (comma) Accept pipeline input? false Accept wildcard characters? false -Encoding <string> Specifies the encoding for the exported CSV file. Valid values are Unic ode, UTF7, UTF8, ASCII, UTF32, BigEndianUnicode, Default, and OEM. The default is ASCII. Required? false Position? named Default value ASCII Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Overwrites the file specified in path without prompting. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to export as CSV strings. Enter a variable that c ontains the objects or type a command or expression that gets the objec ts. You can also pipe objects to Export-CSV. Required? true Position? named Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -NoClobber [<SwitchParameter>] Do not overwrite (replace the contents) of an existing file. By default , if a file exists in the specified path, Export-CSV overwrites the fil e without warning. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -NoTypeInformation [<SwitchParameter>] Omits the type information from the CSV file. By default, the first lin e of the CSV file contains "#TYPE " followed by the fully-qualified nam e of the type of the .NET Framework object. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the path to the CSV output file. The parameter is required. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -UseCulture [<SwitchParameter>] Use the list separator for the current culture as the item delimiter. T he default is a comma (,). This parameter is very useful in scripts that are being distributed to users worldwide. To find the list separator for a culture, use the foll owing command: (Get-Culture).TextInfo.ListSeparator. Required? false Position? named Default value Comma Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any .NET Framework object to Export-CSV. OUTPUTS System.String The CSV list is sent to the file designated in the Path parameter. NOTES The Export-CSV cmdlet converts the objects that you submit into a serie s of CSV variable-length strings and saves them in the specified text f ile. You can use Export-CSV to save objects in a CSV file and then use the Import-CSV cmdlet to create objects from the text in the CSV file. In the CSV file, each object is represented by a comma-separated list o f the property values of the object. The property values are converted to strings (by using the ToString() method of the object), so they are generally represented by the name of the property value. Export-CSV doe s not export the methods of the object. The format of an exported file is as follows: -- The first line of the CSV file contains the string '#TYPE ' followed by the fully qualified name of the .NET Framework type of the object, such as #TYPE System.Diagnostics.Process. To suppress this line, use th e NoTypeInformation parameter. -- The next line of the CSV file represents the column headers. It cont ains a comma-separated list of the names of all the properties of the f irst object. -- Additional lines of the file consist of comma-separated lists of the property values of each object. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process wmiprvse | select-object basePriority,ID,SessionID,Workin gSet | export-csv -path data.csv Description ----------- This command selects a few properties of the wmiprvse process and exports t hem to a CSV format file named data.csv. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-process | export-csv processes.csv C:\PS> get-process | export-csv processes.csv # In processes.csv #TYPE System.Diagnostics.Process __NounName,Name,Handles,VM,WS,PM,NPM,Path,Company,CPU,FileVersion,... Process,powershell,626,201666560,76058624,61943808,11960,C:\WINDOWS... Process,powershell,257,151920640,38322176,37052416,7836,C:\WINDOWS\... Description ----------- This command exports objects representing the processes on the computer to the Processes.csv file in the current directory. Because it does not specif y a delimiter, a comma (,) is used to separate the fields in the file. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-process | export-csv processes.csv -Delimiter ";" # In processes.csv #TYPE System.Diagnostics.Process __NounName;Name;Handles;VM;WS;PM;NPM;Path;Company;CPU;FileVersion;... Process;powershell;626;201666560;76058624;61943808;11960;C:\WINDOWS... Process;powershell;257;151920640;38322176;37052416;7836;C:\WINDOWS\... Description ----------- This command exports objects representing the processes on the computer to the Processes.csv file in the current directory. It uses the Delimiter para meter to specify the semicolon (;). As a result, the fields in the file are separated by semicolons. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-process | export-csv processes.csv -UseCulture Description ----------- This command exports objects representing the processes on the computer to the Processes.csv file in the current directory. It uses the UseCulture par ameter to direct Export-CSV to use the delimiter specified by the ListSepar ator property of the current culture. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-process | export-csv processes.csv -NoTypeInformation C:\PS> get-process | export-csv processes.csv -NoTypeInformation # In processes.csv __NounName,Name,Handles,VM,WS,PM,NPM,Path,Company,CPU,FileVersion,... Process,powershell,626,201666560,76058624,61943808,11960,C:\WINDOWS... Process,powershell,257,151920640,38322176,37052416,7836,C:\WINDOWS\... Description ----------- This command exports objects representing the processes on the computer to the Processes.csv file in the current directory. It uses the NoTypeInformat ion parameter to suppress the type information in the file. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113299 Import-CSV ConvertTo-CSV ConvertFrom-CSV Export-FormatData NAME Export-FormatData SYNOPSIS Saves formatting data from the current session in a formatting file. SYNTAX Export-FormatData [-Force] [-IncludeScriptBlock] [-InputObject <ExtendedTyp eDefinition[]>] [-NoClobber] [-Path <string>] [<CommonParameters>] DESCRIPTION The Export-FormatData cmdlet creates Windows PowerShell formatting files (f ormat.ps1xml) from the formatting objects in the current session. It takes the ExtendedTypeDefinition objects that Get-FormatData returns and saves th em in a file in XML format. Windows PowerShell uses the data in formatting files (format.ps1xml) to gen erate the default display of Microsoft .NET Framework objects in the sessio n. You can view and edit the formatting files and use the Update-FormatData cmdlet to add the formatting data to a session. For more information about formatting files in Windows PowerShell, see abou t_Format.ps1xml. PARAMETERS -Force [<SwitchParameter>] Overwrites an existing output file, even if the file has the read-only attribute. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -IncludeScriptBlock [<SwitchParameter>] Determines whether script blocks in the format data are exported. Because script blocks contain code and can be used maliciously, they ar e not exported by default. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -InputObject <ExtendedTypeDefinition[]> Specifies the format data objects to be exported. Enter a variable that contains the objects or a command that gets the objects, such as a Get -FormatData command. You can also pipe the objects from Get-FormatData to Export-FormatData. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -NoClobber [<SwitchParameter>] Prevents the cmdlet from overwriting existing files. By default, Export -FormatData overwrites files without warning unless the file has the re ad-only attribute. To direct Export-FormatData to overwrite read-only files, use the Force parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies a location for the output file. Enter a path (optional) and file name with a format.ps1xml file name extension. If you omit the pat h, Export-FormatData creates the file in the current directory. If you use a file name extension other than .ps1xml, the Update-FormatD ata cmdlet will not recognize the file. If you specify an existing file, Export-FormatData overwrites the file without warning, unless the file has the read-only attribute. To overwr ite a read-only file, use the Force parameter. To prevent files from be ing overwritten, use the NoClobber parameter. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.ExtendedTypeDefinition You can pipe ExtendedTypeDefinition objects from Get-FormatData to Expo rt-FormatData. OUTPUTS None Export-FormatData does not return any objects. It generates a file and saves it in the specified path. NOTES To use any formatting file, including an exported formatting file, the execution policy for the session must allow scripts and configuration f iles to run. For more information, see about_Execution_Policies. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-formatdata -typename * | export-formatdata -path allformat.ps1xml -IncludeScriptBlock Description ----------- This command exports all of the format data in the session to the AllFormat .ps1xml file. The command uses the Get-FormatData cmdlet to get the format data in the se ssion. A value of * (all) for the TypeName parameter directs the cmdlet to get all of the data in the session. The command uses a pipeline operator (|) to send the format data from the G et-FormatData command to the Export-FormatData cmdlet, which exports the fo rmat data to the AllFormat.ps1 file. The Export-FormatData command uses the IncludeScriptBlock parameter to incl ude script blocks in the format data in the file. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$f = get-formatdata -typename helpinfoshort C:\PS> export-formatdata -inputObject $f -path c:\test\help.format.ps1xml - IncludeScriptBlock Description ----------- These commands export the format data for the HelpInfoShort type to the Hel p.format.ps1xml file. The first command uses the Get-FormatData cmdlet to get the format data for the HelpInfoShort type, and it saves it in the $f variable. The second command uses the InputObject parameter of the Export-FormatData to enter the format data saved in the $f variable. It also uses the Include ScriptBlock parameter to include script blocks in the output. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-formatdata -typename System.Diagnostics.Process | export-FormatDa ta -path process.format.ps1xml C:\PS> Update-FormatData -prependPath .\process.format.ps1xml C:\PS> get-process p* Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 323 5600 powershell 336 3900 powershell_ise 138 4076 PresentationFontCache Description ----------- This example shows the effect of omitting the IncludeScriptBlock parameter from an Export-FormatData command. The first command uses the Get-FormatData cmdlet to get the format data for the System.Diagnostics.Process object that the Get-Process cmdlet returns. The command uses a pipeline operator (|) to send the formatting data to th e Export-FormatData cmdlet, which exports it to the Process.format.ps1xml f ile in the current directory. In this case, the Export-FormatData command does not use the IncludeScriptB lock parameter. The second command uses the Update-FormatData cmdlet to add the Process.for mat.ps1xml file to the current session. The command uses the PrependPath pa rameter to ensure that the formatting data for process objects in the Proce ss.format.ps1xml file is found before the standard formatting data for proc ess objects. The third command shows the effects of this change. The command uses the Ge t-Process cmdlet to get processes that have names that begin with "P". The output shows that property values that are calculated by using script block s are missing from the display. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144302 Get-FormatData Update-FormatData Export-ModuleMember NAME Export-ModuleMember SYNOPSIS Specifies the module members that are exported. SYNTAX Export-ModuleMember [[-Function] <string[]>] [-Alias <string[]>] [-Cmdlet string[]>] [-Variable <string[]>] [<CommonParameters>] DESCRIPTION The Export-ModuleMember cmdlet specifies the module members (such as cmdlet s, functions, variables, and aliases) that are exported from a script modul e (.psm1) file, or from a dynamic module created by using the New-Module cm dlet. This cmdlet can be used only in a script module file or a dynamic mod ule. If a script module does not include an Export-ModuleMember command, the fun ctions in the script module are exported, but the variables and aliases are not. When a script module includes an Export-ModuleMember command, only th e members specified in the Export-ModuleMember command are exported. If a script module contains multiple Export-ModuleMember commands, only the members listed in an Export-ModuleMember command are exported. You can also use Export-ModuleMember to export members that the script modu le imports from other modules. PARAMETERS -Alias <string[]> Specifies the aliases that are exported from the script module file. En ter the alias names. Wildcards are permitted. Required? false Position? named Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Cmdlet <string[]> Specifies the cmdlets that are exported from the script module file. En ter the cmdlet names. Wildcards are permitted. You cannot create cmdlets in a script module file, but you can import c mdlets from a binary module into a script module and re-export them fro m the script module. Required? false Position? named Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Function <string[]> Specifies the functions that are exported from the script module file. Enter the function names. Wildcards are permitted. You can also pipe fu nction name strings to Export-ModuleMember. Required? false Position? 1 Default value None Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true -Variable <string[]> Specifies the variables that are exported from the script module file. Enter the variable names (without a dollar sign). Wildcards are permitt ed. Required? false Position? named Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe function name strings to Export-ModuleMember. OUTPUTS None This cmdlet does not generate any output. NOTES To exclude a member from the list of exported members, add an Export-Mo duleMember command that lists all other members but omits the member th at you want to exclude. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Export-ModuleMember -function * -alias * Description ----------- This command exports the aliases defined in the script module, along with t he functions defined in the script module. To export the aliases, which are not exported by default, you must also exp licitly specify the functions. Otherwise, only the aliases will be exported . -------------------------- EXAMPLE 2 -------------------------- C:\PS>Export-ModuleMember -function Get-Test, New-Test, Start-Test -alias g tt, ntt, stt Description ----------- This command exports three aliases and three functions defined in the scrip t module. You can use this command format to specify the names of module members. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Export-ModuleMember Description ----------- This command specifies that no members defined in the script module are exp orted. This command prevents the module members from being exported, but it does n ot hide the members. Users can read and copy module members or use the call operator (&) to invoke module members that are not exported. -------------------------- EXAMPLE 4 -------------------------- C:\PS>Export-ModuleMember -variable increment Description ----------- This command exports only the $increment variable from the script module. N o other members are exported. If you want to export a variable, in addition to exporting the functions in a module, the Export-ModuleMember command must include the names of all of the functions and the name of the variable. -------------------------- EXAMPLE 5 -------------------------- C:\PS># From TestModule.psm1 function new-test { <function code> } export-modulemember -function new-test function validate-test { <function code> } function start-test { <function code> } set-alias stt start-test export-modulemember -function *-test -alias stt Description ----------- These commands show how multiple Export-ModuleMember commands are interpret ed in a script module (.psm1) file. These commands create three functions and one alias, and then they export t wo of the functions and the alias. Without the Export-ModuleMember commands, all three of the functions would be exported, but the alias would not be exported. With the Export-ModuleMem ber commands, only the Get-Test and Start-Test functions and the STT alias are exported. -------------------------- EXAMPLE 6 -------------------------- C:\PS>new-module -script {function SayHello {"Hello"}; set-alias Hi SayHel lo; Export-ModuleMember -alias Hi -function SayHello} Description ----------- This command shows how to use Export-ModuleMember in a dynamic module that is created by using the New-Module cmdlet. In this example, Export-ModuleMember is used to export both the "Hi" alias and the "SayHello" function in the dynamic module. -------------------------- EXAMPLE 7 -------------------------- C:\PS>function export { param ( [parameter(mandatory=$true)] [validateset("function","variable")] $ type, [parameter(mandatory=$true)] $name, [parameter(mandatory=$true)] $value ) if ($type -eq "function") { Set-item "function:script:$name" $value Export-ModuleMember $name } else { Set-Variable -scope Script $name $value Export-ModuleMember -variable $name } } export function New-Test { ... } function helper { ... } export variable interval 0 $interval = 2 Description ----------- This example includes a function named Export that declares a function or c reates a variable, and then writes an Export-ModuleMember command for the f unction or variable. This lets you declare and export a function or variabl e in a single command. To use the Export function, include it in your script module. To export a f unction, type "Export" before the Function keyword. To export a variable, use the following format to declare the variable and set its value: export variable <variable-name> <value> The commands in the example show the correct format. In this example, only the New-Test function and the $Interval variable are exported. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=141551 Import-Module Get-Module Remove-Module about_Modules Export-PSSession NAME Export-PSSession SYNOPSIS Imports commands from another session and saves them in a Windows PowerShel l module. SYNTAX Export-PSSession [-Session] <PSSession> [-OutputModule] <string> [[-Command Name] <string[]>] [[-FormatTypeName] <string[]>] [-AllowClobber] [-Argument List <Object[]>] [-CommandType {Alias | Function | Filter | Cmdlet | Extern alScript | Application | Script | All}] [-Encoding <string>] [-Force] [-Mod ule <string[]>] [<CommonParameters>] DESCRIPTION The Export-PSSession cmdlet gets cmdlets, functions, aliases, and other com mand types from another PSSession on a local or remote computer and saves t hem in a Windows PowerShell module. To add the commands from the module to the current session, use the Import-Module cmdlet. Unlike Import-PSSession, which imports commands from another PSSession into the current session, Export-PSSession saves the commands in a module. The commands are not imported into the current session. To export commands, first use the New-PSSession cmdlet to create a PSSessio n that has the commands that you want to export. Then use the Export-PSSess ion cmdlet to export the commands. By default, Export-PSSession exports all commands, except for commands that exist in the current session, but you c an use the CommandName parameters to specify the commands to export. The Export-PSSession cmdlet uses the implicit remoting feature of Windows P owerShell. When you import commands into the current session, they run impl icitly in the original session or in a similar session on the originating computer. PARAMETERS -AllowClobber [<SwitchParameter>] Exports the specified commands, even if they have the same names as com mands in the current session. If you import a command with the same name as a command in the current session, the imported command hides or replaces the original commands. For more information, see about_Command_Precedence. Export-PSSession does not import commands that have the same names as c ommands in the current session. The default behavior is designed to pre vent command name conflicts. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -ArgumentList <Object[]> Exports the variant of the command that results from using the specifie d arguments (parameter values). For example, to export the variant of the Get-Item command in the certi ficate (Cert:) drive in the PSSession in $s, type "export-pssession -se ssion $s -command get-item -argumentlist cert:". Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -CommandName <string[]> Exports only the commands with the specified names or name patterns. Wi ldcards are permitted. Use "CommandName" or its alias, "Name". By default, Export-PSSession exports all commands from the PSSession ex cept for commands that have the same names as commands in the current s ession. This prevents imported commands from hiding or replacing comman ds in the current session. To export all commands, even those that hide or replace other commands, use the AllowClobber parameter. If you use the CommandName parameter, the formatting files for the comm ands are not exported unless you use the FormatTypeName parameter. Simi larly, if you use the FormatTypeName parameter, no commands are exporte d unless you use the CommandName parameter. Required? false Position? 3 Default value All commands in the session. Accept pipeline input? false Accept wildcard characters? true -CommandType <CommandTypes> Exports only the specified types of command objects. Use "CommandType" or its alias, "Type". Valid values are: -- Alias: All Windows PowerShell aliases in the current session. -- All: All command types. It is the equivalent of "get-command *". -- Application: All files other than Windows PowerShell files in paths listed in the Path environment variable ($env:path), including .txt, .e xe, and .dll files. -- Cmdlet: The cmdlets in the current session. "Cmdlet" is the default. -- ExternalScript: All .ps1 files in the paths listed in the Path envir onment variable ($env:path). -- Filter and Function: All Windows PowerShell functions. -- Script: Script blocks in the current session. Required? false Position? named Default value All commands in the session. Accept pipeline input? false Accept wildcard characters? false -Encoding <string> Specifies the encoding for the output files. Valid values are "Unicode" , "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", and "OEM". The default is "UTF-8". Required? false Position? named Default value UTF-8 Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Overwrites one or more existing output files, even if the file has the read-only attribute. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -FormatTypeName <string[]> Exports formatting instructions only for the specified Microsoft .NET F ramework types. Enter the type names. By default, Export-PSSession expo rts formatting instructions for all .NET Framework types that are not i n the System.Management.Automation namespace. The value of this parameter must be the name of a type that is returned by a Get-FormatData command in the session from which the commands are being imported. To get all of the formatting data in the remote sessio n, type *. If you use the FormatTypeName parameter, no commands are exported unles s you use the CommandName parameter. Similarly, if you use the CommandName parameter, the formatting files f or the commands are not exported unless you use the FormatTypeName para meter. Required? false Position? 4 Default value Accept pipeline input? false Accept wildcard characters? false -Module <string[]> Exports only the commands in the specified Windows PowerShell snap-ins and modules. Enter the snap-in and module names. Wildcards are not perm itted. For more information, see about_PSSnapins and Import-Module. Required? false Position? named Default value All commands in the session. Accept pipeline input? false Accept wildcard characters? false -OutputModule <string> Specifies a path (optional) and name for the module that Export-PSSessi on creates. The default path is $home\Documents\WindowsPowerShell\Modul es. This parameter is required. If the module subdirectory or any of the files that Export-PSSession cr eates already exist, the command fails. To overwrite existing files, us e the Force parameter. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Session <PSSession> Specifies the PSSession from which the commands are exported. Enter a variable that contains a session object or a command that gets a sessio n object, such as a Get-PSSession command. This parameter is required. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Export-PSSession. OUTPUTS System.IO.FileInfo Export-PSSession returns a list of files that comprise the module that it created. NOTES Export-PSSession relies on the Windows PowerShell remoting infrastructu re. To use this cmdlet, the computer must be configured for remoting. F or more information, see about_Remote_Requirements. You cannot use Export-PSSession to export a Windows PowerShell provider . Exported commands run implicitly in the PSSession from which they were exported. However, the details of running the commands remotely are han dled entirely by Windows PowerShell. You can run the exported commands just as you would run local commands. Export-Module captures and saves information about the PSSession in the module that it exports. If the PSSession from which the commands were exported is closed when you import the module, and there are no active PSSessions to the same computer, the commands in the module attempt to re-create the PSSession. If attempts to re-create the PSSession fail, t he exported commands will not run. The session information that Export-Module captures and saves in the mo dule does not include session options, such as those that you specify i n the $PSSessionOption automatic variable or by using the SessionOption parameters of the New-PSSession, Enter-PSSession, or Invoke-Command c mdlet. If the original PSSession is closed when you import the module, the module will use another PSSession to the same computer, if one is a vailable. To enable the imported commands to run in a correctly configu red session, create a PSSession with the options that you want before y ou import the module. To find the commands to export, Export-PSSession uses the Invoke-Comman d cmdlet to run a Get-Command command in the PSSession. To get and save formatting data for the commands, it uses the Get-FormatData and Expor t-FormatData cmdlets. You might see error messages from Invoke-Command, Get-Command, Get-FormatData, and Export-FormatData when you run an Exp ort-PSSession command. Also, Export-PSSession cannot export commands fr om a session that does not include the Get-Command, Get-FormatData, Sel ect-Object, and Get-Help cmdlets. Export-PSSession uses the Write-Progress cmdlet to display the progress of the command. You might see the progress bar while the command is ru nning. Exported commands have the same limitations as other remote commands, i ncluding the inability to start a program with a user interface, such a s Notepad. Because Windows PowerShell profiles are not run in PSSessions, the comm ands that a profile adds to a session are not available to Export-PSSes sion. To export commands from a profile, use an Invoke-Command command to run the profile in the PSSession manually before exporting commands. The module that Export-PSSession creates might include a formatting fil e, even if the command does not import formatting data. If the command does not import formatting data, any formatting files that are created will not contain formatting data. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$s = new-pssession -computerName Server01 C:\PS> export-pssession -session $s -outputModule Server01 Description ----------- The commands in this example export all commands from a PSSession on the Se rver01 computer to the Server01 module on the local computer except for com mands that have the same names as commands in the current session. It also exports the formatting data for the commands. The first command creates a PSSession on the Server01 computer. The second command exports the commands and formatting data from the session into the Server01 module. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$s = new-pssession -ConnectionUri http://exchange.microsoft.com/mailb ox -credential exchangeadmin01@hotmail.com -authentication negotiate C:\PS> export-pssession -session $r -module exch* -commandname get-*, set-* -formattypename * -outputModule $pshome\Modules\Exchange -encoding ASCII Description ----------- These commands export the Get and Set commands from a Microsoft Exchange Se rver snap-in on a remote computer to an Exchange module in the $pshome\Modu les directory on the local computer. Placing the module in the $pshome\Module directory makes it accessible to a ll users of the computer. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$s = new-pssession -computerName Server01 -credential Server01\User01 C:\PS> export-pssession -session $s -outputModule TestCmdlets -type cmdlet -commandname *test* -formattypename * C:\PS> remove-pssession $s C:\PS> import-module TestCmdlets C:\PS> get-help test* C:\PS> test-files Description ----------- These commands export cmdlets from a PSSession on a remote computer and sav e them in a module on the local computer. Then, the commands add the cmdlet s from the module to the current session so that they can be used. The first command creates a PSSession on the Server01 computer and saves it in the $s variable. The second command exports the cmdlets whose names begin with "Test" from t he PSSession in $s to the TestCmdlets module on the local computer. The third command uses the Remove-PSSession cmdlet to delete the PSSession in $s from the current session. This command shows that the PSSession need not be active to use the commands that were imported from it. The fourth command, which can be run in any session at any time, uses the I mport-Module cmdlet to add the cmdlets in the TestCmdlets module to the cur rent session. The fifth command uses the Get-Help cmdlet to get help for cmdlets whose na mes begin with "Test." After the commands in a module are added to the curr ent session, you can use the Get-Help and Get-Command cmdlets to learn abou t the imported commands, just as you would use them for any command in the session. The sixth command uses the Test-Files cmdlet, which was exported from the S erver01 computer and added to the session. Although it is not evident, the Test-Files command actually runs in a remot e session on the computer from which the command was imported. Windows Powe rShell creates a session from information that is stored in the module. -------------------------- EXAMPLE 4 -------------------------- C:\PS>export-pssession -session $s -AllowClobber -outputModule AllCommands Description ----------- This command exports all commands and all formatting data from the PSSessio n in the $s variable into the current session. The command uses the AllowCl obber parameter to include commands with the same names as commands in the current session. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$options = New-PSSessionOption -NoMachineProfile C:\PS> $s = new-pssession -computername Server01 -sessionoption $options C:\PS> export-pssession -session $s -outputModule Server01 C:\PS> remove-pssession $s C:\PS> new-pssession -computername Server01 -sessionoption $options C:\PS> import-module Server01 Description ----------- This example shows how to run the exported commands in a session with parti cular options when the PSSession from which the commands were exported is c losed. When you use Export-PSSession, it saves information about the original PSSe ssion in the module that it creates. When you import the module, if the ori ginal remote session is closed, the module will use any open remote session that connects to originating computer. If the current session does not include a remote session to the originating computer, the commands in the module will re-establish a session to that c omputer. However, Export-PSSession does not save special options, such as t hose set by using the SessionOption parameter of New-PSSession, in the modu le. Therefore, if you want to run the exported commands in a remote session wit h particular options, you need to create a remote session with the options that you want before you import the module. The first command uses the New-PSSessionOption cmdlet to create a PSSession Option object, and it saves the object in the $options variable. The second command creates a PSSession that includes the specified options. The command uses the New-PSSession cmdlet to create a PSSession on the Ser ver01 computer. It uses the SessionOption parameter to submit the option ob ject in $options. The third command uses the Export-PSSession cmdlet to export commands from the PSSession in $s to the Server01 module. The fourth command uses the Remove-PSSession cmdlet to delete the PSSession in the $s variable. The fifth command uses the New-PSSession cmdlet to create a new PSSession t hat connects to the Server01 computer. This PSSession also uses the session options in the $options variable. The sixth command uses the Import-Module cmdlet to import the commands from the Server01 module. The commands in the module run in the PSSession on th e Server01 computer. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135213 about_Command_Precedence Import-PSSession New-PSSession Import-Module Invoke-Command about_PSSessions FileSystem PROVIDER NAME FileSystem DRIVES C, D SYNOPSIS Provides access to files and directories. DESCRIPTION The Windows PowerShell FileSystem provider lets you get, add, change, clear , and delete files and directories in Windows PowerShell. The FileSystem provider exposes Windows PowerShell drives that correspond t o the logical drives configured on your computer, including drives mapped t o network shares. For example, a computer with one floppy disk drive, one h ard disk drive, and one mapped network shared directory might have drives n amed A, C, and Z. The FileSystem provider exposes Windows PowerShell drives that correspond directly to A, C, and Z, allowing you to reference these d rives from within Windows PowerShell. For example, to reference drive C, yo u use C:, as shown in the following example: get-childitem c: The command returns all the contents on the C drive, including files and di rectories. When you reference a specific directory or file through the File System provider, you must provide the information necessary to identify tha t directory or file. This means that, in some cases, you must provide a ful ly qualified name. A fully qualified name includes the drive name (along wi th a colon), any directory and subdirectory names, and the file name (when applicable). For instance, the following example shows the fully qualified name for the Shell.dll file, which is located in the System32 subdirectory of the Windows directory on the C drive: c:\windows\system32\shell.dll As you can see, each element of the fully qualified name is separated by a backslash (\). Windows PowerShell also allows you to use a forward slash (/ ) to be consistent with a variety of other shells. In some cases, you do not need to supply a fully-qualified name when refere ncing a file or directory. For example, if you want to access a file in you r current working location, you need to provide only the file name. If your current working location is c:\windows, you can view a list of all the .dl l files in that directory by using the following command: get-childitem *.dll If your working directory is something other than c:\windows, such as c:\pr ogram files\Windows PowerShell, your command might need to include the full y qualified name: get-childitem c:\windows\*.dll In some cases, you can use relative references to a location. If your worki ng location is c:\windows, and you want to view a list of .dll files in the c:\windows\system32 directory, you can use the following command: get-childitem .\system32\*.dll The period before \system32 represents the current working location. In some situations, your current working location will be on a drive other than a FileSystem drive. If this is the case, you must always include the n ame of the target drive in your reference. For example, suppose that your c urrent working location is the env: drive. To view the contents of the C dr ive, you would use the following command: get-childitem c: CAPABILITIES TASKS TASK: Navigating the File System -------------------------- EXAMPLE 1 -------------------------- This command gets the current location: get-location The Get-Location cmdlet includes the functionality of commands like the cd command in the Windows Command Prompt and the pwd command in UNIX. For more information, type: get-help get-location -------------------------- EXAMPLE 2 -------------------------- This command sets the current location: set-location C: TASK: Getting File and Directory Information -------------------------- EXAMPLE 1 -------------------------- This command gets all the files and directories in the current director y: get-childitem By default, the Get-ChildItem cmdlet does not recurse. If files and fol ders are present in the current directory when you run this command, a System.IO.FileInfo object and a System.IO.DirectoryInfo object are retu rned. -------------------------- EXAMPLE 2 -------------------------- This command gets all the files and directories in the current director y by using Get-ChildItem: get-childitem | where-object {$_.psiscontainer} It pipes the results to Where-Object, which examines the PSIsContainer property and lets only the objects that are not () containers through the pipeline. -------------------------- EXAMPLE 3 -------------------------- This command gets all the files and directories in the current director y by using Get-ChildItem. It pipes the results to Where-Object, which e xamines the PSIsContainer property and lets only the objects that are c ontainers through the pipeline. get-childitem | where-object {$_.psiscontainer} -------------------------- EXAMPLE 4 -------------------------- This command gets all the files and directories in the current director y by using Get-ChildItem: get-item -path a | format-list * It pipes the results to the Where-Object cmdlet, which examines the PSI sContainer property and lets only the objects that are containers throu gh the pipeline. -------------------------- EXAMPLE 5 -------------------------- This command uses the Get-Item cmdlet to get information about the Test .txt file: get-item -path test.txt | format-list * The Format-List cmdlet is used to display all the properties of the res ulting object. TASK: Copying Files and Directories -------------------------- EXAMPLE 1 -------------------------- This command copies the A.txt file from the C:\A directory to the C:\A\ Bb directory: copy-item -path C:\a\a.txt -destination C:\a\bb\a.txt It overwrites files in the destination directory without prompting for confirmation. -------------------------- EXAMPLE 2 -------------------------- This command copies all the files in the C:\A\Bb directory that have th e .txt file name extension to the C:\A\Cc\Ccc\ directory: copy-item -path C:\a\bb\*.txt -destination C:\a\cc\ccc\ It uses the original names of the files. The command overwrites the exi sting files in the destination directory without prompting for confirma tion. -------------------------- EXAMPLE 3 -------------------------- Copies all the directories and files in the C:\a directory to the C:\c directory. If any of the directories to copy already exist in the desti nation directory, the command will fail unless you specify the Force pa rameter. copy-item -path C:\a\* -destination C:\c -recurse TASK: Moving Files and Directories -------------------------- EXAMPLE 1 -------------------------- This command moves the C.txt file in the C:\A directory to the C:\A\Aa directory: move-item -path C:\a\c.txt -destination C:\a\aa The command will not automatically overwrite an existing file that has the same name. To force the cmdlet to overwrite an existing file, speci fy the Force parameter. -------------------------- EXAMPLE 2 -------------------------- This command moves the C:\A directory and all its contents to the C:\B directory: move-item -path C:\a -destination C:\b You cannot move a directory when that directory is the current location . TASK: Managing File Content -------------------------- EXAMPLE 1 -------------------------- This command appends the "test content" string to the Test.txt file: add-content -path test.txt -value "test content" The existing content in the Test.txt file is not deleted. -------------------------- EXAMPLE 2 -------------------------- This command gets the contents of the Test.txt file and displays them i n the console: get-content -path test.txt You can pipe the contents of the file to another cmdlet. For example, t he following command reads the contents of the Test.txt file and then s upplies them as input to the ConvertTo-HTML cmdlet: get-content -path test.txt | convertto-html -------------------------- EXAMPLE 3 -------------------------- This command replaces the contents of the Test.txt file with the "test content" string: set-content -path test.txt -value "test content" It overwrites the contents of Test.txt. You can use the Value parameter of the New-Item cmdlet to add content to a file when you create it. TASK: Managing Security Descriptors -------------------------- EXAMPLE 1 -------------------------- This command returns a System.Security.AccessControl.FileSecurity objec t: get-acl -path test.txt | format-list -property * For more information about this object, pipe the command to the Get-Mem ber cmdlet. Or, see "FileSecurity Class" in the MSDN (Microsoft Develop er Network) library at http://go.microsoft.com/fwlink/?LinkId=145718. -------------------------- EXAMPLE 2 -------------------------- This command returns a System.Security.AccessControl.DirectorySecurity object: get-acl -path test_directory | format-list -property * For more information about this object, pipe the command to the Get-Mem ber cmdlet. Or, see "DirectorySecurity Class" in the MSDN library at ht tp://go.microsoft.com/fwlink/?LinkId=145736. TASK: Creating Files and Directories -------------------------- EXAMPLE 1 -------------------------- This command creates the Logfiles directory on the C drive: new-item -path c:\ -name logfiles -type directory -------------------------- EXAMPLE 2 -------------------------- This command creates the Log2.txt file in the C:\Logfiles directory and then adds the "test log" string to the file: new-item -path c:\logfiles -name log.txt -type file -------------------------- EXAMPLE 3 -------------------------- Creates a file called Log2.txt in the C:\logfiles directory and adds th e string "test log" to the file. new-item -path c:\logfiles -name log2.txt -type file -value "test log" TASK: Renaming Files and Directories -------------------------- EXAMPLE 1 -------------------------- This command renames the A.txt file in the C:\A directory to B.txt: rename-item -path c:\a\a.txt -newname b.txt -------------------------- EXAMPLE 2 -------------------------- This command renames the C:\A\Cc directory to C:\A\Dd: rename-item -path c:\a\cc -newname dd TASK: Deleting Files and Directories -------------------------- EXAMPLE 1 -------------------------- This command deletes the Test.txt file in the current directory: remove-item -path test.txt -------------------------- EXAMPLE 2 -------------------------- This command deletes all the files in the current directory that have t he .xml file name extension: remove-item -path *.xml TASK: Starting a Program by Invoking an Associated File -------------------------- EXAMPLE 1 -------------------------- The first command uses the Get-Service cmdlet to get information about local services. It pipes the information to the Export-Csv cmdlet and then stores that information in the Services.csv file. The second command uses Invoke-Item to open the Services.csv file in th e program associated with the .csv extension: get-service | export-csv -path services.csv invoke-item -path services.csv DYNAMIC PARAMETERS -Encoding <Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding> Unknown The encoding type is unknown or invalid. The data can be treate d as binary. String Uses the encoding type for a string. Unicode Encodes in UTF-16 format using the little-endian byte order. Byte Encodes a set of characters into a sequence of bytes. BigEndianUnicode Encodes in UTF-16 format using the big-endian byte order. UTF8 Encodes in UTF-8 format. UTF7 Encodes in UTF-7 format. ASCII Uses the encoding for the ASCII (7-bit) character set. Cmdlets Supported: Add-Content, Get-Content, Set-Content -Delimiter <System.String> Specifies the delimiter to use when reading the file. The default is "\ n" (end of line). Cmdlets Supported: Get-Content -Wait <System.Management.Automation.SwitchParameter> Waits for content to be appended to the file. If content is appended, i t returns the appended content. If the content has changed, it returns the entire file. When waiting, Get-Content checks the file once each second until you in terrupt it, such as by pressing CTRL+C. Cmdlets Supported: Get-Content NOTES RELATED LINKS about_Providers ForEach-Object NAME ForEach-Object SYNOPSIS Performs an operation against each of a set of input objects. SYNTAX ForEach-Object [-Process] <ScriptBlock[]> [-Begin <scriptblock>] [-End <scr iptblock>] [-InputObject <psobject>] [<CommonParameters>] DESCRIPTION The ForEach-Object cmdlet performs an operation on each of a set of input o bjects. The input objects can be piped to the cmdlet or specified by using the InputObject parameter. The operation to perform is described within a script block that is provide d to the cmdlet as the value of the Process parameter. The script block can contain any Windows PowerShell script. Within the script block, the current input object is represented by the $_ variable. In addition to using the script block that describes the operations to be c arried out on each input object, you can provide two additional script bloc ks. One, specified as the value of the Begin parameter, runs before the fir st input object is processed. The other, specified as the value of the End parameter, runs after the last input object is processed. The results of the evaluation of all the script blocks, including the ones specified with Begin and End, are passed down the pipeline. PARAMETERS -Begin <scriptblock> Specifies a script block to run before processing any input objects. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -End <scriptblock> Specifies a script block to run after processing all input objects. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Accepts an object that the script block specified in the process parame ter will act upon. Enter a variable that contains the objects, or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Process <ScriptBlock[]> Specifies the script block that is applied to each incoming object. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to ForEach-Object. OUTPUTS System.Management.Automation.PSObject The objects that ForEach-Object returns are determined by the input. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>30000,56798,12432 | foreach-object -process {$_/1024} Description ----------- This command accepts an array of integers, divides each one of them by 1024 , and displays the results. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-childitem C:\ | foreach-object -process { $_.length / 1024 } Description ----------- This command retrieves the files and directories in the root of the C: driv e, and it returns and displays the size of each of them. The zeros represen t directories in which no file size was available. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$events = get-eventlog -logname system -newest 1000 C:\PS> $events | foreach-object -begin {get-date} -process {out-file -filep ath events.txt -append -inputobject $_.message} -end {get-date} Description ----------- This command retrieves the 1000 most recent events from the system log and stores them in the $events variable. It then pipes the events to the ForEac h-Object cmdlet. The Begin parameter displays the current date and time. Ne xt, the Process parameter uses the Out-File cmdlet to create a text file na med events.txt and stores the message property of each of the events in tha t file. Last, the End parameter is used to display the date and time after all of the processing has completed. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemprop erty -path $_.pspath -name RemotePath -value $_.RemotePath.ToUpper();} Description ----------- This command changes the value of the RemotePath registry entry in all of t he subkeys under the HKCU:\Network key to uppercase text. You can use this format to change the form or content of a registry entry value. Each subkey in the Network key represents a mapped network drive that will reconnect at logon. The RemotePath entry contains the UNC path of the conne cted drive. For example, if you map the E: drive to \\Server\Share, there w ill be an E subkey of HKCU:\Network and the value of the RemotePath registr y entry in the E subkey will be \\Server\Share. The command uses the Get-ItemProperty cmdlet to get all of the subkeys of t he Network key and the Set-ItemProperty cmdlet to change the value of the R emotePath registry entry in each key. In the Set-ItemProperty command, the path is the value of the PSPath property of the registry key. (This is a pr operty of the Microsoft .NET Framework object that represents the registry key; it is not a registry entry.) The command uses the ToUpper() method of the RemotePath value, which is a string (REG_SZ). Because Set-ItemProperty is changing the property of each key, the ForEach- Object cmdlet is required to access the property. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113300 Format-Custom NAME Format-Custom SYNOPSIS Uses a customized view to format the output. SYNTAX Format-Custom [[-Property] <Object[]>] [-Depth <int>] [-DisplayError] [-Exp and <string>] [-Force] [-GroupBy <Object>] [-InputObject <psobject>] [-Show Error] [-View <string>] [<CommonParameters>] DESCRIPTION The Format-Custom cmdlet formats the output of a command as defined in an a lternate view. Format-Custom is designed to display views that are not just tables or just lists. You can use the views defined in the *format.PS1XML files in the Windows PowerShell directory, or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to add them to Wi ndows PowerShell. PARAMETERS -Depth <int> Specifies the number of columns in the display. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DisplayError [<SwitchParameter>] Displays errors at the command line. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Expand <string> Formats the collection object, as well as the objects in the collection . This parameter is designed to format objects that support the ICollec tion (System.Collections) interface. The default value is EnumOnly. Valid values are: -- EnumOnly: Displays the properties of the objects in the collection. -- CoreOnly: Displays the properties of the collection object. -- Both: Displays the properties of the collection object and the prope rties of objects in the collection. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Directs the cmdlet to display all of the error information. Use with th e DisplayError or ShowError parameters. By default, when an error objec t is written to the error or display streams, only some of the error in formation is displayed. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -GroupBy <Object> Formats the output in groups based on a shared property or value. Enter an expression or a property of the output. The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are: -- Name (or Label) <string> -- Expression <string> or <script block> -- FormatString <string> Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be formatted. Enter a variable that contains t he objects or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Property <Object[]> Specifies the object properties that appear in the display and the orde r in which they appear. Wildcards are permitted. If you omit this parameter, the properties that appear in the display d epend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command. The value of the Property parameter can be a new calculated property. T o create a calculated property, use a hash table. Valid keys are: -- Expression <string> or <script block> -- Depth <int32> Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -ShowError [<SwitchParameter>] Sends errors through the pipeline. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -View <string> Specifies the name of an alternate format or "view." If you omit this p arameter, Format-Custom uses a default custom view. You cannot use the Property and View parameters in the same command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Format-Custom OUTPUTS Microsoft.PowerShell.Commands.Internal.Format Format-Custom returns the format objects that represent the display. NOTES Format-Custom is designed to display views that are not just tables or just lists. To display an alternate table view, use Format-Table. To di splay an alternate list view, use Format-List. You can also refer to Format-Custom by its built-in alias, "fc". For mo re information, see about_Aliases. The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-command start-transcript | format-custom -view MyView Description ----------- This command formats information about the Start-Transcript cmdlet in the f ormat defined by the MyView view, a custom view created by the user. To run this command successfully, you must first create a new PS1XML file, define the MyView view, and then use the Update-FormatData command to add the PS1 XML file to Windows PowerShell. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-process Winlogon | format-custom Description ----------- This command formats information about the Winlogon process in an alternate customized view. Because the command does not use the View parameter, Form at-Custom uses a default custom view to format the data. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113301 Format-List NAME Format-List SYNOPSIS Formats the output as a list of properties in which each property appears o n a new line. SYNTAX Format-List [[-Property] <Object[]>] [-DisplayError] [-Expand <string>] [-F orce] [-GroupBy <Object>] [-InputObject <psobject>] [-ShowError] [-View <st ring>] [<CommonParameters>] DESCRIPTION The Format-List cmdlet formats the output of a command as a list of propert ies in which each property is displayed on a separate line. You can use For mat-List to format and display all or selected properties of an object as a list (format-list *). Because more space is available for each item in a list than in a table, Wi ndows PowerShell displays more properties of the object in the list, and th e property values are less likely to be truncated. PARAMETERS -DisplayError [<SwitchParameter>] Displays errors at the command line. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Expand <string> Formats the collection object, as well as the objects in the collection . This parameter is designed to format objects that support the ICollec tion (System.Collections) interface. The default value is EnumOnly. Valid values are: -- EnumOnly: Displays the properties of the objects in the collection. -- CoreOnly: Displays the properties of the collection object. -- Both: Displays the properties of the collection object and the prope rties of objects in the collection. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Directs the cmdlet to display all of the error information. Use with th e DisplayError or ShowError parameters. By default, when an error objec t is written to the error or display streams, only some of the error in formation is displayed. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -GroupBy <Object> Formats the output in groups based on a shared property or value. Enter an expression or a property of the output. The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are: -- Name (or Label) <string> -- Expression <string> or <script block> -- FormatString <string> Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be formatted. Enter a variable that contains t he objects or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Property <Object[]> Specifies the object properties that appear in the display and the orde r in which they appear. Wildcards are permitted. If you omit this parameter, the properties that appear in the display d epend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command. The value of the Property parameter can be a new calculated property. T o create a calculated, property, use a hash table. Valid keys are: -- Name (or Label) <string> -- Expression <string> or <script block> -- FormatString <string> Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -ShowError [<SwitchParameter>] Sends errors through the pipeline. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -View <string> Specifies the name of an alternate list format or "view." You cannot us e the Property and View parameters in the same command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Format-List. OUTPUTS Microsoft.PowerShell.Commands.Internal.Format Format-List returns the format objects that represent the list. NOTES You can also refer to Format-List by its built-in alias, "FL". For more information, see about_Aliases. The format cmdlets, such as Format-List, arrange the data to be display ed but do not display it. The data is displayed by the output features of Windows PowerShell and by the cmdlets that contain the Out verb (the Out cmdlets), such as Out-Host, Out-File, and Out-Printer. If you do not use a format cmdlet, Windows PowerShell applies that defa ult format for each object that it displays. The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them. The View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Windo ws PowerShell directory, or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows PowerShell. The alternate view for the View parameter must use the list format; if not, the command fails. If the alternate view is a table, use Format-Ta ble. If the alternate view is neither a list nor a table, use Format-Cu stom. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-service | format-list Description ----------- This command formats information about services on the computer as a list. By default, the services are formatted as a table. The Get-Service cmdlet g ets objects representing the services on the computer. The pipeline operato r (|) passes the results through the pipeline to Format-List. Then, the For mat-List command formats the service information in a list and sends it to the default output cmdlet for display. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$a = get-childitem $pshome\*.ps1xml Description ----------- These commands display information about the PS1XML files in the Windows Po werShell directory as a list. The first command gets the objects representi ng the files and stores them in the $a variable. The second command uses Fo rmat-List to format information about objects stored in $a. This command us es the InputObject parameter to pass the variable to Format-List, which the n sends the formatted output to the default output cmdlet for display. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-process | format-list -property name, basepriority, priorityclass Description ----------- This command displays the name, base priority, and priority class of each p rocess on the computer. It uses the Get-Process cmdlet to get an object rep resenting each process. The pipeline operator (|) passes the process object s through the pipeline to Format-List. Format-List formats the processes as a list of the specified properties. The "Property" parameter name is optio nal, so you can omit it. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-process winlogon | format-list -property * Description ----------- This command displays all of the properties of the Winlogon process. It use s the Get-Process cmdlet to get an object representing the Winlogon process . The pipeline operator (|) passes the Winlogon process object through the pipeline to Format-List. The command uses the Property parameter to specify the properties and the * to indicate all properties. Because the name of t he Property parameter is optional, you can omit it and type the command as: "format-list *". Format-List automatically sends the results to the defaul t output cmdlet for display. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113302 Format-Table NAME Format-Table SYNOPSIS Formats the output as a table. SYNTAX Format-Table [[-Property] <Object[]>] [-AutoSize] [-DisplayError] [-Expand <string>] [-Force] [-GroupBy <Object>] [-HideTableHeaders] [-InputObject <p sobject>] [-ShowError] [-View <string>] [-Wrap] [<CommonParameters>] DESCRIPTION The Format-Table cmdlet formats the output of a command as a table with the selected properties of the object in each column. The object type determin es the default layout and properties that are displayed in each column, but you can use the Property parameter to select the properties that you want to see. You can also use a hash table to add calculated properties to an object bef ore displaying it and to specify the column headings in the table. To add a calculated property, use the Property or GroupBy parameters. PARAMETERS -AutoSize [<SwitchParameter>] Adjusts the column size and number of columns based on the width of the data. By default, the column size and number are determined by the vie w. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DisplayError [<SwitchParameter>] Displays errors at the command line. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Expand <string> Formats the collection object, as well as the objects in the collection . This parameter is designed to format objects that support the ICollec tion (System.Collections) interface. The default value is EnumOnly. Valid values are: -- EnumOnly: Displays the properties of the objects in the collection. -- CoreOnly: Displays the properties of the collection object. -- Both: Displays the properties of the collection object and the prope rties of objects in the collection. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Directs the cmdlet to display all of the error information. Use with th e DisplayError or ShowError parameters. By default, when an error objec t is written to the error or display streams, only some of the error in formation is displayed. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -GroupBy <Object> Arranges sorted output in separate tables based on a property value. Fo r example, you can use GroupBy to list services in separate tables base d on their status. Enter an expression or a property of the output. The output must be sor ted before you send it to Format-Table. The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are: -- Name (or Label) <string> -- Expression <string> or <script block> -- FormatString <string> Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -HideTableHeaders [<SwitchParameter>] Omits the column headings from the table. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be formatted. Enter a variable that contains t he objects, or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Property <Object[]> Specifies the object properties that appear in the display and the orde r in which they appear. Type one or more property names (separated by c ommas), or use a hash table to display a calculated property. Wildcards are permitted. If you omit this parameter, the properties that appear in the display d epend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command. The value of the Property parameter can be a new calculated property. T o create a calculated, property, use a hash table. Valid keys are: -- Name (or Label) <string> -- Expression <string> or <script block> -- FormatString <string> -- Width <int32> -- Alignment (value can be "Left", "Center", or "Right") Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -ShowError [<SwitchParameter>] Sends errors through the pipeline. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -View <string> Specifies the name of an alternate table format or "view." You cannot u se the Property and View parameters in the same command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Wrap [<SwitchParameter>] Displays text that exceeds the column width on the next line. By defaul t, text that exceeds the column width is truncated. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Format-Table. OUTPUTS Microsoft.PowerShell.Commands.Internal.Format Format-Table returns format objects that represent the table. NOTES You can also refer to Format-Table by its built-in alias, "FT". For mor e information, see about_Aliases. The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them. The View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Windo ws PowerShell directory or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows P owerShell. The alternate view for the View parameter must use table format; if it does not, the command fails. If the alternate view is a list, use Forma t-List. If the alternate view is neither a list nor a table, use Format -Custom. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-pssnapin | format-table -auto Description ----------- This command formats information about Windows PowerShell snap-ins in a tab le. By default, they are formatted in a list. The Get-PSSnapin cmdlets gets objects representing the snap-ins. The pipeline operator (|) passes the ob ject to the Format-Table command. Format-Table formats the objects in a tab le. The Autosize parameter adjusts the column widths to minimize truncation . -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-process | sort-object -property basepriority | format-table -grou pby basepriority -wrap Description ----------- This command displays the processes on the computer in groups with the same base priority. The Get-Process cmdlet gets objects representing each process on the comput er. The pipeline operator (|) passes the object to the Sort-Object cmdlet, which sorts the objects in order of their base priority. Another pipeline operator passes the results to the Format-Table command. T he GroupBy parameter arranges the data about the processes into groups base d on the value of their BasePriority property. The Wrap parameter ensures t hat data is not truncated. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-process | sort-object starttime | format-table -view starttime Description ----------- This command displays information about the processes on the computer in gr oup based on the start date of the process. It uses the Get-Process cmdlet to get objects representing the processes on the computer. The pipeline ope rator (|) sends the output of Get-Process to the Sort-Object cmdlet, which sorts it based on the StartTime property. Another pipeline operator sends t he sorted results to Format-Table. The View parameter is used to select the StartTime view that is defined in the DotNetTypes.format.ps1xml formatting file for System.Diagnostics.Proces s objects, such as those returned by Get-Process. This view converts the St artTime of the process to a short date and then groups the processes by sta rt date. The DotNetTypes.format.ps1xml formatting file also contains a Priority view for processes, and you can create your own format.ps1xml files with custom ized views. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-service | format-table -property Name, DependentServices Description ----------- This command displays all of the services on the computer in a table with t wo columns, Name and DependentServices. The command uses the Get-Service cm dlet to get all of the services on the computer. The pipeline operator (|) sends the results to the Format-Table cmdlet, which formats the output in a table. The Property parameter specifies the properties that appear in the table as columns. The name of the Property parameter is optional, so you ca n omit it ("format-table name, dependentservices"). Property and DependentServices are just two of the properties of service ob jects. To view all of the properties, type "get-service | get-member". -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-process notepad | format-table ProcessName, ` @{Label="TotalRunningTime"; Expression={(get-date) - $_.StartTime}} Description ----------- This command shows how to use a calculated property in a table. The command displays a table with the process name and total running time of all Notep ad processes on the local computer. The total running time is calculated by subtracting the start time of each process from the current time. The command uses the Get-Process cmdlet to get all processes named "Notepad " on the local computer. The pipeline operator (|) sends the results to For mat-Table, which displays a table with two columns: ProcessName, a standard property of processes, and TotalRunningTime, a calculated property. The TotalRunningTime property is specified by a hash table with two keys, L abel and Expression. The name of the property is assigned to the Label key. The calculation is assigned to the Expression key. The expression gets the StartTime property of each process object and subtracts it from the result of a Get-Date command, which gets the current date (and time). -------------------------- EXAMPLE 6 -------------------------- C:\PS>$processes = get-wmiobject -ComputerName Server01 win32_process -filt er "name='notepad.exe'" C:\PS> $processes | format-table ProcessName, @{ Label = "Total Running Ti me"; ` Expression={(get-date) - $_.ConvertToDateTime($_.CreationDate)}} Description ----------- These commands are similar to the previous command, except that these comma nds use the Get-WmiObject cmdlet and the Win32_Process class to display inf ormation about Notepad processes on a remote computer. The first command uses the Get-WmiObject cmdlet to get instances of the Win dows Management Instrumentation (WMI) Win32_Process class that describes al l of the processes on the Server01 computer that are named Notepad.exe. The command stores the process information in the $processes variable. The second command uses a pipeline operator (|) to send the process informa tion in the $processes variable to the Format-Table cmdlet, which displays the ProcessName of each process along with a new calculated property. The command assigns the name of the new calculated property, Total Running Time, to the Label key. The script block that is assigned to the Expression key calculates how long the process has been running by subtracting the cr eation date of the process from the current date. The Get-Date cmdlet gets the current date. The ConvertToDateTime method converts the CreationDate pr operty of the Win32_Process object from a WMI CIM_DATETIME object to a Micr osoft .NET Framework DateTime object that can be compared with the output o f Get-Date. Then, the converted creation date is subtracted from the curren t date. The result is the value of Total Running Time. The backtick characters (`) are line continuation characters. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113303 Format-List Format-Wide Format-Custom Format-Wide NAME Format-Wide SYNOPSIS Formats objects as a wide table that displays only one property of each obj ect. SYNTAX Format-Wide [[-Property] <Object>] [-AutoSize] [-Column <int>] [-DisplayErr or] [-Expand <string>] [-Force] [-GroupBy <Object>] [-InputObject <psobject >] [-ShowError] [-View <string>] [<CommonParameters>] DESCRIPTION The Format-Wide cmdlet formats objects as a wide table that displays only o ne property of each object. You can use the Property parameter to determine which property is displayed. PARAMETERS -AutoSize [<SwitchParameter>] Adjusts the column size and number of columns based on the width of the data. By default, the column size and number are determined by the vie w. You cannot use the AutoSize and Column parameters in the same comman d. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Column <int> Specifies the number of columns in the display. You cannot use the Auto Size and Column parameters in the same command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DisplayError [<SwitchParameter>] Displays errors at the command line. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Expand <string> Formats the collection object, as well as the objects in the collection . This parameter is designed to format objects that support the ICollec tion (System.Collections) interface. The default value is EnumOnly. Valid values are: -- EnumOnly: Displays the properties of the objects in the collection. -- CoreOnly: Displays the properties of the collection object. -- Both: Displays the properties of the collection object and the prope rties of objects in the collection. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Overrides restrictions that prevent the command from succeeding, just s o the changes do not compromise security. For example, Force will overr ide the read-only attribute or create directories to complete a file pa th, but it will not attempt to change file permissions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -GroupBy <Object> Formats the output in groups based on a shared property or value. Enter an expression or a property of the output. The value of the GroupBy parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are: -- Name (or Label) <string> -- Expression <string> or <script block> -- FormatString <string> Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be formatted. Enter a variable that contains t he objects, or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Property <Object> Specifies the object properties that appear in the display and the orde r in which they appear. Wildcards are permitted. If you omit this parameter, the properties that appear in the display d epend on the object being displayed. The parameter name ("Property") is optional. You cannot use the Property and View parameters in the same command. The value of the Property parameter can be a new calculated property. T o create a calculated, property, use a hash table. Valid keys are: -- Expression <string> or <script block> -- FormatString <string> Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -ShowError [<SwitchParameter>] Sends errors through the pipeline. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -View <string> Specifies the name of an alternate table format or "view." You cannot u se the Property and View parameters in the same command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Format-Wide. OUTPUTS Microsoft.PowerShell.Commands.Internal.Format Format-Wide returns format objects that represent the table. NOTES You can also refer to Format-Wide by its built-in alias, "fw". For more information, see about_Aliases. The GroupBy parameter assumes that the objects are sorted. Before using Format-Custom to group the objects, use Sort-Object to sort them. The -View parameter lets you specify an alternate format for the table. You can use the views defined in the *.format.PS1XML files in the Wind ows PowerShell directory or you can create your own views in new PS1XML files and use the Update-FormatData cmdlet to include them in Windows PowerShell. The alternate view for the View parameter must use table format; if it does not, the command fails. If the alternate view is a list, use Forma t-List. If the alternate view is neither a list nor a table, use Format -Custom. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-childitem | format-wide -column 3 Description ----------- This command displays the names of files in the current directory in three columns across the screen. The Get-ChildItem cmdlet gets objects representi ng each file in the directory. The pipeline operator (|) passes the file ob jects through the pipeline to Format-Wide, which formats them for output. T he Column parameter specifies the number of columns. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-childitem HKCU:\software\microsoft | format-wide -property pschil dname -autosize Description ----------- This command displays the names of registry keys in the HKEY_CURRENT_USER\S oftware\Microsoft key. The Get-ChildItem cmdlet gets objects representing t he keys. The path is specified as "HKCU:", one of the drives exposed by the Windows PowerShell Registry provider, followed by the key path. The pipeli ne operator (|) passes the registry key objects through the pipeline to For mat-Wide, which formats them for output. The Property parameter specifies t he name of the property, and the AutoSize parameter adjusts the columns for readability. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113304 Function PROVIDER NAME Function DRIVES Function: SYNOPSIS Provides access to the functions defined in Windows PowerShell. DESCRIPTION The Windows PowerShell Function provider lets you get, add, change, clear, and delete the functions and filters in Windows PowerShell. A function is a named block of code that performs an action. When you type the function name, the code in the function runs. A filter is a named block of code that establishes conditions for an action. You can type the name o f the filter in place of the condition, such as in a Where-Object command. In the Function: drive, functions are preceded by the label "Function" and filters are preceded by the label "Filter", but they operate properly when used in the correct context regardless of the label. The Function provider is a flat namespace that contains only the function a nd filter objects. Neither functions nor filters have child items. Each function is an instance of the System.Management.Automation.FunctionIn fo class. Each filter is an instance of the System.Management.Automation.Fi lterInfo class. The examples in this section show how to manage functions, but the same met hods can be used with filters. The Function provider exposes its data store in the Function: drive. To wor k with functions, you can change your location to the Function: drive ("set -location function:"). Or, you can work from another Windows PowerShell dri ve. To reference a function from another location, use the drive name (Func tion:) in the path. The Function provider supports all of the cmdlets whose names contain the I tem noun (the Item cmdlets), except for Invoke-Item. And, it supports the G et-Content and Set-Content cmdlets. However, it does not support the cmdlet s whose names contain the ItemProperty noun (the ItemProperty cmdlets), and it does not support the Filter parameter in any cmdlet. All changes to the functions affect the current console only. To save the c hanges, add the function to the Windows PowerShell profile, or use Export-C onsole to save the current console. CAPABILITIES TASKS TASK: Getting to the Function: Drive -------------------------- EXAMPLE 1 -------------------------- Changes the current location to the Function: drive. You can use this c ommand from any drive in Windows PowerShell. To return to a file system drive, type the drive name. For example, type "set-location c:". set-location function: TASK: Getting Functions -------------------------- EXAMPLE 1 -------------------------- This command gets the list of all the functions in the current session. You can use this command from any Windows PowerShell drive. get-childitem -path function: -------------------------- EXAMPLE 2 -------------------------- This command gets the "man" function from the Function: drive. It uses the Get-Item cmdlet to get the function. The pipeline operator (|) send s the result to Format-Table. The Wrap parameter directs text that does not fit on the line onto the next line. The Autosize parameter resizes the table columns to accommod ate the text. get-item -path man | format-table -wrap -autosize If you are in a different drive, add the drive name (Function:) to the path. -------------------------- EXAMPLE 3 -------------------------- These commands both get the function named "c:". The first command can be used in any drive. The second command is used in the Function: drive . Because the name ends in a colon, which is the syntax for a drive, you must qualify the path with the drive name. Within the Function: drive, you can use either format. In the second command, the dot (.) represent s the current location. c:\PS> get-item -path function:c: PS Function> get-item -path .\c: TASK: Creating a Function -------------------------- EXAMPLE 1 -------------------------- This command uses the New-Item cmdlet to create a function called "HKLM :". The expression in braces is the script block that is represented by the function name. new-item -path function:hklm: -value {set-location hklm:} You can also create a function by typing it at the Windows PowerShell c ommand line. For example, tpe "function:hklm: {set-location hklm:}". If you are in the Function: drive, you can omit the drive name. Because you cannot specify the "Filter" label in New-Item, filters are labeled as functions, but they operate properly with any label. To crea te a filter with the "Filter" label, type the filter at the command lin e. For example, type "filter:Running {$_.Status -eq "Running"}". -------------------------- EXAMPLE 2 -------------------------- This command uses the New-Item cmdlet to create a function called Csrss . It uses the Options dynamic parameter to specify a value of ReadOnly for the Options property of the function. new-item -path function: -name csrss -options readonly -value {get-proc ess csrss} This command works from any location. If you are in the Function: drive , you can use a dot (.) to specify the path. The dot represents the cur rent location. TASK: Deleting a Function -------------------------- EXAMPLE 1 -------------------------- This command deletes the "hklm:" function from the current session. remove-item function:hklm: -------------------------- EXAMPLE 2 -------------------------- This command deletes all the functions from the current session except for the functions whose Options property has a value of Constant. Witho ut the Force parameter, the command does not delete functions whose Opt ions property has a value of ReadOnly. remove-item function:* -force When you delete all the functions, the command prompt changes because t he prompt function, which defines the content of the command prompt, is deleted. TASK: Displaying the Properties and Methods of Functions -------------------------- EXAMPLE 1 -------------------------- This command uses the Get-Item cmdlet to get all the functions. The pip eline operator sends the results to the Get-Member cmdlet, which displa ys the methods and the properties of the object. get-item -path function:* | get-member When you pipe a collection of objects (such as the collection of functi ons in the Function: drive) to Get-Member, Get-Member evaluates each ob ject in the collection separately and returns information about each ob ject type that it finds. If all of the objects are of the same type, it returns information about the single object type. In this case, all of the functions are FunctionInfo objects. To get information about the collection of FunctionInfo objects, use th e InputObject parameter of Get-Member. For example, type "get-member -I nputObject (get-item function:*)". When you use the InputObject paramet er, Get-Member evaluates the collection, not the objects in the collect ion. -------------------------- EXAMPLE 2 -------------------------- This command lists the values of the properties of the "prompt" functio n. It uses the Get-Item cmdlet to get an object that represents the "pr ompt" function. The pipeline operator (|) sends the results to the Form at-List command. The Format-List command uses the Property parameter wi th a wildcard character (*) to format and to display the values of all of the properties of the "prompt" function. get-item function:prompt | format-list -property * TASK: Changing the Properties of a Function -------------------------- EXAMPLE 1 -------------------------- You can use the Set-Item cmdlet with the Options dynamic parameter to c hange the value of the Options property of a function. This command sets the AllScope and ReadOnly options for the "prompt" fu nction. This command uses the Options dynamic parameter of the Set-Item cmdlet. The Options parameter is available in Set-Item only when you u se it with the Alias or Function provider. set-item -path function:prompt -options "AllScope,ReadOnly" -------------------------- EXAMPLE 2 -------------------------- This command uses the Set-Item cmdlet to change the "prompt" function s o that it displays the time before the path. set-item -path function:prompt -value {'PS '+ $(Get-Date -format t) + " " + $(Get-Location) + '> '} The change affects both the Definition and ScriptBlock properties of th e FunctionInfo object. To see the effect of the change, type "get-item -path function:prompt | format-list -property *". -------------------------- EXAMPLE 3 -------------------------- This command uses the Rename-Item cmdlet to change the name of the "hel p" function to "gh". rename-item -path function:help -newname gh TASK: Copying a Function -------------------------- EXAMPLE 1 -------------------------- This command copies the "prompt" function to "oldPrompt", effectively c reating a new name for the script block that is associated with the pro mpt function. You can use this to save the original prompt function if you plan to change it. The Options property of the new function has a value of None. To change the value of the Options property, use Set-Item. copy-item -path function:prompt -destination function:oldPrompt DYNAMIC PARAMETERS -Options <System.Management.Automation.ScopedItemOptions> Determines the value of the Options property of a function. None No options. "None" is the default. Constant The function cannot be deleted, and its properties cannot be ch anged. Constant is available only when you are creating a funct ion. You cannot change the option of an existing function to Co nstant. Private The function is visible only in the current scope (not in child scopes). ReadOnly The properties of the function cannot be changed except by usin g the Force parameter. You can use Remove-Item to delete the fu nction. AllScope The function is copied to any new scopes that are created. Cmdlets Supported: New-Item, Set-Item NOTES RELATED LINKS about_Functions about_Providers Get-Acl NAME Get-Acl SYNOPSIS Gets the security descriptor for a resource, such as a file or registry key . SYNTAX Get-Acl [[-Path] <string[]>] [-Audit] [-Exclude <string[]>] [-Filter <strin g>] [-Include <string[]>] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Get-Acl cmdlet gets objects that represent the security descriptor of a file or resource. The security descriptor contains the access control list s (ACLs) of the resource. The ACL specifies the permissions that users and user groups have to access the resource. PARAMETERS -Audit [<SwitchParameter>] Gets the audit data for the security descriptor from the system access control list (SACL). Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Retrieves only the specified items. The value of this parameter qualifi es the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to a resource. Get-Acl gets the security descriptor of the resource indicated by the path. Wildcards are permitted. If you omit the Path parameter, Get-Acl gets the security descriptor of the cu rrent directory. The parameter name ("Path") is optional. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Get-Acl. OUTPUTS System.Security.AccessControl Get-Acl returns an object that represents the ACLs that it gets. The ob ject type depends upon the ACL type. NOTES By default, Get-Acl displays the Windows PowerShell path to the resourc e (<provider>::<resource-path>), the owner of the resource, and "Access ", a list (array) of the access control entries in the discretionary ac cess control list (DACL) for the resource. The DACL list is controlled by the resource owner. When you format the result as a list, ("get-acl | format-list"), in add ition to the path, owner, and access list, Windows PowerShell displays the following fields: -- Group: The security group of the owner. -- Audit: A list (array) of entries in the system access control list (SACL). The SACL specifies the types of access attempts for which Windo ws generates audit records. -- Sddl: The security descriptor of the resource displayed in a single text string in Security Descriptor Definition Language format. Windows PowerShell uses the GetSddlForm method of security descriptors to retri eve this data. Because Get-Acl is supported by the file system and registry providers, you can use Get-Acl to view the ACL of file system objects, such as fi les and directories, and registry objects, such as registry keys and en tries. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-acl C:\windows Description ----------- This command gets the security descriptor of the C:Windows directory. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-acl C:\Windows\k*.log | format-list -property PSPath, Sddl Description ----------- This command gets the Windows PowerShell path and SDDL for all of the .log files in the C:\Windows directory whose names begin with "k." The command uses Get-Acl to get objects representing the security descripto rs of each log file. It uses a pipeline operator (|) to send the results to the Format-List cmdlet. The command uses the Property parameter of Format- List to display only the PsPath and SDDL properties of each security descri ptor object. Lists are often used in Windows PowerShell, because long values appear trun cated in tables. The SDDL values are valuable to system administrators, because they are sim ple text strings that contain all of the information in the security descri ptor. As such, they are easy to pass and store, and they can be parsed when needed. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-ACL c:/windows/k*.log -Audit | foreach-object { $_.Audit.Count } Description ----------- This command gets the security descriptors of the .log files in the C:\Wind ows directory whose names begin with "k." It uses the Audit parameter to re trieve the audit records from the SACL in the security descriptor. Then it uses the For-EachObject parameter to count the number of audit records asso ciated with each file. The result is a list of numbers representing the num ber of audit records for each log file. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-acl -path hklm:\system\currentcontrolset\control | format-list Description ----------- This command uses Get-Acl to get the security descriptor of the Control sub key (HKLM\SYSTEM\CurrentControlSet\Control) of the registry. The Path parameter specifies the Control subkey. The pipeline operator (|) passes the security descriptor that Get-Acl retrieves to the Format-List co mmand, which formats the properties of the security descriptor as a list so that they are easy to read. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113305 Set-Acl Get-Alias NAME Get-Alias SYNOPSIS Gets the aliases for the current session. SYNTAX Get-Alias [[-Name] <string[]>] [-Exclude <string[]>] [-Scope <string>] [ mmonParameters>] Get-Alias [-Definition <string[]>] [-Exclude <string[]>] [-Scope <string>] [<CommonParameters>] DESCRIPTION The Get-Alias cmdlet gets the aliases (alternate names for commands and exe cutable files) in the current session. This includes built-in aliases, alia ses that you have set or imported, and aliases that you have added to your Windows PowerShell profile. By default, Get-Alias takes an alias and returns the command name. When you use the Definition parameter, Get-Alias takes a command name and returns i ts aliases. PARAMETERS -Definition <string[]> Gets the aliases for the specified item. Enter the name of a cmdlet, fu nction, script, file, or executable file. This parameter is called Definition, because it searches for the item n ame in the Definition property of the alias object. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Na me and Definition parameters. Enter a name, a definition, or a pattern, such as "s*". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the aliases to retrieve. Wildcards are permitted. By default, Get-Alias retrieves all aliases defined for the current session. The p arameter name ("Name") is optional. You can also pipe alias names to Ge t-Alias. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Scope <string> Gets only the aliases in the specified scope. Valid values are "Global" , "Local", or "Script", or a number relative to the current scope (0 th rough the number of scopes, where 0 is the current scope and 1 is its p arent). "Local" is the default. For more information, see about_Scopes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe alias names to Get-Alias. OUTPUTS System.Management.Automation.AliasInfo Get-Alias returns an object that represents each alias. NOTES An alias is an alternate name or nickname for a cmdlet, function, or an executable file. To run the cmdlet, function, or executable, you can u se its full name or any alias. For more information, see about_Aliases. To create a new alias, use Set-Alias or New-Alias. To delete an alias, use Remove-Item. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-alias Description ----------- This command gets all aliases in the current session. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-alias -name g*, s* -exclude get-* Description ----------- This command gets all aliases that begin with "g" or "s", except for aliase s that begin with "get-". -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-alias -definition Get-ChildItem Description ----------- This command gets the aliases for the Get-ChildItem cmdlet. By default, the Get-Alias cmdlet gets the item name when you know the alias . The Definition parameter gets the alias when you know the item name. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-alias | where-object {$_.Options -match "ReadOnly"} Description ----------- This command retrieves all aliases in which the value of the Options proper ty is ReadOnly. This command provides a quick way to find the aliases that are built into Windows PowerShell, because they have the ReadOnly option. Options is just one property of the AliasInfo objects that Get-Alias gets. To find all properties and methods of AliasInfo objects, type "get-alias | get-member". -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-alias -definition "*-pssession" -exclude e* -scope global Description ----------- This example gets aliases for commands that have names that end in "-pssess ion", except for those that begin with "e". The command uses the Scope parameter to apply the command in the global sco pe. This is useful in scripts when you want to get the aliases in the sessi on. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113306 about_Aliases Set-Alias New-Alias Export-Alias Import-Alias Alias Provider Get-AuthenticodeSignature NAME Get-AuthenticodeSignature SYNOPSIS Gets information about the Authenticode signature in a file. SYNTAX Get-AuthenticodeSignature [-FilePath] <string[]> [<CommonParameters>] DESCRIPTION The Get-AuthenticodeSignature cmdlet gets information about the Authenticod e signature in a file. If the file is not signed, the information is retrie ved, but the fields are blank. PARAMETERS -FilePath <string[]> Specifies the path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("FilePath") i s optional. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a file path to Get-AuthenticodeSign ature. OUTPUTS System.Management.Automation.Signature Get-AuthenticodeSignature returns a signature object for each signature that it gets. NOTES For information about Authenticode signatures in Windows PowerShell, se e about_Signing. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-AuthenticodeSignature -filepath C:\Test\NewScript.ps1 Description ----------- This command gets information about the Authenticode signature in the NewSc ript.ps1 file. It uses the FilePath parameter to specify the file. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-authenticodesignature test.ps1, test1.ps1, sign-file.ps1, makexml .ps1 Description ----------- This command gets information about the Authenticode signature in the four files listed at the command line. In this command, the name of the FilePath parameter, which is optional, is omitted. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-childitem $pshome\*.* | foreach-object {Get-AuthenticodeSignature $_} | where {$_.status -eq "Valid"} Description ----------- This command lists all of the files in the $pshome directory that have a va lid Authenticode signature. The $pshome automatic variable contains the pat h to the Windows PowerShell installation directory. The command uses the Get-ChildItem cmdlet to get the files in the $pshome d irectory. It uses a pattern of *.* to exclude directories (although it also excludes files without a dot in the filename). The command uses a pipeline operator (|) to send the files in $pshome to th e Foreach-Object cmdlet, where Get-AuthenticodeSignature is called for each file. The results of the Get-AuthenticodeSignature command are sent to a Where-Ob ject command that selects only the signature objects with a status of "Vali d". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113307 about_Signing about_Execution_Policies Set-AuthenticodeSignature Get-ExecutionPolicy Set-ExecutionPolicy Get-ChildItem NAME Get-ChildItem SYNOPSIS Gets the items and child items in one or more specified locations. SYNTAX Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Exclude <string[] >] [-Force] [-Include <string[]>] [-Name] [-Recurse] [-UseTransaction] [<Co mmonParameters>] Get-ChildItem [-LiteralPath] <string[]> [[-Filter] <string>] [-Exclude <str ing[]>] [-Force] [-Include <string[]>] [-Name] [-Recurse] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Get-ChildItem cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child items. You can use the Recurse parameter to get items in all child containers. A location can be a file system location, such as a directory, or a locatio n exposed by another provider, such as a registry hive or a certificate sto re. PARAMETERS -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to get items that cannot otherwise not be accessed by the user, such as hidden or system files. Implementation varies from p rovider to provider. For more information, see about_Providers. Even us ing the Force parameter, the cmdlet cannot override security restrictio ns. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Retrieves only the specified items. The value of this parameter qualifi es the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcards are permitted. The Include parameter is effective only when the command includes the R ecurse parameter or the path leads to the contents of a directory, such as C:\Windows\*, where the wildcard character specifies the contents o f the C:\Windows directory. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to one or more locations. Unlike Path, the value of Li teralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in si ngle quotation marks. Single quotation marks tell Windows PowerShell no t to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name [<SwitchParameter>] Retrieves only the names of the items in the locations. If you pipe the output of this command to another command, only the item names are sen t. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Recurse [<SwitchParameter>] Gets the items in the specified locations and in all child items of the locations. Recurse works only when the path points to a container that has child i tems, such as C:\Windows or C:\Windows\*, and not when it points to ite ms that do not have child items, such as C:\Windows\*.exe. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Get-ChildItem. OUTPUTS Object. The type of object that Get-ChildItem returns is determined by the prov ider with which it is used. NOTES You can also refer to Get-ChildItem by its built-in aliases, "ls", "dir ", and "gci". For more information, see about_Aliases. Get-ChildItem does not get hidden items by default. To get hidden items , use -Force. The Get-ChildItem cmdlet is designed to work with the data exposed by a ny provider. To list the providers available in your session, type "Get -PsProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-childitem Description ----------- This command gets the child items in the current location. If the location is a file system directory, it gets the files and sub-directories in the cu rrent directory. If the item does not have child items, this command return s to the command prompt without displaying anything. The default display lists the mode (attributes), last write time, file size (length), and the name of the file. The valid values for mode are d (direc tory), a (archive), r (read-only), h (hidden), and s (system). -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-childitem . -include *.txt -recurse -force Description ----------- This command retrieves all of the .txt files in the current directory and i ts subdirectories. The dot (.) represents the current directory and the Inc lude parameter specifies the file name extension. The Recurse parameter dir ects Windows PowerShell to retrieve objects recursively, and it indicates t hat the subject of the command is the specified directory and its contents. The force parameter adds hidden files to the display. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-childitem c:\windows\logs\* -include *.txt -exclude A* Description ----------- This command lists the .txt files in the Logs subdirectory, except for thos e whose names start with the letter A. It uses the wildcard character (*) t o indicate the contents of the Logs subdirectory, not the directory contain er. Because the command does not include the Recurse parameter, Get-ChildIt em does not include the content of directory automatically; you need to spe cify it. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-childitem registry::hklm\software Description ----------- This command retrieves all of the registry keys in the HKEY_LOCAL_MACHINE\S OFTWARE key in the registry of the local computer. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-childitem -name Description ----------- This command retrieves only the names of items in the current directory. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-childitem cert:\. -recurse -codesigningcert Description ----------- This command gets all of the certificates in the certificate store that hav e code-signing authority. The command uses the Get-ChildItem cmdlet. The path specifies the Cert: dri ve exposed by the Windows PowerShell certificate provider. The backslash (\ ) symbol specifies a subdirectory of the certificate store and the dot (.) represents the current directory, which would be the root directory of the certificate store. The Recurse parameter specifies a recursive search. The CodeSigningCertificate parameter is a dynamic parameter that gets only certificates with code-signing authority. For more information, type "get-h elp certificate". -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-childitem * -include *.exe Description ----------- This command retrieves all of the items in the current directory with a ".e xe" file name extension. The wildcard character (*) represents the contents of the current directory (not the container). When using the Include param eter without the Recurse parameter, the path must point to contents, not a container. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113308 about_Providers Get-Item Get-Alias Get-Location Get-Process Get-Command NAME Get-Command SYNOPSIS Gets basic information about cmdlets and other elements of Windows PowerShe ll commands. SYNTAX Get-Command [[-Name] <string[]>] [-CommandType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | All}] [[-ArgumentList] <O bject[]>] [-Module <string[]>] [-Syntax] [-TotalCount <int>] [<CommonParame ters>] Get-Command [-Noun <string[]>] [-Verb <string[]>] [[-ArgumentList] <Object[ ]>] [-Module <string[]>] [-Syntax] [-TotalCount <int>] [<CommonParameters>] DESCRIPTION The Get-Command cmdlet gets basic information about cmdlets and other eleme nts of Windows PowerShell commands in the session, such as aliases, functio ns, filters, scripts, and applications. Get-Command gets its data directly from the code of a cmdlet, function, scr ipt, or alias, unlike Get-Help, which gets its information from help topic files. Without parameters, "Get-Command" gets all of the cmdlets and functions in the current session. "Get-Command *" gets all Windows PowerShell elements a nd all of the non-Windows-PowerShell files in the Path environment variable ($env:path). It groups the files in the "Application" command type. You can use the Module parameter of Get-Command to find the commands that w ere added to the session by adding a Windows PowerShell snap-in or importin g a module. PARAMETERS -ArgumentList <Object[]> Gets information about a cmdlet or function when it is used with the sp ecified parameters ("arguments"), such as a path. The alias for Argum entList is Args. To detect parameters that are added to a cmdlet when it is used with a particular provider, set the value of ArgumentList to a path in the pro vider drive, such as "HKML\Software" or "cert:\my". Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -CommandType <CommandTypes> Gets only the specified types of commands. Use "CommandType" or its ali as, "Type". By default, Get-Command gets cmdlets and functions. Valid values are: -- Alias: All Windows PowerShell aliases in the current session. -- All: All command types. It is the equivalent of "get-command *". -- Application: All non-Windows-PowerShell files in paths listed in the Path environment variable ($env:path), including .txt, .exe, and .dll files. -- Cmdlet: The cmdlets in the current session. "Cmdlet" is the default. -- ExternalScript: All .ps1 files in the paths listed in the Path envir onment variable ($env:path). -- Filter and Function: All Windows PowerShell functions. -- Script: Script blocks in the current session. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Module <string[]> Gets the commands that came from the specified modules or snap-ins. Ent er the names of modules or snap-ins, or enter snap-in or module objects . You can refer to this parameter by its name, Module, or by its alias, P SSnapin. The parameter name that you choose has no effect on the comman d or its output. This parameter takes string values, but you can also supply a PSModuleI nfo or PSSnapinInfo object, such as the objects that Get-Module, Get-PS Snapin, and Import-PSSession return. Required? false Position? named Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Gets information only about the cmdlets or command elements with the sp ecified name. <String> represents all or part of the name of the cmdlet or command element. Wildcards are permitted. To list commands with the same name in execution order, type the comman d name without wildcard characters. For more information, see the Notes section. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Noun <string[]> Gets cmdlets and functions with names that include the specified noun. <String> represents one or more nouns or noun patterns, such as "proces s" or "*item*". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Syntax [<SwitchParameter>] Gets only specified data about the command element. * For aliases, retrieves the standard name. * For cmdlets, retrieves the syntax. * For functions and filters, retrieves the function definiti on. * For scripts and applications (files), retrieves the path a nd filename. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -TotalCount <int> Gets only the specified number of command elements. You can use this pa rameter to limit the output of a command. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Verb <string[]> Gets information about cmdlets and functions with names that include th e specified verb. <String> represents one or more verbs or verb pattern s, such as "remove" or *et". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a "Name", "Command", and "Verb" noun-property specified, o r a string object to Get-Command. OUTPUTS Object The type of object returned depends on the type of command element retr ieved. For example, Get-Command on a cmdlet retrieves a CmdletInfo obje ct, while Get-Command on a DLL retrieves an ApplicationInfo object. NOTES Without parameters, "Get-Command" gets information about the Windows Po werShell cmdlets and functions. Use the parameters to qualify the eleme nts retrieved. Unlike Get-Help, which displays the contents of XML-based help topic fi les, Get-Command gets its cmdlet information directly from the cmdlet c ode in the system. Get-Command returns the commands in alphabetical order. When the sessio n contains more than one command with the same name, Get-Command return s the commands in execution order. The first command that is listed is the command that runs when you type the command name without qualifica tion. For more information, see about_Command_Precedence. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-command Description ----------- This command gets information about all of the Windows PowerShell cmdlets a nd functions. The default display lists the command type ("Cmdlet" or "Function" or "Filt er"), the name of the cmdlet or function, and the syntax or function defini tion. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-command -verb set | format-list Description ----------- This command gets information about all of the cmdlets and functions with t he verb "set", and it displays some of that information in a list. The list format includes fields that are omitted from the table display, in cluding the complete syntax. To display all fields (all properties of the o bject), type "get-command -verb set | format-list *". -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-command -type cmdlet | sort-object noun | format-table -group nou n Description ----------- This command retrieves all of the cmdlets, sorts them alphabetically by the noun in the cmdlet name, and then displays them in noun-based groups. This display can help you find the cmdlets for a task. By default, Get-Command displays items in the order in which the system dis covers them, which is also the order in which they are selected to run when a run command is ambiguous. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-command -module Microsoft.PowerShell.Security, TestModule Description ----------- This command gets the commands in the Microsoft.PowerShell.Security snap-in and the Test-Module module. The Module parameter gets commands that were added by importing modules or adding Windows PowerShell snap-ins. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-command get-childitem -args cert: -syntax Description ----------- This command retrieves information about the Get-ChildItem cmdlet when Get- ChildItem is used with the Windows PowerShell Certificate provider. When you compare the syntax displayed in the output with the syntax that is displayed when you omit the Args (ArgumentList) parameter, you'll see that the Certificate provider dynamically adds a parameter, CodeSigningCert, to the Get-ChildItem cmdlet. -------------------------- EXAMPLE 6 -------------------------- C:\PS>(get-command get-childitem -ArgumentList cert:).parametersets[0].para meters | where-object { $_.IsDynamic } Description ----------- This command retrieves only parameters that are added to the Get-ChildItem cmdlet dynamically when it is used with the Windows PowerShell Certificate provider. This is an alternative to the method used in the previous example . In this command, the "get-command get-childitem -ArgumentList cert:" is pro cessed first. It requests information from Get-Command about the Get-ChildI tem cmdlet when it is used with the Certificate provider. The ".parameterse ts[0]" selects the first parameter set (set 0) of "get-childitem -argumentL ist cert:" and ".parameters" selects the parameters in that parameter set. The resulting parameters are piped to the Where-Object cmdlet to test each parameter ("$_.") by using the IsDynamic property. To find the properties o f the objects in a command, use Get-Member. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-command * Description ----------- This command gets information about the Windows PowerShell cmdlets, functio ns, filters, scripts, and aliases in the current console. It also gets information about all of the files in the paths of the Path en vironment variable ($env:path). It returns an ApplicationInfo object (Syste m.Management.Automation.ApplicationInfo) for each file, not a FileInfo obje ct (System.IO.FileInfo). -------------------------- EXAMPLE 8 -------------------------- C:\PS>get-command | where-object {$_.definition -like "*first*"} CommandType Name Definition ----------- ---- --------- Cmdlet Select-Object Select-Object [[-Property] Description ----------- This command finds a cmdlet or function based on the name of one of its par ameters. You can use this command to identify a cmdlet or function when all that you can recall is the name of one of its parameters. In this case, you recall that one of the cmdlets or functions has a First p arameter that gets the first "n" objects in a list, but you cannot remember which cmdlet it is. This command uses the Get-Command cmdlet to get a CmdletInfo object represe nting each of the cmdlets and functions in the session. The CmdletInfo obje ct has a Definition property that contains the syntax of the cmdlet or func tion, which includes its parameters. The command uses a pipeline operator (|) to pass the CmdletInfo object to t he Where-Object cmdlet, which examines the definition (syntax) of each obje ct ($_) for a value that includes "first". The result shows that the First parameter belongs to the Select-Object cmdl et. -------------------------- EXAMPLE 9 -------------------------- C:\PS>get-command dir | format-list Name : dir CommandType : Alias Definition : Get-ChildItem ReferencedCommand : Get-ChildItem ResolvedCommand : Get-ChildItem Description ----------- This example shows how to use the Get-Command cmdlet with an alias. Althoug h it is typically used on cmdlets, Get-Command also displays information ab out the code in scripts, functions, aliases, and executable files. This command displays the "dir" alias in the current console. The command p ipes the result to the Format-List cmdlets. -------------------------- EXAMPLE 10 -------------------------- C:\PS>get-command notepad CommandType Name Definition ----------- ---- ---------- Application notepad.exe C:\WINDOWS\system32\notepad.exe Application NOTEPAD.EXE C:\WINDOWS\NOTEPAD.EXE Description ----------- This example shows how to use Get-Command to determine which command Window s PowerShell runs when it has access to multiple commands with the same nam e. When you use the Name parameter without wildcard characters, Get-Command lists the commands with that name in execution precedence order. This command shows which Notepad program Windows PowerShell runs when you t ype "Notepad" without a fully qualified path. The command uses the Name par ameter without wildcard characters. The sample output shows the Notepad commands in the current console. It ind icates that Windows PowerShell will run the instance of Notepad.exe in the C:\Windows\System32 directory. -------------------------- EXAMPLE 11 -------------------------- C:\PS>(get-command get-date).pssnapin C:\PS> (get-command remove-gpo).module Description ----------- These commands show how to find the snap-in or module from which a particul ar cmdlet originated. The first command uses the PSSnapin property of the CmdletInfo object to fi nd the snap-in that added the Get-Date cmdlet. The second command uses the Module property of the CmdletInfo object to fin d the module that added the Remove-GPO cmdlet. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113309 about_Command_Precedence Get-Help Get-PSDrive Get-Member Import-PSSession Export-PSSession Get-ComputerRestorePoint NAME Get-ComputerRestorePoint SYNOPSIS Gets the restore points on the local computer. SYNTAX Get-ComputerRestorePoint [[-RestorePoint] <Int32[]>] [<CommonParameters>] Get-ComputerRestorePoint -LastStatus [<CommonParameters>] DESCRIPTION The Get-ComputerRestorePoint cmdlet gets the restore points on the local co mputer. This cmdlet can also display the status of the most recent attempt to restore the computer. You can use the information returned by Get-ComputerRestorePoint to select a restore point, and you can use the sequence number to identify a restore point for the Restore-Computer cmdlet. PARAMETERS -LastStatus [<SwitchParameter>] Gets the status of the most recent system restore operation. Required? true Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -RestorePoint <Int32[]> Gets the restore points with the specified sequence numbers. Enter the sequence numbers of one or more restore points. By default, Get-Compute rRestorePoint gets all restore points on the local computer. Required? false Position? 1 Default value All restore points Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS System.Management.ManagementObject#root\default\SystemRestore or String. Get-ComputerRestore returns a SystemRestore object, which is an instanc e of the WMI SystemRestore class. When you use the LastStatus parameter , this cmdlet returns a string. NOTES To run a Get-ComputerRestorePoint command on Windows Vista and later ve rsions of Windows, open Windows PowerShell with the "Run as administrat or" option. This cmdlet uses the Windows Management Instrumentation (WMI) SystemRes tore class. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-computerrestorepoint Description ----------- This command gets all of the restore points on the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-computerrestorepoint -restorepoint 232, 240, 245 Description ----------- This command gets the restore points with sequence numbers 232, 240, and 24 5. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-computerrestorepoint -laststatus The last restore failed. Description ----------- This command displays the status of the most recent system restore operatio n on the local computer. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-computerrestorepoint | format-table SequenceNumber, @{Label="Date "; Expression={$_.ConvertToDateTime($_.CreationTime)}}, Description -auto SequenceNumber Date Description -------------- ---- ----------- 253 8/5/2008 3:19:20 PM Windows Update 254 8/6/2008 1:53:24 AM Windows Update 255 8/7/2008 12:00:04 AM Scheduled Checkpoint ... Description ----------- This command displays the restore points in a table for easy reading. The Format-Table command includes a calculated property that uses the Conve rtToDateTime method to convert the value of the CreationTime property from WMI format to a DateTime object. -------------------------- EXAMPLE 5 -------------------------- C:\PS>((get-computerrestorepoint)[-1]).sequencenumber Description ----------- This command gets the sequence number of the most recently created restore point on the computer. The command uses the -1 index to get the last item in the array that Get-Co mputerRestorePoint returns. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135215 Enable-ComputerRestore Disable-ComputerRestore Restore-Computer Restart-Computer Get-Content NAME Get-Content SYNOPSIS Gets the content of the item at the specified location. SYNTAX Get-Content [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclud e <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-ReadCount <Int64>] [-TotalCount <Int64>] [-UseTransaction] [<CommonParameters>] Get-Content [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <stri ng[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-ReadCount <Int64 >] [-TotalCount <Int64>] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Get-Content cmdlet gets the content of the item at the location specifi ed by the path, such as the text in a file. It reads the content one line a t a time and returns an object for each line. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers that are installed wit h Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Overrides restrictions that prevent the command from succeeding, just s o the changes do not compromise security. For example, Force will overr ide the read-only attribute or create directories to complete a file pa th, but it will not attempt to change file permissions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Retrieves only the specified items. The value of this parameter qualifi es the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies the path to an item. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcard s. If the path includes escape characters, enclose it in single quotati on marks. Single quotation marks tell Windows PowerShell not to interpr et any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the path to an item. Get-Content retrieves the content of the item. Wildcards are permitted. The parameter name ("Path" or "FilePath ") is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -ReadCount <Int64> Specifies how many lines of content are sent through the pipeline at a time. The default value is 1. A value of 0 (zero) sends all of the cont ent at one time. This parameter does not change the content displayed, but it does affec t the time it takes to display the content. As the value of ReadCount i ncreases, the time it takes to return the first line increases, but the total time for the operation decreases. This can make a perceptible di fference in very large items. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -TotalCount <Int64> Specifies how many lines of content are retrieved. The default is -1 (a ll lines). Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to Get-Content. OUTPUTS Object Get-Content returns objects that represent the content that it gets. Th e object type depends on the content type. NOTES You can also refer to Get-Content by its built-in aliases, "cat", "type " and "gc". For more information, see about_Aliases. The Get-Content cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-P sProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-content -Path C:\Chapters\chapter1.txt Description ----------- This command displays the content of the Chapter1.txt file on the console. It uses the Path parameter to specify the name of the item. Get-Content act ually passes the content down the pipeline, but because there are no other pipeline elements, the content is formatted and displayed on the console. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-content c:\Logs\Log060912.txt -totalcount 50 | set-content sample .txt Description ----------- This command gets the first 50 lines of the Log060912.txt file and stores t hem in the sample.txt file. The command uses the Get-Content cmdlet to get the text in the file. (The name of Path parameter, which is optional, is om itted.) The TotalCount parameter limits the retrieval to the first 50 lines . The pipeline operator (|) sends the result to Set-Content, which places i t in the sample.txt file. -------------------------- EXAMPLE 3 -------------------------- C:\PS>(get-content cmdlets.txt -totalcount 5)[-1] Description ----------- This command gets the fifth line of the Cmdlets.txt text file. It uses the TotalCount parameter to get the first five lines and then uses array notati on to get the last line (indicated by "-1") of the resulting set. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113310 about_Providers Add-Content Set-Content Clear-Content Get-Counter NAME Get-Counter SYNOPSIS Gets performance counter data from local and remote computers. SYNTAX Get-Counter [-Counter] <string[]> [-ComputerName <string[]>] [-Continuous] [-MaxSamples <Int64>] [-SampleInterval <int>] [<CommonParameters>] Get-Counter -ListSet <string[]> [-ComputerName <string[]>] [<CommonParamete rs>] DESCRIPTION The Get-Counter cmdlet gets live, real-time performance counter data direct ly from the performance monitoring instrumentation in Windows. You can use it to get performance data from the local or remote computers at the sampl e interval that you specify. Without parameters, a "Get-Counter" command gets counter data for a set of system counters. You can use the parameters of Get-Counter to specify one or more computers, to list the performance counter sets and the counters that they contain, a nd to set the sample size and interval. PARAMETERS -ComputerName <string[]> Gets data from the specified computers. Type the NetBIOS name, an Inter net Protocol (IP) address, or the fully qualified domain names of the c omputers. The default value is the local computer. Note: Get-Counter does not rely on Windows PowerShell remoting. You ca n use the ComputerName parameter of Get-Counter even if your computer i s not configured for remoting in Windows PowerShell. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Continuous [<SwitchParameter>] Gets samples continuously until you press CTRL+C. By default, Get-Count er gets only one counter sample. You can use the SampleInterval paramet er to set the interval for continuous sampling. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Counter <string[]> Gets data from the specified performance counters. Enter one or more co unter paths. Wildcards are permitted only in the Instance value. You ca n also pipe counter path strings to Get-Counter. Each counter path has the following format: "[\\<ComputerName>]\<CounterSet>(<Instance>)\ For example: "\\Server01\Processor(2)\% User Time". The <ComputerName> element is optional. If you omit it, Get-Counter use s the value of the ComputerName parameter. Note: To get correctly formatted counter paths, use the ListSet parame ter to get a performance counter set. The Paths and PathsWithInstances properties of each performance counter set contain the individual count er paths formatted as a string. You can save the counter path strings i n a variable or pipe the string directly to another Get-Counter command . For a demonstration, see the examples. Required? true Position? 2 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? true -ListSet <string[]> Gets the specified performance counter sets on the computers. Enter the names of the counter sets. Wildcards are permitted. You can also pipe counter set names to Get-Counter. Required? true Position? named Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true -MaxSamples <Int64> Specifies the number of samples to get from each counter. The default i s 1 sample. To get samples continuously (no maximum sample size), use t he Continuous parameter. To collect a very large data set, consider running a Get-Counter comman d as a Windows PowerShell background job. For more information, see abo ut_Jobs and Start-Job. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SampleInterval <int> Specifies the time between samples in seconds. The minimum value and th e default value are 1 second. Required? false Position? named Default value 1 Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String[] You can pipe counter paths and counter set (ListSet) names to Get-Count er. OUTPUTS Microsoft.PowerShell.Commands.GetCounter.CounterSet, Microsoft.PowerShell.C ommands.GetCounter.PerformanceCounterSampleSet, Microsoft.PowerShell.Comman ds.GetCounter.PerformanceCounterSample The ListSet parameter gets Microsoft.PowerShell.Commands.GetCounter.Cou nterSet objects. The Counter parameter gets Microsoft.PowerShell.Comman ds.GetCounter.PerformanceCounterSampleSet objects. Each counter value is a Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSample object. NOTES Performance counters are often protected by access control lists (ACLs) . To get all available performance counters, open Windows PowerShell wi th the "Run as administrator" option. By default, Get-Counter gets one sample during a one-second sample inte rval. To change this behavior, use the MaxSamples and Continuous parame ters. The MaxSamples and SampleInterval values that you set apply to all the counters on all the computers in the command. To set different values f or different counters, enter separate Get-Counter commands for each cou nter. -------------------------- EXAMPLE 1 -------------------------- C:\PS># Get-Counter Description ----------- This command gets all of the counter sets on the local computer. C:\PS> get-counter -ListSet * Because many of the counter sets are protected by access control lists (ACL s), to see all counter sets, open Windows PowerShell with the "Run as admin istrator" option before using the Get-Counter command. -------------------------- EXAMPLE 2 -------------------------- C:\PS># Get-Counter Description ----------- This command gets the current "% Processor Time" combined values for all pr ocessors on the local computer. It collects data every two seconds until it has three values. C:\PS> get-counter -Counter "\Processor(_Total)\% Processor Time" -SampleIn terval 2 -MaxSamples 3 -------------------------- EXAMPLE 3 -------------------------- C:\PS># Get-Counter Description ----------- This command gets an alphabetically sorted list of the names of all of the counter sets on the local computer. C:\PS> get-counter -listset * | sort-object countersetname | format-table countersetname -------------------------- EXAMPLE 4 -------------------------- C:\PS># Get-Counter Description ----------- These commands use the Path property of a counter set to find the correctly formatted path names for the performance counters. You can use a command l ike this one to get the correct counter path names. The first command gets the path names of the performance counters in the Me mory counter set on the local computer. C:\PS> (get-counter -listset memory).paths \Memory\Page Faults/sec \Memory\Available Bytes \Memory\Committed Bytes \Memory\Commit Limit \Memory\Write Copies/sec \Memory\Transition Faults/sec \Memory\Cache Faults/sec \Memory\Demand Zero Faults/sec \Memory\Pages/sec \Memory\Pages Input/sec ... The second command gets the path names that include "cache". C:\PS> (get-counter -listset memory).paths | where {$_ -like "*cache*"} \Memory\Cache Faults/sec \Memory\Cache Bytes \Memory\Cache Bytes Peak \Memory\System Cache Resident Bytes \Memory\Standby Cache Reserve Bytes \Memory\Standby Cache Normal Priority Bytes \Memory\Standby Cache Core Bytes -------------------------- EXAMPLE 5 -------------------------- C:\PS># Get-Counter Description ----------- These commands get the Disk Reads/sec counter data from the Server01 and Se rver02 computers. The first command saves the Disk Reads/sec counter path in the $diskreads v ariable. C:\PS> $diskreads = "\LogicalDisk(C:)\Disk Reads/sec" The second command uses a pipeline operator (|) to send the counter path in the $diskreads variable to the Get-Counter cmdlet. The command uses the Ma xSamples parameter to limit the output to 10 samples. C:\PS> $diskreads | get-counter -computer Server01, Server02 -maxsamples 10 -------------------------- EXAMPLE 6 -------------------------- C:\PS># Get-Counter Description ----------- This command gets the correctly formatted path names for the PhysicalDisk performance counters, including the instance names. C:\PS> (get-counter -list physicaldisk).pathswithinstances -------------------------- EXAMPLE 7 -------------------------- C:\PS># Get-Counter Description ----------- These commands get the value of the "% DPC Time" performance counter on 50 randomly select computers in the enterprise. The first command uses the Get-Content cmdlet to get the list of enterprise servers from the Servers.txt file. It uses the Get-Random cmdlet to select 50 server names randomly from the Servers.txt file contents. The results a re saved in the $servers variable. C:\PS> $servers = get-random (get-content servers.txt) -count 50 The second command saves the counter path to the "% DPC Time" cmdlet in the $Counter variable. The counter path includes a wildcard character in the i nstance name to get the data on all of the processors on each of the comput ers. C:\PS> $counter = "\Processor(*)\% DPC Time" The third command uses the Get-Counter cmdlet to get the counter values. It uses the Counter parameter to specify the counters and the ComputerName pa rameter to specify the computers saved in the $servers variable. C:\PS> get-counter -Counter $counter -computername $servers -------------------------- EXAMPLE 8 -------------------------- C:\PS># Get-Counter Description ----------- These commands get a single value for all of the performance counters in th e memory counter set on the local computer. The first command gets the counter paths and saves them in the $memCounters variable. C:\PS> $memCounters = (get-counter -list memory).paths The second command uses the Get-Counter cmdlet to get the counter data for each counter. It uses the Counter parameter to specify the counters in $mem Counters. C:\PS> get-counter -counter $memCounters -------------------------- EXAMPLE 9 -------------------------- C:\PS># Get-Counter Description ----------- This example shows the property values in the PerformanceCounterSample obje ct that represents each data sample. The first command saves a counter path in the $counter variable. C:\PS> $counter = "\\SERVER01\Process(Idle)\% Processor Time" The second command uses the Get-Counter cmdlet to get one sample of the cou nter values. It saves the results in the $data variable. C:\PS> $data = get-counter $counter The third command uses the Format-List cmdlet to display all the properties of the CounterSamples property of the sample set object as a list. C:\PS> $data.countersamples | format-list -property * Path : \\SERVER01\process(idle)\% processor time InstanceName : idle CookedValue : 198.467899571389 RawValue : 14329160321003 SecondValue : 128606459528326201 MultipleCount : 1 CounterType : Timer100Ns Timestamp : 7/15/2008 6:39:12 PM Timestamp100NSec : 128606207528320000 Status : 0 DefaultScale : 0 TimeBase : 10000000 You can use the properties of the CounterSamples object to examine, select, sort, and group the data. -------------------------- EXAMPLE 10 -------------------------- C:\PS># Get-Counter Description ----------- The command runs a Get-Counter command as background job. For more informat ion, see Start-Job. C:\PS> $counters = "\LogicalDisk(_Total)\% Free Space" C:\PS> start-job -scriptblock {get-counter -counter $counters -maxsamples 1 000) -------------------------- EXAMPLE 11 -------------------------- C:\PS># Get-Counter Description ----------- This command uses the Get-Counter and Get-Random cmdlets to find the percen tage of free disk space on 50 computers selected randomly from the Servers. txt file. C:\PS> get-counter -computername (get-random servers.txt -count 50) -counte r "\LogicalDisk(*)\% Free Space" -------------------------- EXAMPLE 12 -------------------------- C:\PS># Get-Counter Description ----------- This example shows how to associate counter data with the computer on which it originated, and how to manipulate the data. The first command uses the Get-Counter cmdlet to get the "LogicalDisk\% Fre e Space" counter value from two remote computers, S1 and S2. It saves the r esult in the $a variable. $a = get-counter "\LogicalDisk(_Total)\% Free Space" -comp s1, s2 The second command displays the results in the $a variable. All of the data is stored in the object, but it is not easy to see it in this form. C:\PS> $a Counter Paths: \\s1\\logicaldisk(c:)\% free space, \\s1\\logicaldisk(d:)\% free space, \\s1\\logicaldisk(_total)\% free space, \\s2\\logicaldisk(c:)\% free space, \\s2\\logicaldisk(_total)\% free space Timestamp : 7/15/2008 5:09:08 PM Cooked Values : "0.327058823529412", "17.8952248493278", "12.9994033060778" , "75.0754805595626", "75.0754805595626" The third command displays in a table the value of the CounterSamples prope rty of the PerformanceCounterSampleSet object that Get-Counter returns. (To see all of the properties and methods of the object, pipe it to the Get-Me mber cmdlet.) C:\PS> $a.countersamples | format-table -auto Path InstanceName CookedValue ---- ------------ ----------- \\s1\\logicaldisk(c:)\% free space c: 0.327058823529412 \\s1\\logicaldisk(d:)\% free space d: 17.8952248493278 \\s1\\logicaldisk(_total)\% free space _total 12.9994033060778 \\s2\\logicaldisk(c:)\% free space c: 75.0754805595626 \\s2\\logicaldisk(_total)\% free space _total 75.0754805595626 The CounterSamples property contains a PerformanceCounterSample object with its own properties and methods. The fourth command uses array notation to get the first counter sample and a pipeline operator to send the counter sa mple object to the Format-List cmdlet, which displays all of its properties and methods in a list. This display shows the richness of the data in each counter sample object. The fourth command shows how to select data from the counter samples. It us es the Where-Object cmdlet to get only the counter samples with a CookedVal ue of less than 15. C:\PS> $a.countersamples | where {$_.cookedvalue -lt 15} Path InstanceName CookedValue ---- ------------ ----------- \\s1\\logicaldisk(c:)\% free space c: 0.327058823529412 \\s1\\logicaldisk(_total)\% free space _total 12.9994033060778 -------------------------- EXAMPLE 13 -------------------------- C:\PS># Get-Counter Description ----------- This example shows how to sort the performance counter data that you retrie ve. The example finds the processes on the computer that are using the most processor time during the sampling. The first command gets the "Process\% Processor Time" counter for all the p rocesses on the computer. The command saves the results in the $p variable. C:\PS> $p = get-counter '\Process(*)\% Processor Time' The second command gets the CounterSamples property of the sample set objec t in $p and it sorts the samples in descending order based on the cooked va lue of the sample. The command uses the Format-Table cmdlet and its AutoFor mat parameter to position the columns in the table. C:\PS> $p.CounterSamples | sort-object -property CookedValue -Descending | format-table -auto Path InstanceName CookedV alue ---- ------------ ------- ---- \\server01\process(_total)\% processor time _total 200.006410 42078 \\server01\process(idle)\% processor time idle 200.006410 42078 \\server01\process(explorer#1)\% processor time explorer 0 \\server01\process(dwm#1)\% processor time dwm 0 \\server01\process(taskeng#1)\% processor time taskeng 0 \\server01\process(taskhost#1)\% processor time taskhost 0 \\server01\process(winlogon)\% processor time winlogon 0 \\server01\process(csrss)\% processor time csrss 0 -------------------------- EXAMPLE 14 -------------------------- C:\PS># Get-Counter Description ----------- These commands find the processes on the computer with the largest working sets. They list the processes in descending order based on their working se t size. The first command gets one sample of the "Process\Working Set - Private" co unter for each process. The command saves the counter data in the $ws varia ble. C:\PS> $ws = get-counter "\Process(*)\Working Set - Private" The second command uses a pipeline operator (|) to send the data in the Cou nterSamples property of the $ws variable to the Sort-Object cmdlet, where t he process data is sorted in descending order by the value of the CookedVal ue property. Another pipeline sends the sorted data to the Format-Table cmd let, where the data is formatted as a table with InstanceName and CookedVal ue columns. C:\PS> $ws.countersamples | sort-object -property cookedvalue -descending | format-table -property InstanceName, CookedValue -auto InstanceName CookedValue ------------ ----------- _total 162983936 svchost 40370176 powershell 15110144 explorer 14135296 svchost 10928128 svchost 9027584 ... -------------------------- EXAMPLE 15 -------------------------- C:\PS># Get-Counter Description ----------- This command gets a series of samples of the Processor\% Processor Time cou nter at the default one second interval. To stop the command, press CTRL + C. C:\PS> get-counter -counter "\processor(_total)\% processor time" -continuo us RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=138335 Import-Counter Export-Counter Get-Credential NAME Get-Credential SYNOPSIS Gets a credential object based on a user name and password. SYNTAX Get-Credential [-Credential] <PSCredential> [<CommonParameters>] DESCRIPTION The Get-Credential cmdlet creates a credential object for a specified user name and password. You can use the credential object in security operations . The cmdlet prompts the user for a password or user name and password. Users are prompted through a dialog box or at the command line, depending on the system registry setting. PARAMETERS -Credential <PSCredential> Specifies a user name for the credential, such as "User01" or "Domain01 \User01". The parameter name ("Credential") is optional. When you submit the command, you will be prompted for a password. If you enter a user name without a domain, Get-Credential inserts a bac kslash before the name. If you omit this parameter, you will be prompted for a user name and a password. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.PSCredential Get-Credential returns a credential object. NOTES You can use the PSCredential object that Get-Credential creates in cmdl ets that request user authentication, such as those with a Credential p arameter. The Credential parameter is not supported by the providers that are ins talled with Windows PowerShell. However, you can use the Credential par ameter with Get-WmiObject, because it calls the Microsoft .NET Framewor k directly. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$c = Get-Credential Description ----------- This command gets a credential object and saves it in the $c variable. When you enter the command, a dialog box appears requesting a user name and password. When you enter the requested information, the cmdlet creates a P SCredential object representing the credentials of the user and saves it in the $c variable. You can use the object as input to cmdlets that request user authentication , such as those with a Credential parameter. However, the providers that ar e installed with Windows PowerShell do not support the Credential parameter . -------------------------- EXAMPLE 2 -------------------------- C:\PS>$c = Get-Credential C:\PS>Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c Description ----------- These commands use a credential object from Get-Credential to authenticate a user on a remote computer so they can use Windows Management Instrumentat ion (WMI) to manage the computer. The first command gets a credential object and saves it in the $c variable. The second command uses the credential object in a Get-WmiObject command. This command gets information about the disk drives on the Server01 compute r. -------------------------- EXAMPLE 3 -------------------------- C:\PS>C:\PS>Get-WmiObject Win32_BIOS -ComputerName Server01 ' -Credential (get-credential Domain01\User01) Description ----------- This command shows how to include a Get-Credential command in a Get-WmiObje ct command. This command uses the Get-WmiObject cmdlet to get information about the BIO S on the Server01 computer. It uses the Credential parameter to authenticat e the user, Domain01\User01, and a Get-Credential command as the value of t he Credential parameter. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$c = Get-Credential -credential User01 C:\PS>$c.Username \User01 Description ----------- This example creates a credential that includes a user name without a domai n name. It demonstrates that Get-Credential inserts a backslash before the user name. The first command gets a credential with the user name User01 and stores it in the $c variable. The second command displays the value of the Username property of the resul ting credential object. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$credential = $host.ui.PromptForCredential("Need credentials", "Pleas e enter your user name and password.", "", "NetBiosUserName") Description ----------- This command uses the PromptForCredential method to prompt the user for the ir user name and password. The command saves the resulting credentials in t he $credential variable. PromptForCredential is an alternative to using Get-Credential. When you use PromptForCredential, you can specify the caption, messages, and user name that appear in the message box. -------------------------- EXAMPLE 6 -------------------------- C:\PS>Set-ItemProperty 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds' Con solePrompting $true Description ----------- When requiring a user name and password, as a default, a dialog box appears to prompt the user. To be prompted at the command line, modify the registr y by running this command in Windows PowerShell Run as administrator. Use the same command with "ConsolePrompting $false" to be prompted with a d ialog box. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113311 Get-Culture NAME Get-Culture SYNOPSIS Gets the current culture set in the operating system. SYNTAX Get-Culture [<CommonParameters>] DESCRIPTION The Get-Culture cmdlet gets information about the current culture settings. This includes information about the current language settings on the syste m, such as the keyboard layout, and the display format of items such as num bers, currency, and dates. You can also use the Get-UICulture cmdlet, which gets the current user inte rface culture on the system. The user-interface (UI) culture determines whi ch text strings are used for user interface elements, such as menus and mes sages. PARAMETERS <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Globalization.CultureInfo Get-Culture returns an object that represents the current culture. NOTES You can also use the $PsCulture and $PsUICulture variables. The $PsCult ure variable stores the name of the current culture and the $PsUICultur e variable stores the name of the current UI culture. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-culture Description ----------- This command displays information about the regional settings on the comput er. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$c = get-culture C:\PS> $c | format-list -property * Parent : en LCID : 1033 KeyboardLayoutId : 1033 Name : en-US IetfLanguageTag : en-US DisplayName : English (United States) NativeName : English (United States) EnglishName : English (United States) TwoLetterISOLanguageName : en ThreeLetterISOLanguageName : eng ThreeLetterWindowsLanguageName : ENU CompareInfo : CompareInfo - 1033 TextInfo : TextInfo - 1033 IsNeutralCulture : False CultureTypes : SpecificCultures, InstalledWin32Cultures, FrameworkCultures NumberFormat : System.Globalization.NumberFormatInfo DateTimeFormat : System.Globalization.DateTimeFormatInfo Calendar : System.Globalization.GregorianCalendar OptionalCalendars : {System.Globalization.GregorianCalendar, S ystem.Globalization.GregorianCalendar} UseUserOverride : True IsReadOnly : False C:\PS> $c.calendar MinSupportedDateTime : 1/1/0001 12:00:00 AM MaxSupportedDateTime : 12/31/9999 11:59:59 PM AlgorithmType : SolarCalendar CalendarType : Localized Eras : {1} TwoDigitYearMax : 2029 IsReadOnly : False C:\PS> $c.datetimeformat AMDesignator : AM Calendar : System.Globalization.GregorianCalendar DateSeparator : / FirstDayOfWeek : Sunday CalendarWeekRule : FirstDay FullDateTimePattern : dddd, MMMM dd, yyyy h:mm:ss tt LongDatePattern : dddd, MMMM dd, yyyy LongTimePattern : h:mm:ss tt MonthDayPattern : MMMM dd PMDesignator : PM RFC1123Pattern : ddd, dd MMM yyyy HH':'mm':'ss 'GMT' ShortDatePattern : M/d/yyyy ShortTimePattern : h:mm tt SortableDateTimePattern : yyyy'-'MM'-'dd'T'HH':'mm':'ss TimeSeparator : : UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z' YearMonthPattern : MMMM, yyyy AbbreviatedDayNames : {Sun, Mon, Tue, Wed...} ShortestDayNames : {Su, Mo, Tu, We...} DayNames : {Sunday, Monday, Tuesday, Wednesday...} AbbreviatedMonthNames : {Jan, Feb, Mar, Apr...} MonthNames : {January, February, March, April...} IsReadOnly : False NativeCalendarName : Gregorian Calendar AbbreviatedMonthGenitiveNames : {Jan, Feb, Mar, Apr...} MonthGenitiveNames : {January, February, March, April...} C:\PS> $c.datetimeformat.firstdayofweek Sunday Description ----------- This example demonstrates the vast amount of data in the culture object. It shows how to display the properties and sub-properties of the object. The first command uses the Get-Culture cmdlet to get the current culture se ttings on the computer. It stores the resulting culture object in the $c va riable. The second command displays all of the properties of the culture object. It uses a pipeline operator (|) to send the culture object in $c to the Forma t-List cmdlet. It uses the Property parameter to display all (*) properties of the object. (This command can be abbreviated as "$c | fl *".) The remaining commands explore the properties of the culture object by usin g dot notation to display the values of the object properties. You can use this notation to display the value of any property of the object. The third command uses dot notation to display the value of the Calendar pr operty of the culture object. The fourth command uses dot notation to display the value of the DataTimeFo rmat property of the culture object. Many object properties have properties. The fifth command uses dot notation to display the value of the FirstDayOfWeek property of the DateTimeFormat property. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113312 Get-Date NAME Get-Date SYNOPSIS Gets the current date and time. SYNTAX Get-Date [-Format <string>] [[-Date] <DateTime>] [-Day <int>] [-DisplayHint {Date | Time | DateTime}] [-Hour <int>] [-Minute <int>] [-Month <int>] [-S econd <int>] [-Year <int>] [<CommonParameters>] Get-Date [-UFormat <string>] [[-Date] <DateTime>] [-Day <int>] [-DisplayHin t {Date | Time | DateTime}] [-Hour <int>] [-Minute <int>] [-Month <int>] [- Second <int>] [-Year <int>] [<CommonParameters>] DESCRIPTION The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. It can format the date and time in several Win dows and UNIX formats. You can use Get-Date to generate a date or time char acter string, and then send the string to other cmdlets or programs. PARAMETERS -Date <DateTime> Specifies a date and time. By default, Get-Date gets the current system date and time. Type the date in a format that is standard for the system locale, such as dd-MM-yyyy (German [Germany]) or MM/dd/yyyy (English [United States] ). Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Day <int> Specifies the day of the month that is displayed. Enter a value from 1 to 31. This value is displayed instead of the current day. If you specify a value that is greater than the number of days in the m onth, Windows PowerShell adds the number of days to the month and displ ays the result. For example, "get-date -month 2 -day 31" displays "Marc h 3", not "February 31". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DisplayHint <DisplayHintType> Determines which elements of the date and time are displayed. Valid values are: -- Date: displays only the date -- Time: displays only the time -- DateTime: displays the date and time DateTime is the default. This parameter does not affect the DateTime object that Get-Date retrie ves. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Format <string> Displays the date and time in the Microsoft .NET Framework format indic ated by the format specifier. Enter a format specifier. For a list of a vailable format specifiers, see "DateTimeFormatInfo Class" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink /?LinkId=143638. When you use the Format parameter, Windows PowerShell retrieves only th e properties of the DateTime object that it needs to display the date i n the format that you specify. As a result, some of the properties and methods of DateTime objects might not be available. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Hour <int> Specifies the hour that is displayed. Enter a value from 1 to 23. This value is displayed instead of the current hour. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Minute <int> Specifies the minute that is displayed. Enter a value from 1 to 59. Thi s value is displayed instead of the current minute. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Month <int> Specifies the month that is displayed. Enter a value from 1 to 12. This value is displayed instead of the current month. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Second <int> Specifies the second that is displayed. Enter a value from 1 to 59. Thi s value is displayed instead of the current second. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UFormat <string> Displays the date and time in UNIX format. For a list of the format spe cifiers, see the Notes section. When you use the UFormat parameter, Windows PowerShell retrieves only t he properties of the DateTime object that it needs to display the date in the format that you specify. As a result, some of the properties and methods of DateTime objects might not be available. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Year <int> Specifies the year that is displayed. Enter a value from 1 to 9999. Thi s value is displayed instead of the current year. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.DateTime or System.String When you use the Format or UFormat parameters, the output object is Sys tem.String. NOTES By default, the date-time is displayed in long-date and long-time forma ts for the system locale. When you pipe a date to cmdlets that expect string input, such as Add-C ontent, Windows PowerShell converts the DateTime object to a string bef ore adding it to the file. The default ToString() format is short date and long time. To specify an alternate format, use the Format or UForma t parameters of Get-Date. Uformat Values: The following are the values of the UFormat parameter. The format for t he command is: get-date -uformat %<value> For example, get-date -uformat %d Date-Time: Date and time - full (default) (Friday, June 16, 2006 10:31:27 AM) c Date and time - abbreviated (Fri Jun 16 10:31:27 2006) Date: D Date in mm/dd/yy format (06/14/06) x Date in standard format for locale (09/12/07 for English-US) Year: C Century (20 for 2006) Y Year in 4-digit format (2006) y Year in 2-digit format (06) G Same as 'Y' g Same as 'y' Month: b Month name - abbreviated (Jan) B Month name - full (January) h Same as 'b' m Month number (06) Week: W Week of the year (00-52) V Week of the year (01-53) U Same as 'W' Day: a Day of the week - abbreviated name (Mon) A Day of the week - full name (Monday) u Day of the week - number (Monday = 1) d Day of the month - 2 digits (05) e Day of the month - digit preceded by a space ( 5) j Day of the year - (1-366) w Same as 'u' Time: p AM or PM r Time in 12-hour format (09:15:36 AM) R Time in 24-hour format - no seconds (17:45) T Time in 24 hour format (17:45:52) X Same as 'T' Z Time zone offset from Universal Time Coordinate (UTC) (-07) Hour: H Hour in 24-hour format (17) I Hour in 12 hour format (05) k Same as 'H' l Same as 'I' (Upper-case I = Lower-case L) Minutes & Seconds: M Minutes (35) S Seconds (05) s Seconds elapsed since January 1, 1970 00:00:00 (1150451174.95705) Special Characters: n newline character (\n) t Tab character (\t) -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-date -DisplayHint date Tuesday, June 13, 2006 Description ----------- This command retrieves a DateTime object, but it displays only the date. It uses the DisplayHint parameter to indicate that only the date is to be dis played. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-date -format g 6/13/2006 12:43 PM Description ----------- This command retrieves the current date and time and formats it in short-da te and short-time format. It uses the .NET Framework "g" format specifier ( General [short date and short time]) to specify the format. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-date -uformat "%Y / %m / %d / %A / %Z" 2006 / 06 / 13 / Tuesday / -07 Description ----------- This command retrieves the current date and time and formats it as specifie d by the command. In this case, the format includes the full year (%Y), the two-digit numeric month (%m), the date (%d), the full day of the week (%A) , and the offset from UTC ("Zulu"). -------------------------- EXAMPLE 4 -------------------------- C:\PS>(get-date -year 2000 -month 12 -day 31).dayofyear 366 Description ----------- This command displays the day of the year for the current date. For example , December 31 is the 365th day of 2006, but it is the 366th day of 2000. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$a = get-date C:\PS> $a.IsDaylightSavingTime() True Description ----------- These commands tell you whether the current date and time are adjusted for daylight savings time in the current locale. The first command creates a variable named $a and then assigns the object r etrieved by Get-Date to the $a variable. Then, it uses the IsDaylightSaving Time method on the object in $a. To see the properties and methods of the DateTime object, type: "get-date | get-member". -------------------------- EXAMPLE 6 -------------------------- C:\PS>$a = get-date C:\PS> $a.ToUniversalTime() Tuesday, June 13, 2006 8:09:19 PM Description ----------- These commands convert the current date and time to UTC time. The first command creates a variable named $a and then assigns the object r etrieved by Get-Date to the $a variable. Then, it uses the ToUniversalTime method on the object in $a. -------------------------- EXAMPLE 7 -------------------------- C:\PS>$a = get-wmiobject win32_bios -computer server01 $a | format-list -property Name, @{Label="BIOS Age"; ` Expression={(get-date) - $_.ConvertToDateTime($_.ReleaseDate)}} Name : Default System BIOS BIOS Age : 1345.17:31:07.1091047 Description ----------- Windows Management Instrumentation (WMI) uses a different date-time object than the .NET Framework date-time object that Get-Date returns. To use date -time information from WMI in a command with date-time information from Get -Date, you have to use the ConvertToDateTime method to convert WMI CIM_DATE TIME objects to .NET Framework DateTime objects. The commands in this example display the name and age of the BIOS on a remo te computer, Server01. The first command uses the Get-WmiObject cmdlet to get an instance of the W in32_BIOS class on Server01 and then stores it in the $a variable. The second command uses the pipeline operator (|) to send the WMI object st ored in $a to the Format-List cmdlet. The Property parameter of Format-List is used to specify two properties to display in the list, "Name" and "BIOS Age". The "BIOS Age" property is specified in a hash table. The table incl udes the Label key, which specifies the name of the property, and the Expre ssion key, which contains the expression that calculates the BIOS age. The expression uses the ConvertToDateTime method to convert each instance of Re leaseDate to a .NET Framework DateTime object. Then, the value is subtracte d from the value of the Get-Date cmdlet, which, without parameters, gets th e current date. The backtick character (`) is the line continuation character in Windows Po werShell. -------------------------- EXAMPLE 8 -------------------------- C:\PS>get-date Tuesday, June 13, 2006 12:43:42 PM Description ----------- This command gets a DateTime object and displays the current date and time in the long date and long time formats for the system locale, as though you typed "get-date -format F". -------------------------- EXAMPLE 9 -------------------------- C:\PS>get-date C:\PS> Tuesday, September 26, 2006 11:25:31 AM c:\PS>(get-date).ToString() 9/26/2006 11:25:31 AM C:\PS>get-date | add-content test.txt # Adds 9/26/2006 11:25:31 AM C:\PS>get-date -format F | add-content test.txt # Adds Tuesday, September 26, 2006 11:25:31 AM Description ----------- These commands demonstrate how to use Get-Date with Add-Content and other c mdlets that convert the DateTime object that Get-Date generates to a string . The first command shows that the default display from a "get-date" command is in long-date and long-time format. The second command shows that the default display from the ToString() metho d of the DateTime object is in short-date and short-time format. The third command uses a pipeline operator to send the DateTime object to t he Add-Content cmdlet, which adds the content to the Test.txt file. Because Add-Content uses the ToString() method of the DateTime object, the date th at is added is in short-date and short-time format. The fourth command uses the Format parameter of Get-Date to specify the for mat. When you use the Format or UFormat parameters, Get-Date generates a st ring, not a DateTime object. Then, when you send the string to Add-Content, it adds the string to the Test.txt file without changing it. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113313 Set-Date New-TimeSpan Get-Event NAME Get-Event SYNOPSIS Gets the events in the event queue. SYNTAX Get-Event [-EventIdentifier] <int> [<CommonParameters>] Get-Event [[-SourceIdentifier] <string>] [<CommonParameters>] DESCRIPTION The Get-Event cmdlet gets events in the Windows PowerShell event queue for the current session. You can get all events or use the EventIdentifier or S ourceIdentifier parameters to specify the events. When an event occurs, it is added to the event queue. The event queue inclu des events for which you have registered, events created by using the New-E vent cmdlet, and the event that is raised when Windows PowerShell exits. Yo u can use Get-Event or Wait-Event to get the events. This cmdlet does not get events from the Event Viewer logs. To get those ev ents, use Get-WinEvent or Get-EventLog. PARAMETERS -EventIdentifier <int> Gets only the events with the specified event identifier. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -SourceIdentifier <string> Gets only events with the specified source identifier. The default is a ll events in the event queue. Wildcards are not permitted. Required? false Position? 1 Default value All events Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.PSEventArgs Get-Event returns a PSEventArgs object for each event. To see a descrip tion of this object, type "get-help get-event -full" and see the Notes section of the help topic. NOTES Events, event subscriptions, and the event queue exist only in the curr ent session. If you close the current session, the event queue is disca rded and the event subscription is canceled. The Get-Event cmdlet returns a PSEventArgs object (System.Management.Au tomation.PSEventArgs) with the following properties. -- ComputerName: The name of the computer on which the event occurred. This property value is populated only when the event is forwarded from a remote computer. -- RunspaceId: A GUID that uniquely identifies the session in which th e event occurred. This property value is populated only when the event is forwarded from a remote computer. -- EventIdentifier: An integer (Int32) that uniquely identifies the eve nt notification in the current session. -- Sender: The object that generated the event. In the value of the Act ion parameter, the $Sender automatic variable contains the sender objec t. -- SourceEventArgs: The first parameter that derives from EventArgs, if it exists. For example, in a timer elapsed event in which the signatu re has the form "Object sender, Timers.ElapsedEventArgs e", the SourceE ventArgs property would contain the Timers.ElapsedEventArgs. In the val ue of the Action parameter, the $SourceEventArgs automatic variable con tains this value. -- SourceArgs: All parameters of the original event signature. For a st andard event signature, $args[0] represents the sender, and $args[1] re presents the SourceEventArgs. In the value of the Action parameter, the $SourceArgs automatic variable contains this value. -- SourceIdentifier: A string that identifies the event subscription. In the value of the Action parameter, the SourceIdentifier property of the $Event automatic variable contains this value. -- TimeGenerated: A DateTime object that represents the time at which t he event was generated. In the value of the Action parameter, the TimeG enerated property of the $Event automatic variable contains this value. --MessageData: Data associated with the event subscription. Users speci fy this data when they register an event. In the value of the Action pa rameter, the MessageData property of the $Event automatic variable cont ains this value. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-event Description ----------- This command gets all events in the event queue. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-event -sourceIdentifier "PowerShell.ProcessCreated" Description ----------- This command gets events in which the value of the SourceIdentifier propert y is "PowerShell.ProcessCreated". -------------------------- EXAMPLE 3 -------------------------- C:\PS>$events = get-event C:\PS> $events[0] | format-list -property * ComputerName : RunspaceId : c2153740-256d-46c0-a57c-b805917d1b7b EventIdentifier : 1 Sender : System.Management.ManagementEventWatcher SourceEventArgs : System.Management.EventArrivedEventArgs SourceArgs : {System.Management.ManagementEventWatcher, System.Manage ment.EventArrivedEventArgs} SourceIdentifier : ProcessStarted TimeGenerated : 11/13/2008 12:09:32 PM MessageData : C:\PS> get-event | where {$_.TimeGenerated -ge "11/13/2008 12:15:00 PM"} ComputerName : RunspaceId : c2153740-256d-46c0-a57c-b8059325d1a0 EventIdentifier : 1 Sender : System.Management.ManagementEventWatcher SourceEventArgs : System.Management.EventArrivedEventArgs SourceArgs : {System.Management.ManagementEventWatcher, System.Manage ment.EventArrivedEventArgs} SourceIdentifier : ProcessStarted TimeGenerated : 11/13/2008 12:15:00 PM MessageData : Description ----------- This example shows how to get events by using properties other than SourceI dentifier. The first command gets all events in the event queue and saves them in the $events variable. The second command uses array notation to get the first (0-index) event in the array in the $events variable. The command uses a pipeline operator (|) to send the event to the Format-List command, which displays all propertie s of the event in a list. This allows you to examine the properties of the event object. The third command shows how to use the Where-Object cmdlet to get an event based on the time that it was generated. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-event -eventIdentifier 2 Description ----------- This command gets the event with an event identifier of 2. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113453 Register-ObjectEvent Register-EngineEvent Register-WmiEvent Unregister-Event New-Event Remove-Event Wait-Event Get-EventLog NAME Get-EventLog SYNOPSIS Gets the events in an event log, or a list of the event logs, on the local or remote computers. SYNTAX Get-EventLog [-AsString] [-ComputerName <string[]>] [-List] [<CommonParamet ers>] Get-EventLog [-LogName] <string> [[-InstanceId] <Int64[]>] [-After <DateTim e>] [-AsBaseObject] [-Before <DateTime>] [-ComputerName <string[]>] [-Entry Type <string[]>] [-Index <Int32[]>] [-Message <string>] [-Newest ource <string[]>] [-UserName <string[]>] [<CommonParameters>] DESCRIPTION The Get-EventLog cmdlet gets events and event logs on the local and remote computers. Use the parameters of Get-EventLog to search for events by using their prop erty values. Get-EventLog gets only the events that match all of the specif ied property values. The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinE vent. PARAMETERS -After <DateTime> Gets only the events that occur after the specified date and time. Ente r a DateTime object, such as the one returned by the Get-Date cmdlet. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -AsBaseObject [<SwitchParameter>] Returns a standard System.Diagnostics.EventLogEntry object for each eve nt. Without this parameter, Get-EventLog returns an extended PSObject o bject with additional EventLogName, Source, and InstanceId properties. To see the effect of this parameter, pipe the events to the Get-Member cmdlet and examine the TypeName value in the result. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -AsString [<SwitchParameter>] Returns the output as strings, instead of objects. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Before <DateTime> Gets only the events that occur before the specified date and time. Ent er a DateTime object, such as the one returned by the Get-Date cmdlet. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Specifies a remote computer. The default is the local computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qu alified domain name of a remote computer. To specify the local computer , type the computer name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Get-EventLog even if your computer is n ot configured to run remote commands. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -EntryType <string[]> Gets only events with the specified entry type. Valid values are Error, Information, FailureAudit, SuccessAudit, and Warning. The default is a ll events. Required? false Position? named Default value All events Accept pipeline input? false Accept wildcard characters? false -Index <Int32[]> Gets only events with the specified index values. Required? false Position? named Default value All events Accept pipeline input? false Accept wildcard characters? false -InstanceId <Int64[]> Gets only events with the specified instance IDs. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -List [<SwitchParameter>] Gets a list of event logs on the computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LogName <string> Specifies the event log. Enter the log name (the value of the Log prop erty; not the LogDisplayName) of one event log. Wildcard characters are not permitted. This parameter is required. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Message <string> Gets events that have the specified string in their messages. You can u se this property to search for messages that contain certain words or p hrases. Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -Newest <int> Specifies the maximum number of events retrieved. Get-EventLog gets the specified number of events, beginning with the newest event in the log . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Source <string[]> Gets events that were written to the log by the specified sources. Wild cards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -UserName <string[]> Gets only the events that are associated with the specified user names. Enter names or name patterns, such as User01, User*, or Domain01\User* . Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None. You cannot pipe input to this cmdlet. OUTPUTS System.Diagnostics.EventLogEntry. System.Diagnostics.EventLog. System.Strin g If the LogName parameter is specified, the output is a collection of Ev entLogEntry objects (System.Diagnostics.EventLogEntry). If only the List parameter is specified, the output is a collection of EventLog objects (System.Diagnostics.EventLog). If both the List and AsString parameters are specified, the output is a collection of Strings (System.String). NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-eventlog -list Description ----------- This command displays information about the event logs on the computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-eventlog -newest 5 -logname application Description ----------- This command displays the five most recent entries in the Application event log. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$events = get-eventlog -logname system -newest 1000 C:\PS> $events | group-object -property source -noelement | sort-object -pr operty count -descending Count Name ----- ---- 75 Service Control Manager 12 Print 6 UmrdpService 2 DnsApi 2 DCOM 1 Dhcp 1 TermDD 1 volsnap Description ----------- This example shows how to find all of the sources that are represented in t he 1000 most recent entries in the System event log. The first command gets the 1,000 most recent entries from the System event log and stores them in the $events variable. The second command uses a pipeline operator (|) to send the events in $even ts to the Group-Object cmdlet, which groups the entries by the value of the Source property. The command uses a second pipeline operator to send the g rouped events to the Sort-Object cmdlet, which sorts them in descending ord er, so the most frequently appearing source is listed first. Source is just property of event log entries. To see all of the properties of an event log entry, pipe the events to the Get-Member cmdlet. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-eventlog -logname System -EntryType Error Description ----------- This command gets only error events from the System event log. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-eventlog -logname System -instanceID 3221235481 -Source "DCOM" Description ----------- This command gets events from the System log that have an InstanceID of 322 1235481 and a Source value of "DCOM." -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-eventlog -logname "Windows PowerShell" -computername localhost, S erver01, Server02 Description ----------- This command gets the events from the "Windows PowerShell" event log on thr ee computers, Server01, Server02, and the local computer, known as "localho st". -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-eventlog -logname "Windows PowerShell" -message "*failed*" Description ----------- This command gets all the events in the Windows PowerShell event log that h ave a message value that includes the word "failed". -------------------------- EXAMPLE 8 -------------------------- C:\PS>$a = get-eventlog -log System -newest 1 C:\PS> $a | format-list -property * EventID : 7036 MachineName : Server01 Data : {} Index : 10238 Category : (0) CategoryNumber : 0 EntryType : Information Message : The description for Event ID Source : Service Control Manager ReplacementStrings : {WinHTTP Web Proxy Auto-Disco InstanceId : 1073748860 TimeGenerated : 4/11/2008 9:56:05 PM TimeWritten : 4/11/2008 9:56:05 PM UserName : Site : Container : Description ----------- This example shows how to display all of the property values of an event. The first command gets the newest event from the System event log and saves it in the $a variable. The second command uses a pipeline operator (|) to send the event in $a to the Format-List command, which displays all (*) of the event properties. -------------------------- EXAMPLE 9 -------------------------- C:\PS>get-eventlog -log application -source outlook | where {$_.eventID -eq 34} Description ----------- This command gets events in the Application event log where the source is O utlook and the event ID is 34. Even though Get-EventLog does not have an Ev entID parameter, you can use the Where-Object cmdlet to select events based on the value of any event property. -------------------------- EXAMPLE 10 -------------------------- C:\PS>get-eventlog -log system -username NT* | group-object -property usern ame -noelement | format-table Count, Name -auto Count Name ----- ---- 6031 NT AUTHORITY\SYSTEM 42 NT AUTHORITY\LOCAL SERVICE 4 NT AUTHORITY\NETWORK SERVICE Description ----------- This command returns the events in the system log grouped by the value of their UserName property. The Get-EventLog command uses the UserName paramet er to get only events in which the user name begins with "NT*". -------------------------- EXAMPLE 11 -------------------------- C:\PS>$May31 = get-date 5/31/08 C:\PS> $July1 = get-date 7/01/08 C:\PS> get-eventlog -log "Windows PowerShell" -entrytype Error -after $may3 1 -before $july1 Description ----------- This command gets all of the errors in the Windows PowerShell event log tha t occurred in June 2008. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113314 Get-WinEvent Clear-EventLog Limit-EventLog New-EventLog Remove-EventLog Show-EventLog Write-EventLog Get-WinEvent Get-EventSubscriber NAME Get-EventSubscriber SYNOPSIS Gets the event subscribers in the current session. SYNTAX Get-EventSubscriber [-SubscriptionId] <int> [[-Force]] [<CommonParameters>] Get-EventSubscriber [[-SourceIdentifier] <string>] [[-Force]] [<CommonParam eters>] DESCRIPTION The Get-EventSubscriber cmdlet gets the event subscribers in the current se ssion. When you subscribe to an event by using a Register event cmdlet, an event s ubscriber is added to your Windows PowerShell session, and the events to wh ich you subscribed are added to your event queue whenever they are raised. To cancel an event subscription, delete the event subscriber by using the U nregister-Event cmdlet. PARAMETERS -Force [<SwitchParameter>] Gets all event subscribers, including subscribers for events that are h idden by using the SupportEvent parameter of Register-ObjectEvent, Regi ster-WmiEvent, and Register-EngineEvent. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -SourceIdentifier <string> Gets only the event subscribers with the specified SourceIdentifier pro perty value. By default, Get-EventSubscriber gets all event subscribers in the session. Wildcards are not permitted. This parameter is case-se nsitive. Required? false Position? 1 Default value All event subscribers Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -SubscriptionId <int> Gets only the specified subscription identifier. By default, Get-EventS ubscriber gets all event subscribers in the session. Required? true Position? 1 Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.PSEventSubscriber Get-EventSubscriber returns an object that represents each event subscr iber. NOTES The New-Event cmdlet, which creates a custom event, does not generate a subscriber. Therefore, the Get-EventSubscriber cmdlet will not find a subscriber object for these events. However, if you use the Register-En gineEvent cmdlet to subscribe to a custom event (in order to forward th e event or to specify an action), Get-EventSubscriber will find the sub scriber that Register-EngineEvent generates. Events, event subscriptions, and the event queue exist only in the curr ent session. If you close the current session, the event queue is disca rded and the event subscription is canceled. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$timer = New-Object Timers.Timer C:\PS> $timer | Get-Member -Type Event C:\PS> Register-ObjectEvent -inputObject $timer -EventName Elapsed -SourceI dentifier Timer.Elapsed C:\PS> Get-EventSubscriber C:\PS> $timer = New-Object Timers.Timer C:\PS> $timer | Get-Member -Type Event TypeName: System.Timers.Timer Name MemberType Definition ---- ---------- ---------- Disposed Event System.EventHandler Disposed(System.Object, System.Even tArgs) Elapsed Event System.Timers.ElapsedEventHandler Elapsed(System.Object , System.Timers.ElapsedEventArgs) C:\PS> Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceI dentifier Timer.Elapsed C:\PS> Get-EventSubscriber SubscriptionId : 4 SourceObject : System.Timers.Timer EventName : Elapsed SourceIdentifier : Timer.Elapsed Action : HandlerDelegate : SupportEvent : False ForwardEvent : False Description ----------- This example uses a Get-EventSubscriber command to get the event subscriber for a timer event. The first command uses the New-Object cmdlet to create an instance of a tim er object. It saves the new timer object in the $timer variable. The second command uses the Get-Member cmdlet to display the events that ar e available for timer objects. The command uses the Type parameter of the G et-Member cmdlet with a value of Event. The third command uses the Register-ObjectEvent cmdlet to register for the Elapsed event on the timer object. The fourth command uses the Get-EventSubscriber cmdlet to get the event sub scriber for the Elapsed event. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$timer = New-Object Timers.Timer C:\PS> $timer.Interval = 500 C:\PS> Register-ObjectEvent -inputObject $timer -eventName Elapsed -sourceI dentifier Timer.Random -Action { $random = Get-Random -Min 0 -Max 100 } Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 3 Timer.Random NotStarted False $random = Get-Random . .. C:\PS> $timer.Enabled = $true C:\PS> $subscriber = Get-EventSubcriber -sourceIdentifer Timer.Random C:\PS> ($subscriber.action).gettype().fullname PSEventJob C:\PS> $subscriber.action | format-list -property * State : Running Module : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0 StatusMessage : HasMoreData : True Location : Command : $random = Get-Random -Min 0 -Max 100 JobStateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : 88944290-133d-4b44-8752-f901bd8012e2 Id : 1 Name : Timer.Random ChildJobs : {} ... C:\PS> & $subscriber.action.module {$random} 96 C:\PS> & $subscriber.action.module {$random} 23 Description ----------- This example shows how to use the dynamic module in the PSEventJob object i n the Action property of the event subscriber. The first command uses the New-Object cmdlet to create a timer object. The second command sets the interval of the timer to 500 (milliseconds). The third command uses the Register-ObjectEvent cmdlet to register the Elap sed event of the timer object. The command includes an action that handles the event. Whenever the timer interval elapses, an event is raised and the commands in the action run. In this case, the Get-Random cmdlet generates a random number between 0 and 100 and saves it in the $random variable. The source identifier of the event is Timer.Random. When you use an Action parameter in a Register-ObjectEvent command, the com mand returns a PSEventJob object that represents the action. The fourth command enables the timer. The fifth command uses the Get-EventSubscriber cmdlet to get the event subs criber of the Timer.Random event. It saves the event subscriber object in t he $subscriber variable. The sixth command shows that the Action property of the event subscriber ob ject contains a PSEventJob object. In fact, it contains the same PSEventJob object that the Register-ObjectEvent command returned. The seventh command uses the Format-List cmdlet to display all of the prope rties of the PSEventJob object in the Action property in a list. The result reveal that the PSEventJob object has a Module property that contains a dy namic script module that implements the action. The remaining commands use the call operator (&) to invoke the command in t he module and display the value of the $random variable. You can use the ca ll operator to invoke any command in a module, including commands that are not exported. In this case, the commands show the random number that is bei ng generated when the Elapsed event occurs. For more information about modules, see about_Modules. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135155 Register-ObjectEvent Register-EngineEvent Register-WmiEvent Unregister-Event Get-Event New-Event Remove-Event Wait-Event Get-ExecutionPolicy NAME Get-ExecutionPolicy SYNOPSIS Gets the execution policies for the current session. SYNTAX Get-ExecutionPolicy [[-Scope] {Process | CurrentUser | LocalMachine | UserP olicy | MachinePolicy}] [-List] [<CommonParameters>] DESCRIPTION The Get-ExecutionPolicy cmdlet gets the execution policies for the current session. The execution policy is determined by execution policies that you set by us ing Set-ExecutionPolicy and the Group Policy settings for the Windows Power Shell execution policy. The default value is "Restricted." Without parameters, Get-ExecutionPolicy gets the execution policy that is e ffective in the session. You can use the List parameter to get all executio n policies that affect the session or the Scope parameter to get the execut ion policy for a particular scope. For more information, see about_Execution_Policies. PARAMETERS -List [<SwitchParameter>] Gets all execution policy values for the session listed in precedence o rder. By default, Get-ExecutionPolicy gets only the effective executio n policy. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Scope <ExecutionPolicyScope> Gets the execution policy in the specified scope. By default, Get-Exec utionPolicy gets the effective execution policy for the current session . Valid values are: -- MachinePolicy: The execution policy set by a Group Policy for all us ers of the computer. -- UserPolicy: The execution policy set by a Group Policy for the curre nt user of the computer. -- Process: The execution policy that is set for the current Windows Po werShell process. -- CurrentUser: The execution policy that is set for the current user. -- LocalMachine: The execution policy that is set for all users of the computer. Required? false Position? 1 Default value Effective execution policy Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS Microsoft.PowerShell.ExecutionPolicy Get-ExecutionPolicy returns an object for each execution policy that it gets. NOTES You cannot use Get-ExecutionPolicy to get particular execution policies set for a particular scope or to get the execution policy set by a Gro up Policy. Get-ExecutionPolicy only gets the effective execution policy that results from applying all precedence rules. The execution policy is part of the security strategy of Windows PowerS hell. It determines whether you can load configuration files (including your Windows PowerShell profile) and run scripts, and it determines wh ich scripts, if any, must be digitally signed before they will run. The effective execution policy is determined by the policies that you s et by using Set-ExecutionPolicy and the "Turn on Script Execution" grou p policies for computers and users. The precedence order is Computer Gr oup Policy > User Group Policy > Process (session) execution policy > U ser execution policy > Computer execution policy. For more information about Windows PowerShell execution policy, includi ng definitions of the Windows PowerShell policies, see about_Execution_ Policies. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-executionpolicy Restricted Description ----------- This command gets the current execution policy for the shell. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-executionpolicy RemoteSigned; get-executionPolicy RemoteSigned Description ----------- These commands set a new user preference for the shell execution policy and then display the effective execution policy. The commands are separated by a semicolon (;). In this example, because there is no Group Policy setting , the user preference is the effective policy for the shell. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-executionpolicy -list Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser AllSigned LocalMachine RemoteSigned C:\PS> get-executionpolicy AllSigned Description ----------- These commands get all execution policies in the current session and the ef fective execution policy. The first command gets all execution policies that affect the current sessi on. The policies are listed in precedence order. The second command gets only the effective execution policy, which is the o ne set in the CurrentUser scope. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113315 Set-ExecutionPolicy Get-AuthenticodeSignature Set-AuthenticodeSignature about_Execution_Policies about_Signing Get-FormatData NAME Get-FormatData SYNOPSIS Gets the formatting data in the current session. SYNTAX Get-FormatData [[-TypeName] <string[]>] [<CommonParameters>] DESCRIPTION The Get-FormatData cmdlet gets the formatting data in the current session. The formatting data in the session includes formatting data from Format.ps1 xml formatting files (such as those in the $pshome directory), formatting d ata for modules that you import into the session, and formatting data for c ommands that you import into your session by using the Import-PSSession cmd let. You can use this cmdlet to examine the formatting data. Then, you can use t he Export-FormatData cmdlet to serialize the objects (convert them to XML) and save them in Format.ps1xml files. For more information about formatting files in Windows PowerShell, see abou t_Format.ps1xml. PARAMETERS -TypeName <string[]> Gets only the formatting data with the specified type names. Enter the type names. Wildcards are permitted. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? true <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.ExtendedTypeDefinition NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-formatdata Description ----------- This command gets all the formatting data in the session. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-formatdata -typename Microsoft.Wsman* Description ----------- This command gets the formatting data items whose names begin with "Microso ft.Wsman". -------------------------- EXAMPLE 3 -------------------------- C:\PS>$f = get-formatdata -typename helpinfoshort C:\PS> $f TypeName FormatViewDefinition -------- -------------------- HelpInfoShort {help , TableControl} C:\PS> $f.FormatViewDefinition[0].control Headers Rows ------- ---- {System.Management.Automation.TableControlColumnHeader, System.Manageme... {System.Management.Automation.TableControlRow} C:\PS> $f.FormatViewDefinition[0].control.headers Label Alignment Width ----- --------- ----- Name Left 33 Category Left 9 Undefined 0 Description ----------- This example shows how to get a formatting data object and examine its prop erties. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$a = get-formatdata C:\PS> import-module bitstransfer C:\PS> $b = get-formatdata C:\PS> compare-object $a $b InputObject SideIndicator ----------- ------------- Microsoft.BackgroundIntelligentTransfer.Management.BitsJob => C:\PS> get-formatdata *bits* | export-formatdata -filepath c:\test\bits.for mat.ps1xml C:\PS> get-content c:\test\bits.format.ps1xml <?xml version="1.0" encoding="utf-8"?><Configuration><ViewDefinitions> <View><Name>Microsoft.BackgroundIntelligentTransfer.Management.BitsJob</Nam e> ... Description ----------- This example shows how to use Get-FormatData and Export-FormatData to expor t the formatting data that is added by a module. The first four commands use the Get-FormatData, Import-Module, and Compare- Object cmdlets to identify the format type that the BitsTransfer module add s to the session. The fifth command uses the Get-FormatData cmdlet to get the format type tha t the BitsTransfer module adds. It uses a pipeline operator (|) to send the format type object to the Export-FormatData cmdlet, which converts it back to XML and saves it in the specified format.ps1xml file. The final command shows an excerpt of the format.ps1xml file content. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144303 Export-FormatData Update-FormatData Get-Help NAME Get-Help SYNOPSIS Displays information about Windows PowerShell commands and concepts. SYNTAX Get-Help [-Full] [[-Name] <string>] [-Category <string[]>] [-Component <str ing[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role <stri ng[]>] [<CommonParameters>] Get-Help [-Detailed] [[-Name] <string>] [-Category <string[]>] [-Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role string[]>] [<CommonParameters>] Get-Help [-Examples] [[-Name] <string>] [-Category <string[]>] [-Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role string[]>] [<CommonParameters>] Get-Help [-Parameter <string>] [[-Name] <string>] [-Category <string[]>] [- Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string> ] [-Role <string[]>] [<CommonParameters>] DESCRIPTION The Get-Help cmdlet displays information about Windows PowerShell concepts and commands, including cmdlets, providers, functions and scripts. To get a list of all cmdlet help topic titles, type "get-help *". If you type "Get-Help" followed by the exact name of a help topic, or by a word unique to a help topic, Get-Help displays the topic contents. If you e nter a word or word pattern that appears in several help topic titles, Get- Help displays a list of the matching titles. If you enter a word that does not appear in any help topic titles, Get-Help displays a list of topics tha t include that word in their contents. In addition to "get-help", you can also type "help" or "man", which display s one screen of text at a time, or "<cmdlet-name> -?", which is identical t o Get-Help but works only for cmdlets. You can display the entire help file or selected parts of the file, such as the syntax, parameters, or examples. You can also use the Online parameter to display an online version of a help file in your Internet browser. Thes e parameters have no effect on conceptual help topics. Conceptual help topics in Windows PowerShell begin with "about_", such as " about_Comparison_Operators". To see all "about_" topics, type "get-help abo ut_*". To see a particular topic, type "get-help about_<topic-name>", such as "get-help about_Comparison_Operators". PARAMETERS -Category <string[]> Displays help for items in the specified category. Valid values are Ali as, Cmdlet, Provider, and HelpFile. Conceptual topics are in the HelpFi le category. Category is a property of the MamlCommandHelpInfo object that Get-Help returns. This parameter has no effect on displays of conceptual ("about _") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Component <string[]> Displays a list of tools with the specified component value, such as "E xchange." Enter a component name. Wildcards are permitted. Component is a property of the MamlCommandHelpInfo object that Get-Help returns. This parameter has no effect on displays of conceptual ("Abou t_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Detailed [<SwitchParameter>] Adds parameter descriptions and examples to the basic help display. This parameter has no effect on displays of conceptual ("About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Examples [<SwitchParameter>] Displays only the name, synopsis, and examples. To display only the exa mples, type "(get-help <cmdlet-name>).examples". This parameter has no effect on displays of conceptual ("About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Full [<SwitchParameter>] Displays the entire help file for a cmdlet, including parameter descrip tions and attributes, examples, input and output object types, and addi tional notes. This parameter has no effect on displays of conceptual ("About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Functionality <string[]> Displays help for items with the specified functionality. Enter the fun ctionality. Wildcards are permitted. Functionality is a property of the MamlCommandHelpInfo object that Get- Help returns. This parameter has no effect on displays of conceptual (" About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Requests help about the specified tool or conceptual topic. Enter a cmd let, provider, script, or function name, such as Get-Member, a conceptu al topic name, such as "about_Objects", or an alias, such as "ls". Wild cards are permitted in cmdlet and provider names, but you cannot use wi ldcards to find the names of function help and script help topics. To get help for a script that is not located in a path that is listed i n the Path environment variable, type the path and file name of the scr ipt . If you enter the exact name of a help topic, Get-Help displays the topi c contents. If you enter a word or word pattern that appears in several help topic titles, Get-Help displays a list of the matching titles. If you enter a word that does not match any help topic titles, Get-Help d isplays a list of topics that include that word in their contents. The names of conceptual topics, such as about_Objects, must be entered in English, even in non-English versions of Windows PowerShell. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Online [<SwitchParameter>] Displays the online version of a help topic in the default Internet bro wser. This parameter is valid only for cmdlet, function, and script hel p topics. Get-Help uses the Internet address (Uniform Resource Identifier [URI]) that appears in the first item of the Related Links section of a cmdlet , function, or script help topic. This parameter works only when the he lp topic includes a URI that begins with "Http" or "Https" and an Inter net browser is installed on the system. For information about supporting this feature in help topics that you w rite, see about_Comment_Based_Help, and see "How to Write Cmdlet Help" in the MSDN (Microsoft Developer Network) library at http://go.microsof t.com/fwlink/?LinkID=123415. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Parameter <string> Displays only the detailed descriptions of the specified parameters. Wi ldcards are permitted. This parameter has no effect on displays of conceptual ("About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Gets help that explains how the cmdlet works in the specified provider path. Enter a Windows PowerShell provider path. This parameter gets a customized version of a cmdlet help topic that ex plains how the cmdlet works in the specified Windows PowerShell provide r path. This parameter is effective only for help about a provider cmdl et and only when the provider includes a custom version of the provider cmdlet help topic. To see the custom cmdlet help for a provider path, go to the provider p ath location and enter a Get-Help command or, from any path location, u se the Path parameter of Get-Help to specify the provider path. For mor e information, see about_Providers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Role <string[]> Displays help customized for the specified user role. Enter a role. Wil dcards are permitted. Enter the role that the user plays in an organization. Some cmdlets dis play different text in their help files based on the value of this para meter. This parameter has no effect on help for the core cmdlets. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS System.String or MamlCommandHelpInfo If you request a conceptual topic, Get-Help returns it as a string. If you specify the name of a cmdlet,, function, or script, it returns a Ma mlCommandHelpInfo object. Otherwise, Get-Help returns one of the format ted views that are specified in the Help.Format.ps1xml file in the $psh ome directory. NOTES Without parameters, "Get-Help" displays information about the Windows P owerShell help system. The full view of help (-full) includes a table of information about the parameters. The table includes the following fields: -- Required: Indicates whether the parameter is required (true) or opt ional (false). -- Position: Indicates whether the parameter is named or positional (n umbered). Positional parameters must appear in a specified place in the command. -- "Named" indicates that the parameter name is required, but that the parameter can appear anywhere in the command. -- <Number> indicates that the parameter name is optional, but when the name is omitted, the parameter must be in the place specified by the n umber. For example, "2" indicates that when the parameter name is omitt ed, the parameter must be the second (2) or only unnamed parameter in t he command. When the parameter name is used, the parameter can appear a nywhere in the command. -- Default value: The parameter value that Windows PowerShell uses if y ou do not include the parameter in the command. -- Accepts pipeline input: Indicates whether you can (true) or cannot ( false) send objects to the parameter through a pipeline. "By Property N ame" means that the pipelined object must have a property with the same name as the parameter name. -- Accepts wildcard characters: Indicates whether the value of a parame ter can include wildcard characters, such as * and ?. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-help Description ----------- This command displays help about the Windows PowerShell help system. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-help * Description ----------- This command displays a list of all help files in the Windows PowerShell he lp system. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-help get-alias C:\PS>help get-alias C:\PS>get-alias -? Description ----------- These commands display basic information about the get-alias cmdlet. The "G et-Help" and "-?" commands display the information on a single page. The "H elp" command displays the information one page at a time. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-help about_* Description ----------- This command displays a list of the conceptual topics included in Windows P owerShell help. All of these topics begin with the characters "about_". To display a particular help file, type "get-help <topic-name>, for example, " get-help about_signing". -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-help ls -detailed Description ----------- This command displays detailed help for the Get-ChildItem cmdlet by specify ing one of its aliases, "ls." The Detailed parameter requests the detailed view of the help file, which includes parameter descriptions and examples. To see the complete help file for a cmdlet, use the Full parameter. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-help format-string -full Description ----------- This command displays the full view help for the Format-String cmdlet. The full view of help includes parameter descriptions, examples, and a table of technical details about the parameters. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-help start-service -examples Description ----------- This command displays examples of using start-service in Windows PowerShell commands. -------------------------- EXAMPLE 8 -------------------------- C:\PS>get-help get-childitem -parameter f* Description ----------- This command displays descriptions of the parameters of the Get-ChildItem c mdlet that begin with "f" (filter and force). For descriptions of all param eters, type "get-help get-childitem parameter*". -------------------------- EXAMPLE 9 -------------------------- C:\PS>(get-help write-output).syntax Description ----------- This command displays only the syntax of the Write-Output cmdlet. Syntax is one of many properties of help objects; others are description, d etails, examples, and parameters. To find all properties and methods of hel p objects, type "get-help <cmdlet-name> | get-member"; for example, "get-he lp start-service | get member". -------------------------- EXAMPLE 10 -------------------------- C:\PS>(get-help trace-command).alertset Description ----------- This command displays the notes about the cmdlet. The notes are stored in t he alertSet property of the help object. The notes include conceptual information and tips for using the cmdlet. By default, the notes are displayed only when you use the Full parameter of Ge t-Help, but you can also display them by using the alertSet property. -------------------------- EXAMPLE 11 -------------------------- C:\PS>get-help add-member -full | out-string -stream | select-string -patte rn clixml Description ----------- This example shows how to search for a word in particular cmdlet help topic . This command searches for the word "clixml" in the full version of the he lp topic for the Add-Member cmdlet. Because the Get-Help cmdlet generates a MamlCommandHelpInfo object, not a s tring, you need to use a command that transforms the help topic content int o a string, such as Out-String or Out-File. -------------------------- EXAMPLE 12 -------------------------- C:\PS>get-help get-member -online Description ----------- This command displays the online version of the help topic for the Get-Memb er cmdlet. -------------------------- EXAMPLE 13 -------------------------- C:\PS>get-help remoting Description ----------- This command displays a list of topics that include the word "remoting" in their contents. When you enter a word that does not appear in any topic title, Get-Help dis plays a list of topics that include that word. -------------------------- EXAMPLE 14 -------------------------- C:\PS>get-help get-item -path SQLSERVER:\DataCollection NAME Get-Item SYNOPSIS Gets a collection of Server objects for the local computer and any comp uters to which you have made a SQL Server PowerShell connection. ... C:\PS> cd SQLSERVER:\DataCollection C:\PS> SQLSERVER:\DataCollection> get-help get-item NAME Get-Item SYNOPSIS Gets a collection of Server objects for the local computer and any comp uters to which you have made a SQL Server PowerShell connection. ... C:\PS> Get-Item NAME Get-Item SYNOPSIS Gets the item at the specified location. ... Description ----------- This example shows how to get help for the Get-Item cmdlet that explains ho w to use the cmdlet in the DataCollection node of the Windows PowerShell SQ L Server provider. The example shows two ways of getting the custom help for Get-Item. The first command uses the Path parameter of Get-Help to specify the provid er path. This command can be entered at any path location. The second command uses the Set-Location cmdlet (alias = "cd") to go to the provider path. From that location, even without the Path parameter, the Ge t-Help command gets the custom help for the provider path. The third command shows that a Get-Help command in a file system path, and without the Path parameter, gets the standard help for the Get-Item cmdlet. -------------------------- EXAMPLE 15 -------------------------- C:\PS>get-help c:\ps-test\MyScript.ps1 Description ----------- This command gets help for the MyScript.ps1 script. For information about w riting help for your functions and scripts, see about_Comment_Based_Help. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113316 about_Comment_Based_Help Get-Command Get-PSDrive Get-Member Get-History NAME Get-History SYNOPSIS Gets a list of the commands entered during the current session. SYNTAX Get-History [[-Id] <Int64[]>] [[-Count] <int>] [<CommonParameters>] DESCRIPTION The Get-History cmdlet gets the session history, that is, the list of comma nds entered during the current session. Windows PowerShell automatically ma intains a history of each session. You can save the session history in XML or CSV format. By default, history files are saved in the home directory, b ut you can save the file in any location. PARAMETERS -Count <int> Displays the specified number of the most recent history entries. The d efault is 32. If you use both the Count and Id parameters in a command, the display ends with the command specified by the Id parameter. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Id <Int64[]> Specifies the ID number of a command in the session history. Get-Histor y gets only the specified command. If you use Id and Count, Get-History gets the most recent commands ending with the command specified by the Id parameter. Required? false Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS Int64 You can pipe a history ID to Get-History. OUTPUTS Microsoft.PowerShell.Commands.HistoryInfo Get-History returns a history object for each history item that it gets . NOTES The session history is a list of the commands entered during the sessio n along with the ID. The session history represents the order of execut ion, the status, and the start and end times of the command. As you ent er each command, Windows PowerShell adds it to the history so that you can reuse it. For more information about the command history, see about _History. You can also refer to Get-History by its built-in aliases, "h", "histor y", and "ghy". For more information, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-history Description ----------- This command gets the 32 most recently submitted commands. The default disp lay shows each command and its ID, which indicates the order of execution. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-history | where-object {$_.commandLine -like "*service*"} Description ----------- This command gets entries from the command history that include the word, " service". The first command gets the 32 most recent entries in the session history. The pipeline operator (|) passes the results to the Where-Object c mdlet, which selects only the commands that include "service". -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-history -id 7 -count 5 | export-csv history.csv Description ----------- This command gets the five most recent history entries ending with entry 7. The pipeline operator (|) passes the result to the Export-Csv cmdlet, whic h formats the history as comma-separated text and saves it in the History.c sv file. The file includes the data that is displayed when you format the h istory as a list, including the status and start and end times of the comma nd. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-history -count 1 Description ----------- This command gets the last (most recently entered) command in the command h istory. It uses the Count parameter to display just one command. By default , Get-History displays the most recent commands. This command can be abbrev iated to "h -c 1" and is equivalent to pressing the up-arrow key. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-history -count $MaximumHistoryCount Description ----------- This command displays all of the commands saved in the session history. By default, $MaximumHistoryCount is 64, so this command can be abbreviated as "h -c 64". -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-history | format-list Description ----------- This command displays all of the properties of entries in the session histo ry. The pipeline operator (|) passes the result to the Format-List cmdlet, which displays all of the properties of each history entry, including the I D, status, and start and end times of the command. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113317 about_history Invoke-History Add-History Clear-History Get-Host NAME Get-Host SYNOPSIS Gets an object that represents the current host program. And, displays Wind ows PowerShell version and regional information by default. SYNTAX Get-Host [<CommonParameters>] DESCRIPTION The Get-Host cmdlet gets an object that represents the program that is host ing Windows PowerShell. The default display includes the Windows PowerShell version number and the current region and language settings that the host is using, but the host o bject contains a wealth of information, including detailed information abou t the version of Windows PowerShell that is currently running and the curre nt culture and UI culture of Windows PowerShell. You can also use this cmd let to customize features of the host program user interface, such as the t ext and background colors. PARAMETERS <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.Internal.Host.InternalHost Get-Host returns a System.Management.Automation.Internal.Host.InternalH ost object. NOTES The $host automatic variable contains the same object that Get-Host ret urns, and you can use it in the same way. Similarly, the $PSCulture an d $PSUICulture automatic variables contain the same objects that the Cu rrentCulture and CurrentUICulture properties of the host object contain . You can use these features interchangeably. For more information, see about_Automatic_Variables. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-host Name : ConsoleHost Version : 2.0 InstanceId : e4e0ab54-cc5e-4261-9117-4081f20ce7a2 UI : System.Management.Automation.Internal.Host.InternalHostU serInterface CurrentCulture : en-US CurrentUICulture : en-US PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy IsRunspacePushed : False Runspace : System.Management.Automation.Runspaces.LocalRunspace Description ----------- This command displays information about the Windows PowerShell console, whi ch is the current host program for Windows PowerShell in this example. It i ncludes the name of the host, the version of Windows PowerShell that is run ning in the host, and current culture and UI culture. The Version, UI, CurrentCulture, CurrentUICulture, PrivateData, and Runspac e properties each contain an object with very useful properties. Later exam ples examine these properties. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$h = get-host C:\PS> $win = $h.ui.rawui.windowsize C:\PS> $win.height = 10 C:\PS> $win.width = 10 C:\PS> $h.ui.rawui.set_windowsize($win) Description ----------- This command resizes the Windows PowerShell window to 10 pixels by 10 pixel s. -------------------------- EXAMPLE 3 -------------------------- C:\PS>(get-host).version | format-list -property * Major : 2 Minor : 0 Build : -1 Revision : -1 MajorRevision : -1 MinorRevision : -1 Description ----------- This command gets detailed information about the version of Windows PowerSh ell running in the host. You can view, but not change, these values. The Version property of Get-Host contains a System.Version object. This com mand uses a pipeline operator (|) to send the version object to the Format- List cmdlet. The Format-List command uses the Property parameter with a val ue of all (*) to display all of the properties and property values of the v ersion object. -------------------------- EXAMPLE 4 -------------------------- C:\PS>(get-host).currentculture | format-list -property * Parent : en LCID : 1033 KeyboardLayoutId : 1033 Name : en-US IetfLanguageTag : en-US DisplayName : English (United States) NativeName : English (United States) EnglishName : English (United States) TwoLetterISOLanguageName : en ThreeLetterISOLanguageName : eng ThreeLetterWindowsLanguageName : ENU CompareInfo : CompareInfo - 1033 TextInfo : TextInfo - 1033 IsNeutralCulture : False CultureTypes : SpecificCultures, InstalledWin32Cultures, FrameworkCultures NumberFormat : System.Globalization.NumberFormatInfo DateTimeFormat : System.Globalization.DateTimeFormatInfo Calendar : System.Globalization.GregorianCalendar OptionalCalendars : {System.Globalization.GregorianCalendar, S ystem.Globalization.GregorianCalendar} UseUserOverride : True IsReadOnly : False Description ----------- This command gets detailed information about the current culture set for Wi ndows PowerShell running in the host. This is the same information that is returned by the Get-Culture cmdlet. (Similarly, the CurrentUICulture property returns the same object that Get- UICulture returns.) The CurrentCulture property of the host object contains a System.Globaliza tion.CultureInfo object. This command uses a pipeline operator (|) to send the CultureInfo object to the Format-List cmdlet. The Format-List command u ses the Property parameter with a value of all (*) to display all of the pr operties and property values of the CultureInfo object. -------------------------- EXAMPLE 5 -------------------------- C:\PS>(get-host).currentculture.DateTimeFormat | format-list -property * AMDesignator : AM Calendar : System.Globalization.GregorianCalendar DateSeparator : / FirstDayOfWeek : Sunday CalendarWeekRule : FirstDay FullDateTimePattern : dddd, MMMM dd, yyyy h:mm:ss tt LongDatePattern : dddd, MMMM dd, yyyy LongTimePattern : h:mm:ss tt MonthDayPattern : MMMM dd PMDesignator : PM RFC1123Pattern : ddd, dd MMM yyyy HH':'mm':'ss 'GMT' ShortDatePattern : M/d/yyyy ShortTimePattern : h:mm tt SortableDateTimePattern : yyyy'-'MM'-'dd'T'HH':'mm':'ss TimeSeparator : : UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z' YearMonthPattern : MMMM, yyyy AbbreviatedDayNames : {Sun, Mon, Tue, Wed...} ShortestDayNames : {Su, Mo, Tu, We...} DayNames : {Sunday, Monday, Tuesday, Wednesday...} AbbreviatedMonthNames : {Jan, Feb, Mar, Apr...} MonthNames : {January, February, March, April...} IsReadOnly : False NativeCalendarName : Gregorian Calendar AbbreviatedMonthGenitiveNames : {Jan, Feb, Mar, Apr...} MonthGenitiveNames : {January, February, March, April...} Description ----------- This command returns detailed information about the DateTimeFormat of the c urrent culture that is being used for Windows PowerShell. The CurrentCulture property of the host object contains a CultureInfo objec t that, in turn, has many useful properties. Among them, the DateTimeFormat property contains a DateTimeFormatInfo object with many useful properties. To find the type of an object that is stored in an object property, use the Get-Member cmdlet. To display the property values of the object, use the F ormat-List cmdlet. -------------------------- EXAMPLE 6 -------------------------- C:\PS>(get-host).ui.rawui | format-list -property * ForegroundColor : DarkYellow BackgroundColor : DarkBlue CursorPosition : 0,390 WindowPosition : 0,341 CursorSize : 25 BufferSize : 120,3000 WindowSize : 120,50 MaxWindowSize : 120,81 MaxPhysicalWindowSize : 182,81 KeyAvailable : False WindowTitle : Windows PowerShell 2.0 (04/11/2008 00:08:14) Description ----------- This command displays the properties of the RawUI property of the host obje ct. By changing these values, you can change the appearance of the host pro gram. -------------------------- EXAMPLE 7 -------------------------- C:\PS>(get-host).ui.rawui.backgroundcolor = "Black" C:\PS> cls Description ----------- These commands change the background color of the Windows PowerShell consol e to black. The "cls" command is an alias for the Clear-Host function, whic h clears the screen and changes the whole screen to the new color. This change is effective only in the current session. To change the backgro und color of the console for all sessions, add the command to your Windows PowerShell profile. -------------------------- EXAMPLE 8 -------------------------- C:\PS>$host.privatedata.errorbackgroundcolor = "white" Description ----------- This command changes the background color of error messages to white. This command uses the $host automatic variable, which contains the host obj ect for the current host program. Get-Host returns the same object that $ho st contains, so you can use them interchangeably. This command uses the PrivateData property of $host as its ErrorBackgroundC olor property. To see all of the properties of the object in the $host.priv atedata property, type "$host.privatedata | format-list * ". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113318 Read-Host Out-Host Write-Host Get-HotFix NAME Get-HotFix SYNOPSIS Gets the hotfixes that have been applied to the local and remote computers. SYNTAX Get-HotFix [[-Id] <string[]>] [-ComputerName <string[]>] [-Credential <PSCr edential>] [<CommonParameters>] Get-HotFix [-Description <string[]>] [-ComputerName <string[]>] [-Credentia l <PSCredential>] [<CommonParameters>] DESCRIPTION The Get-Hotfix cmdlet gets the hotfixes that have been applied to the local computer or to remote computers by Component-Based Servicing. PARAMETERS -ComputerName <string[]> Specifies a remote computer. The default is the local computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qu alified domain name of a remote computer. This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Get-Hotfix even if your computer is not configured to run remote commands. Required? false Position? named Default value Local computer Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. Required? false Position? named Default value Current user Accept pipeline input? false Accept wildcard characters? false -Description <string[]> Gets only hotfixes with the specified descriptions. Wildcards are permi tted. The default is all hotfixes on the computer. Required? false Position? named Default value All hotfixes Accept pipeline input? false Accept wildcard characters? true -Id <string[]> Gets only hotfixes with the specified hotfix IDs. The default is all ho tfixes on the computer. Required? false Position? 1 Default value All hotfixes Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to Get-HotFix. OUTPUTS System.Management.ManagementObject#root\CIMV2\Win32_QuickFixEngineering Get-Hotfix returns objects that represent the hotfixes on the computer. NOTES This cmdlet uses the Win32_QuickFixEngineering WMI class, which represe nts small system-wide updates of the operating system. Starting with Wi ndows Vista, this class returns only the updates supplied by Component Based Servicing (CBS). It does not include updates that are supplied by Microsoft Windows Installer (MSI) or the Windows update site. For more information, see the Win32_QuickFixEngineering class topic in the Micr osoft .NET Framework SDK at http://go.microsoft.com/fwlink/?LinkID=1450 71. The output of this cmdlet might be different on different operating sys tems. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-hotfix Description ----------- This command gets all hotfixes on the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-hotfix -description Security* -computername Server01, Server02 -c red Server01\admin01 Description ----------- This command gets all hotfixes on the Server01 and Server02 computers that have a description that begins with "Security". -------------------------- EXAMPLE 3 -------------------------- C:\PS>$a = get-content servers.txt C:\PS> $a | foreach { if ((get-hotfix -id KB957095 -computername $_)) { ad d-content $_ -path Missing-kb953631.txt }} Description ----------- The commands in this example create a text file listing the names of comput ers that are missing a security update. The commands use the Get-Hotfix cmdlet to get the KB957095 security update on all of the computers whose names are listed in the Servers.txt file. If a computer does not have the update, the Add-Content cmdlet writes the c omputer name in the Missing-KB953631.txt file. -------------------------- EXAMPLE 4 -------------------------- C:\PS>(get-hotfix | sort installedon)[-1] Description ----------- This command gets the most recent hotfix on the computer. It gets the hotfixes, sorts them by the value of the InstalledOn property, and then it uses array notation to select the last item in the array. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135217 Get-ComputerRestorePoint Get-Item NAME Get-Item SYNOPSIS Gets the item at the specified location. SYNTAX Get-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-UseTransacti on] [<CommonParameters>] Get-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string[ ]>] [-Filter <string>] [-Force] [-Include <string[]>] [-UseTransaction] [<C ommonParameters>] DESCRIPTION The Get-Item cmdlet gets the item at the specified location. It does not ge t the contents of the item at the location unless you use a wildcard charac ter (*) to request all the contents of the item. The Get-Item cmdlet is used by Windows PowerShell providers to enable you t o navigate through different types of data stores. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user-name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. The Exclude parameter is effective only when the command includes the c ontents of an item, such as C:\Windows\*, where the wildcard character specifies the contents of the C:\Windows directory. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to get items that cannot otherwise be accessed, such as hidden items. Implementation varies from provider to provider. For m ore information, see about_Providers. Even using the Force parameter, t he cmdlet cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Retrieves only the specified items. The value of this parameter qualifi es the Path parameter. Enter a path element or pattern, such as "*.txt" . Wildcards are permitted. The Include parameter is effective only when the command includes the c ontents of an item, such as C:\Windows\*, where the wildcard character specifies the contents of the C:\Windows directory. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the item. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards . If the path includes escape characters, enclose it in single quotatio n marks. Single quotation marks tell Windows PowerShell not to interpre t any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the path to an item. Get-Item gets the item at the specified location. Wildcards are permitted. This parameter is required, but the parameter name ("Path") is optional. Use a dot (.) to specify the current location. Use the wildcard charact er (*) to specify all the items in the current location. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Get-Item. OUTPUTS Object Get-Item returns the objects that it gets. The type is determined by th e type of objects in the path. NOTES You can also refer to Get-Item by its built-in alias, "gi". For more in formation, see about_Aliases. Get-Item does not have a Recurse parameter, because it gets only an ite m, not its contents. To get the contents of an item recursively, use Ge t-ChildItem. To navigate through the registry, use Get-Item to get registry keys and Get-ItemProperty to get registry values and data. The registry values are considered to be properties of the registry key. The Get-Item cmdlet is designed to work with the data exposed by any pr ovider. To list the providers available in your session, type "Get-PsPr ovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-item . Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 7/26/2006 10:01 AM ps-test Description ----------- This command gets the current directory. The dot (.) represents the item at the current location (not its contents). -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-item * Directory: C:\ps-test Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 7/26/2006 9:29 AM Logs d---- 7/26/2006 9:26 AM Recs -a--- 7/26/2006 9:28 AM 80 date.csv -a--- 7/26/2006 10:01 AM 30 filenoext -a--- 7/26/2006 9:30 AM 11472 process.doc -a--- 7/14/2006 10:47 AM 30 test.txt Description ----------- This command gets all the items in the current directory. The wildcard char acter (*) represents all the contents of the current item. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-item C:\ Description ----------- This command gets the current directory of the C: drive. The object that is retrieved represents only the directory, not its contents. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-item C:\* Description ----------- This command gets the items in the C: drive. The wildcard character (*) rep resents all the items in the container, not just the container. In Windows PowerShell, use a single asterisk (*) to get contents, instead o f the traditional "*.*". The format is interpreted literally, so "*.*" woul d not retrieve directories or file names without a dot. -------------------------- EXAMPLE 5 -------------------------- C:\PS>(get-item C:\Windows).LastAccessTime Description ----------- This command gets the LastAccessTime property of the C:\Windows directory. LastAccessTime is just one property of file system directories. To see all of the properties of a directory, type "(Get-Item <directory-name>) | Get-M ember". -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-item hklm:\software\microsoft\powershell\1\shellids\microsoft.pow ershell\* Description ----------- This command shows the contents of the Microsoft.PowerShell registry key. Y ou can use Get-Item with the Windows PowerShell Registry provider to get re gistry keys and subkeys, but you must use Get-ItemProperty to get the regis try values and data. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-item c:\Windows\* -include *.* -exclude w* Description ----------- This command gets items in the Windows directory with names that include a dot (.), but do not begin with w*. This command works only when the path in cludes a wildcard character (*) to specify the contents of the item. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113319 about_Providers Clear-Item Copy-Item Invoke-Item Move-Item Set-Item New-Item Remove-Item Rename-Item Get-ItemProperty NAME Get-ItemProperty SYNOPSIS Gets the properties of a specified item. SYNTAX Get-ItemProperty [-LiteralPath] <string[]> [[-Name] <string[]>] [-Credentia l <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include g[]>] [-UseTransaction] [<CommonParameters>] Get-ItemProperty [-Path] <string[]> [[-Name] <string[]>] [-Credential <PSCr edential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [ -UseTransaction] [<CommonParameters>] DESCRIPTION The Get-ItemProperty cmdlet gets the properties of the specified items. For example, you can use Get-ItemProperty to get the value of the LastAccessTi me property of a file object. You can also use Get-ItemProperty to view reg istry entries and their values. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Includes the specified items. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation ma rks. Single quotation marks tell Windows PowerShell not to interpret an y characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Specifies the name of the property or properties to retrieve. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the item or items. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Get-ItemProperty. OUTPUTS Object Get-ItemProperty returns an object for each item property that it gets. The object type depends on the object that is retrieved. NOTES The Get-ItemProperty cmdlet is designed to work with the data exposed b y any provider. To list the providers available in your session, type " Get-PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-itemproperty C:\Windows Description ----------- This command gets information about the C:\Windows directory. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-itemproperty C:\Test\Weather.xls | format-list Description ----------- This command gets the properties of the C:\Test\Weather.xls file. The resul t is piped to the Format-List cmdlet to display the output as a list. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersio n Description ----------- This command displays the value name and data of each of the registry entri es contained in the CurrentVersion registry subkey. Note that the command r equires that there is a Windows PowerShell drive named HKLM: that is mapped to the HKEY_LOCAL_MACHINE hive of the registry. A drive with that name and mapping is available in Windows PowerShell by default. Alternatively, the path to this registry subkey can be specified by using the following altern ative path that begins with the provider name followed by two colons: Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersio n ` -name "ProgramFilesDir" Description ----------- This command gets the value name and data of the ProgramFilesDir registry e ntry in the CurrentVersion registry subkey. The command uses the Path param eter to specify the subkey and the Name parameter to specify the value name of the entry. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShe llEngine ApplicationBase : C:\Windows\system32\WindowsPowerShell\v1.0\ ConsoleHostAssemblyName : Microsoft.PowerShell.ConsoleHost, Version=1.0.0.0 , Culture=neutral, PublicKeyToken=31bf3856ad 364e35, ProcessorArchitecture=msil PowerShellVersion : 2.0 RuntimeVersion : v2.0.50727 CTPVersion : 5 PSCompatibleVersion : 1.0,2.0 Description ----------- This command gets the value names and data of the registry entries in the PowerShellEngine registry key. The results are shown in the following sampl e output. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds \Microsoft.PowerShell Path ExecutionPolicy ---- --------------- C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe RemoteSigned C:\PS>get-itemproperty -path HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds \Microsoft.PowerShell | format-list -property * PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\So ftware\Microsoft\PowerShell\1\ShellIds\Micro soft.PowerShell PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\So ftware\Microsoft\PowerShell\1\ShellIds PSChildName : Microsoft.PowerShell PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry Path : C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe ExecutionPolicy : RemoteSigned Description ----------- This example shows how to format the output of a Get-ItemProperty command i n a list to make it easy to see the registry values and data and to make it easy to interpret the results. The first command uses the Get-ItemProperty cmdlet to get the registry entr ies in the Microsoft.PowerShell subkey. This subkey stores options for the default shell for Windows PowerShell. The results are shown in the followin g sample output. The output shows that there are two registry entries, Path and ExecutionPol icy. When a registry key contains fewer than five entries, by default it is displayed in a table, but it is often easier to view in a list. The second command uses the same Get-ItemProperty command. However, this ti me, the command uses a pipeline operator (|) to send the results of the com mand to the Format-List cmdlet. The Format-List command uses the Property p arameter with a value of * (all) to display all of the properties of the ob jects in a list. The results are shown in the following sample output. The resulting display shows the Path and ExecutionPolicy registry entries, along with several less familiar properties of the registry key object. The other properties, prefixed with "PS", are properties of Windows PowerShell custom objects, such as the objects that represent the registry keys. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113320 about_Providers Set-ItemProperty Clear-ItemProperty Copy-ItemProperty Move-ItemProperty New-ItemProperty Remove-ItemProperty Rename-ItemProperty Get-Job NAME Get-Job SYNOPSIS Gets Windows PowerShell background jobs that are running in the current ses sion. SYNTAX Get-Job [-Command <string[]>] [<CommonParameters>] Get-Job [[-InstanceId] <Guid[]>] [<CommonParameters>] Get-Job [[-Name] <string[]>] [<CommonParameters>] Get-Job [[-Id] <Int32[]>] [<CommonParameters>] Get-Job [-State {NotStarted | Running | Completed | Failed | Stopped | Bloc ked}] [<CommonParameters>] DESCRIPTION The Get-Job cmdlet gets objects that represent the background jobs that wer e started in the current session. You can use Get-Job to get jobs that were started by using Start-Job, or by using the AsJob parameter of any cmdlet. Without parameters, a "Get-Job" command gets all jobs in the current sessio n. You can use the parameters of Get-Job to get particular jobs. The job object that Get-Job returns contains useful information about the j ob, but it does not contain the job results. To get the results, use the Re ceive-Job cmdlet. A Windows PowerShell background job is a command that runs "in the backgrou nd" without interacting with the current session. Typically, you use a back ground job to run a complex command that takes a long time to complete. For more information about background jobs in Windows PowerShell, see about_Jo bs. PARAMETERS -Command <string[]> Gets the jobs that include the specified command. The default is all jo bs. Enter a command (as a string). You can use wildcards to specify a c ommand pattern. Required? false Position? named Default value All jobs Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Id <Int32[]> Gets only jobs with the specified IDs. The ID is an integer that uniquely identifies the job within the curren t session. It is easier to remember and to type than the instance ID, b ut it is unique only within the current session. You can type one or mo re IDs (separated by commas). To find the ID of a job, type "Get-Job" w ithout parameters. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InstanceId <Guid[]> Gets jobs with the specified instance IDs. The default is all jobs. An instance ID is a GUID that uniquely identifies the job on the comput er. To find the instance ID of a job, use Get-Job. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Name <string[]> Gets the job with the specified friendly names. Enter a job name, or us e wildcard characters to enter a job name pattern. By default, Get-Job gets all jobs in the current session. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -State <JobState> Gets only jobs in the specified state. Valid values are NotStarted, Run ning, Completed, Stopped, Failed, and Blocked. By default, Get-Job gets all the jobs in the current session. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.RemotingJob Get-Job returns objects that represent the jobs in the session. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-job Description ----------- This command gets all background jobs started in the current session. It do es not include jobs created in other sessions, even if the jobs run on the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$j = get-job -name Job1 C:\PS> $ID = $j.InstanceID C:\PS> $ID Guid ---- 03c3232e-1d23-453b-a6f4-ed73c9e29d55 C:\PS> stop-job -instanceid $ID Description ----------- These commands show how to get the instance ID of a job and then use it to stop a job. Unlike the name of a job, which is not unique, the instance ID is unique. The first command uses the Get-Job cmdlet to get a job. It uses the Name pa rameter to identify the job. The command stores the job object that Get-Job returns in the $j variable. In this example, there is only one job with th e specified name. The second command gets the InstanceId property of the object in the $j var iable and stores it in the $ID variable. The third command displays the value of the $ID variable. The fourth command uses Stop-Job cmdlet to stop the job. It uses the Instan ceId parameter to identify the job and $ID variable to represent the instan ce ID of the job. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-job -command "*get-process*" Description ----------- This command gets the jobs on the system that include a Get-Process command . The command uses the Command parameter of Get-Job to limit the jobs retri eved. The command uses wildcard characters (*) to get jobs that include a G et-Process command anywhere within the command string. -------------------------- EXAMPLE 4 -------------------------- C:\PS>"*get-process*" | get-job Description ----------- Like the command in the previous example, this command gets the jobs on th e system that include a Get-Process command. The command uses a pipeline op erator (|) to send a string (in double quotation marks) to the Get-Job cmdl et. It is the equivalent of the previous command. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-job -state NotStarted Description ----------- This command gets only those jobs that have been created but have not yet b een started. This includes jobs that are scheduled to run in the future and those not yet scheduled. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-job -name job* Description ----------- This command gets all jobs that have job names beginning with "job". Becaus e "job<number>" is the default name for a job, this command gets all jobs t hat do not have an explicitly assigned name. -------------------------- EXAMPLE 7 -------------------------- C:\PS>start-job -scriptblock {get-process} -name MyJob C:\PS> $j = get-job -name MyJob C:\PS> $j Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 myjob Completed True localhost get-process C:\PS> receive-job -job $j Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 124 4 13572 12080 59 1140 audiodg 783 16 11428 13636 100 548 CcmExec 96 4 4252 3764 59 3856 ccmsetup ... Description ----------- This example shows how to use Get-Job to get a job object, and then it show s how to use the job object to represent the job in a command. The first command uses the Start-Job cmdlet to start a background job that runs a Get-Process command on the local computer. The command uses the Name parameter of Start-Job to assign a friendly name to the job. The second command uses Get-Job to get the job. It uses the Name parameter of Get-Job to identify the job. The command saves the resulting job object in the $j variable. The third command displays the value of the job object in the $j variable. The value of the State property shows that the job is complete. The value o f the HasMoreData property shows that there are results available from the job that have not yet been retrieved. The fourth command uses the Receive-Job cmdlet to get the results of the jo b. It uses the job object in the $j variable to represent the job. You can also use a pipeline operator to send a job object to Receive-Job. -------------------------- EXAMPLE 8 -------------------------- C:\PS>start-job -scriptblock {get-eventlog system} C:\PS> invoke-command -computername S1 -scriptblock {get-eventlog system} - AsJob C:\PS> invoke-command -computername S2 -scriptblock {start-job -scriptblock {get-eventlog system}} C:\PS> get-job Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job1 Running True localhost get-eventlog system 2 Job2 Running True S1 get-eventlog system C:\PS> invoke-command -computername S2 -scriptblock {get-job} Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 4 Job4 Running True localhost get-eventlog system Description ----------- This example demonstrates that the Get-Job cmdlet can get all of the jobs t hat were started in the current session, even if they were started by using different methods. The first command uses the Start-Job cmdlet to start a job on the local com puter. The second command uses the AsJob parameter of Invoke-Command to start a jo b on the S1 computer. Even though the commands in the job run on the remote computer, the job object is created on the local computer, so you use loca l commands to manage the job. The third command uses the Invoke-Command cmdlet to run a Start-Job command on the S2 computer. With this method, the job object is created on the rem ote computer, so you use remote commands to manage the job. The fourth command uses Get-Job to get the jobs stored on the local compute r. The fifth command uses Invoke-Command to run a Get-Job command on the S2 co mputer. The sample output shows the results of the Get-Job commands. For more information about running background jobs on remote computers, see about_Remote_Jobs. -------------------------- EXAMPLE 9 -------------------------- C:\PS>start-job -scriptblock {get-process} Id Name State HasMoreData Location Co mmand -- ---- ----- ----------- -------- -- ----- 1 Job1 Failed False localhost ge t-process C:\PS> (get-job).jobstateinfo | format-list -property * State : Failed Reason : C:\PS> get-job | format-list * HasMoreData : False StatusMessage : Location : localhost Command : get-process JobStateInfo : Failed Finished : System.Threading.ManualResetEvent InstanceId : fb792295-1318-4f5d-8ac8-8a89c5261507 Id : 1 Name : Job1 ChildJobs : {Job2} Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} StateChanged : C:\PS> (get-job -name job2).jobstateinfo.reason Connecting to remote server using WSManCreateShellEx api failed. The async callback gave the following error message : Access is denied. Description ----------- This command shows how to use the job object that Get-Job returns to invest igate why a job failed. It also shows how to get the child jobs of each job . The first command uses the Start-Job cmdlet to start a job on the local com puter. The job object that Start-Job returns shows that the job failed. The value of the State property is "Failed". The second command uses Get-Job to get the job object. The command uses the dot method to get the value of the JobStateInfo property of the object. It uses a pipeline operator to send the object in the JobStateInfo property t o the Format-List cmdlet, which formats all of the properties of the object (*) in a list. The result of the Format-List command shows that the value of the Reason pr operty of the job is blank. The third command investigates further. It uses a Get-Job command to get th e job and then uses a pipeline operator to send the entire job object to th e Format-List cmdlet, which displays all of the properties of the job in a list. The display of all properties in the job object shows that the job contains a child job named "Job2". The fourth command uses Get-Job to get the job object that represents the J ob2 child job. This is the job in which the command actually ran. It uses t he dot method to get the Reason property of the JobStateInfo property. The result shows that the job failed because of an "access denied" error. I n this case, the user forgot to use the "Run as administrator" option when opening Windows PowerShell. Because background jobs use the remoting features of Windows PowerShell, th e computer must be configured for remoting to run a job, even when the job runs on the local computer. For information about requirements for remoting in Windows PowerShell, see about_Remote_Requirements. For troubleshooting tips, see about_Remote_Troub leshooting. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113328 about_Jobs about_Job_details about_Remote_Jobs Start-Job Receive-Job Wait-Job Stop-Job Remove-Job Invoke-Command Get-Location NAME Get-Location SYNOPSIS Gets information about the current working location. SYNTAX Get-Location [-PSDrive <string[]>] [-PSProvider <string[]>] [-UseTransactio n] [<CommonParameters>] Get-Location [-Stack] [-StackName <string[]>] [-UseTransaction] [<CommonPar ameters>] DESCRIPTION The Get-Location cmdlet gets an object that represents the current director y, much like the pwd (print working directory) command. When you move between Windows PowerShell drives, Windows PowerShell retains your location in each drive. You can use Get-Location to find your locatio n in each drive. You can also use Get-Location to get the current directory at run time and use it in functions and scripts, such as in a function that displays the cu rrent directory in the Windows PowerShell prompt. If you use the Push-Location cmdlet to add locations to a path stack, you c an use the Stack parameter of Get-Location to display the current stack. PARAMETERS -PSDrive <string[]> Gets the current location in the specified Windows PowerShell drive. For example, if you are in the Certificate: drive, you can use this par ameter to find your current location in the C: drive. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PSProvider <string[]> Gets the current location in the drive supported by the specified Windo ws PowerShell provider. If the specified provider supports more than one drive, Get-Location re turns the location on the most recently accessed drive. For example, if you are in the C: drive, you can use this parameter to find your current location in the drives of the Windows PowerShell Regi stry provider. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Stack [<SwitchParameter>] Displays the locations in the default path stack. To add paths to the default stack, use the Push-Location cmdlet. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -StackName <string[]> Displays the locations in the specified path stacks. To create path stacks, use the Push-Location cmdlet. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS PathInfo objects or StackInfo objects If you use the Stack or StackName parameters, Get-Location returns a St ackInfo object. Otherwise, it returns a PathInfo object. NOTES Locations can be stored on a stack. The Push-Location cmdlet adds a loc ation to the top of the stack. The Pop-Location cmdlet gets the locatio n at the top of the stack. The ways that the PSProvider, PSDrive, Stack, and StackName parameters interact depends on the provider. Some combinations will result in erro rs, such as specifying both a drive and a provider that does not expose that drive. If no parameters are specified, Get-Location returns the P athInfo object for the provider that contains the current working locat ion. The Get-Location cmdlet is designed to work with the data exposed by an y provider. To list the providers available in your session, type "Get- PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-location Path ---- C:\WINDOWS Description ----------- This command displays your location in the current Windows PowerShell drive . For example, if you are in the Windows directory of the C: drive, it displa ys the path to that directory. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-location Description ----------- These commands demonstrate the use of Get-Location to display your current location in different Windows PowerShell drives. The first command uses the Set-Location cmdlet to set the current location to the Windows subdirectory of the C: drive. C:\PS> set-location C:\Windows The second command uses the Set-Location cmdlet to change the location to t he HKLM:\Software\Microsoft registry key. When you change to a location in the HKLM: drive, Windows PowerShell retains your location in the C: drive. PS C:\WINDOWS> set-location HKLM:\Software\Microsoft PS HKLM:\Software\Microsoft> The third command uses the Set-Location cmdlet to change the location to th e "HKCU:\Control Panel\Input Method" registry key. PS HKLM:\Software\Microsoft> set-location 'HKCU:\Control Panel\Input Me thod' PS HKCU:\Control Panel\Input Method> The fourth command uses the Get-Location cmdlet to find the current locatio n on the C: drive. It uses the PSDrive parameter to specify the drive. PS HKCU:\Control Panel\Input Method> get-location -psdrive c Path ---- C:\WINDOWS The fifth command uses the Set-Location cmdlet to return to the C: drive. E ven though the command does not specify a subdirectory, Windows PowerShell returns you to the saved location. PS HKCU:\Control Panel\Input Method> set-location C: PS C:\WINDOWS> The sixth command uses the Get-Location cmdlet to find the current location in the drives supported by the Windows PowerShell registry provider. Get-L ocation returns the location of the most recently accessed registry drive, HKCU:. PS C:\WINDOWS> get-location -psprovider registry Path ---- HKCU:\Control Panel\Input Method To see the current location in the HKLM: drive, you need to use the PSDrive parameter to specify the drive. The seventh command does just this: PS C:\WINDOWS> get-location -psdrive HKLM Path ---- HKLM:\Software\Microsoft -------------------------- EXAMPLE 3 -------------------------- C:\PS>set-location Description ----------- These commands show how to use the Stack and StackName parameters of Get-Lo cation to list the paths in the default and alternate path stacks. The first command sets the current location to the Windows directory on the C: drive. C:\PS> set-location C:\Windows The second command uses the Push-Location cmdlet to push the current locati on (C:\Windows) onto the path stack and change to the System32 subdirectory . Because no stack is specified, the current location is pushed onto the de fault stack. C:\WINDOWS>push-location System32 The third command pushes the current location (C:\Windows\System32) onto th e Stack2 stack and changes the location to the WindowsPowerShell subirector y. C:\Windows\System32>push-location WindowsPowerShell -stack Stack2 The fourth command uses the Get-Location cmdlet to get the paths on the def ault path stack. C:\WINDOWS\system32\WindowsPowerShell>get-location -stack Path ---- C:\WINDOWS The last command uses the StackName parameter of Get-Location to get the pa ths on the Stack2 stack. C:\WINDOWS\system32\WindowsPowerShell>get-location -stackname Stack2 Path ---- C:\WINDOWS\system32 -------------------------- EXAMPLE 4 -------------------------- C:\PS>function prompt { 'PowerShell: ' + (get-location) + '> '} PowerShell: C:\WINDOWS> Description ----------- This example shows how to customize the Windows PowerShell prompt. The func tion that defines the prompt includes a Get-Location command, which is run whenever the prompt appears in the console. The format of the default Windows PowerShell prompt is defined by a special function called "prompt". You can change the prompt in your console by cre ating a new function called "prompt". To see the current prompt function, type the following command: get-content function:prompt The command begins with the "function" keyword followed by the function nam e, "prompt". The function body appears within braces ( {} ). This command defines a new prompt that begins with the string "PowerShell: ". To append the current location, it uses a Get-Location command, which ru ns when the prompt function is called. The prompt ends with the string "> " . RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113321 about_Providers Pop-Location Push-Location Set-Location Get-Member NAME Get-Member SYNOPSIS Gets the properties and methods of objects. SYNTAX Get-Member [[-Name] <string[]>] [-Force] [-InputObject <psobject>] [-Member Type {AliasProperty | CodeProperty | Property | NoteProperty | ScriptProper ty | Properties | PropertySet | Method | CodeMethod | ScriptMethod | Method s | ParameterizedProperty | MemberSet | Event | All}] [-Static] [-View {Ext ended | Adapted | Base | All}] [<CommonParameters>] DESCRIPTION The Get-Member cmdlet gets the "members" (properties and methods) of object s. To specify the object, use the InputObject parameter or pipe an object to G et-Member. To retrieve information about static members (members of the cla ss, not of the instance), use the Static parameter. To get only certain typ es of members, such as NoteProperties, use the MemberType parameter. PARAMETERS -Force [<SwitchParameter>] Adds the intrinsic members (PSBase, PSAdapted, PSObject, PSTypeNames) a nd the compiler-generated get_ and set_ methods to the display. By defa ult, Get-Member gets these properties in all views other than "Base" an d "Adapted," but it does not display them. The following list describes the properties that are added when you use the Force parameter: -- PSBase: The original properties of the .NET Framework object withou t extension or adaptation. These are the properties defined for the obj ect class and listed in MSDN. -- PSAdapted: The properties and methods defined in the Windows PowerSh ell extended type system. -- PSExtended: The properties and methods that were added in the Types. ps1xml files or by using the Add-Member cmdlet. -- PSObject: The adapter that converts the base object to a Windows Pow erShell PSObject object. -- PSTypeNames: A list of object types that describe the object, in ord er of specificity. When formatting the object, Windows PowerShell searc hes for the types in the Format.ps1xml files in the Windows PowerShell installation directory ($pshome). It uses the formatting definition for the first type that it finds. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the object whose members are retrieved. Using the InputObject parameter is not the same as piping an object to Get-Member. The differences are as follows: -- When you pipe a collection of objects to Get-Member, Get-Member gets the members of the individual objects in the collection, such as the p roperties of the integers in an array of integers. -- When you use InputObject to submit a collection of objects, Get-Memb er gets the members of the collection, such as the properties of the ar ray in an array of integers. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -MemberType <PSMemberTypes> Gets only members with the specified member type. The default is All. The valid values for this parameter are: -- AliasProperty: A property that defines a new name for an existing pr operty. -- CodeMethod: A method that references a static method of a .NET Frame work class. -- CodeProperty: A property that references a static property of a .NET Framework class. -- Event: Indicates that the object sends a message to indicate an act ion or a change in state. -- MemberSet: A predefined collection of properties and methods, such a s PSBase, PSObject, and PSTypeNames. -- Method: A method of the underlying .NET Framework object. -- NoteProperty: A property with a static value. -- ParameterizedProperty: A property that takes parameters and paramete r values. -- Property: A property of the underlying .NET Framework object. -- PropertySet: A predefined collection of object properties. -- ScriptMethod: A method whose value is the output of a script. -- ScriptProperty: A property whose value is the output of a script. -- All: Gets all member types. -- Methods: Gets all types of methods of the object (for example, Metho d, CodeMethod, ScriptMethod). -- Properties: Gets all types of properties of the object (for example, Property, CodeProperty, AliasProperty, ScriptProperty). Not all objects have every type of member. If you specify a member type that the object does not have, Windows PowerShell returns a null value . To get related types of members, such as all extended members, use the View parameter. If you use the MemberType parameter with the Static or View parameters, Get-Member gets the members that belong to both sets. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the names of one or more properties or methods of the object. Get-Member gets only the specified properties and methods. If you use the Name parameter with the MemberType, View, or Static para meters, Get-Member gets only the members that satisfy the criteria of a ll parameters. To get a static member by name, use the Static parameter with the Name parameter. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Static [<SwitchParameter>] Gets only the static properties and methods of the object. Static properties and methods are defined on the class of objects, not on any particular instance of the class. If you use the Static parameter with the View parameter, the View param eter is ignored. If you use the Static parameter with the MemberType pa rameter, Get-Member gets only the members that belong to both sets. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -View <PSMemberViewTypes> Gets only particular types of members (properties and methods). Specify one or more of the values. The default is "Adapted, Extended". Valid values are: -- Base: Gets only the original properties and methods of the .NET Fra mework object (without extension or adaptation). -- Adapted: Gets only the properties and methods defined in the Window s PowerShell extended type system. -- Extended: Gets only the properties and methods that were added in th e Types.ps1xml files or by using the Add-Member cmdlet. -- All: Gets the members in the Base, Adapted, and Extended views. The View parameter determines the members retrieved, not just the displ ay of those members. To get particular member types, such as script properties, use the Memb erType parameter. If you use the MemberType and View parameters in the same command, Get-Member gets the members that belong to both sets. If you use the Static and View parameters in the same command, the View pa rameter is ignored. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Get-Member OUTPUTS Microsoft.PowerShell.Commands.MemberDefinition Get-Member returns an object for each property or method that its gets. NOTES You can retrieve information about a collection object either by using the InputObject parameter or by piping the object, preceded by a comma, to Get-Member. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-service | get-member TypeName: System.ServiceProcess.ServiceController Name MemberType Definition ---- ---------- ---------- Name AliasProperty Name = ServiceName Close Method System.Void Close() Continue Method System.Void Continue() CreateObjRef Method System.Runtime.Remoting.ObjRef Crea teObjRef(Type requestedType) Dispose Method System.Void Dispose() Equals Method System.Boolean Equals(Object obj) ExecuteCommand Method System.Void ExecuteCommand(Int32 co mmand) GetHashCode Method System.Int32 GetHashCode() GetLifetimeService Method System.Object GetLifetimeService() GetType Method System.Type GetType() InitializeLifetimeService Method System.Object InitializeLifetimeSer vice() Pause Method System.Void Pause() Refresh Method System.Void Refresh() Start Method System.Void Start(), System.Void St art(String[] args) Stop Method System.Void Stop() ToString Method System.String ToString() WaitForStatus Method System.Void WaitForStatus(ServiceCo ntrollerStatus desiredStatus), System.Voi... CanPauseAndContinue Property System.Boolean CanPauseAndContinue {get;} CanShutdown Property System.Boolean CanShutdown {get;} CanStop Property System.Boolean CanStop {get;} Container Property System.ComponentModel.IContainer Co ntainer {get;} DependentServices Property System.ServiceProcess.ServiceContro ller[] DependentServices {get;} DisplayName Property System.String DisplayName {get;set; } MachineName Property System.String MachineName {get;set; } ServiceHandle Property System.Runtime.InteropServices.Safe Handle ServiceHandle {get;} ServiceName Property System.String ServiceName {get;set; } ServicesDependedOn Property System.ServiceProcess.ServiceContro ller[] ServicesDependedOn {get;} ServiceType Property System.ServiceProcess.ServiceType S erviceType {get;} Site Property System.ComponentModel.ISite Site {g et;set;} Status Property System.ServiceProcess.ServiceContro llerStatus Status {get;} Description ----------- This command displays the properties and methods of the process objects (Sy stem.ServiceProcess.ServiceController) that are generated by the Get-Servic e cmdlet. The command uses the pipeline operator (|) to send the output of a Get-Serv ice command to Get-Member. Because the Get-Member part of the command does not have any parameters, it uses all of the default values. As such, it gets all member types, but it does not get static members and does not display intrinsic members. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-service | get-member -force C:\PS> (get-service -schedule).psbase Description ----------- This example gets all of the members (properties and methods) of the servic e objects (System.ServiceProcess.ServiceController) retrieved by the Get-Se rvice cmdlet, including the intrinsic members, such as PSBase and PSObject, and the get_ and set_ methods. The first command uses the Get-Service cmdlet to get objects that represent the services on the system. It uses a pipeline operator (|) to pass the se rvice objects to the Get-Member cmdlet. The Get-Member command uses the Force parameter to add the intrinsic member s and compiler-generated members of the objects to the display. Get-Member gets these members, but it hides them by default. You can use these properties and methods in the same way that you would use an adapted method of the object. The second command shows how to display t he value of the PSBase property of the Schedule service. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-service | get-member -view extended TypeName: System.ServiceProcess.ServiceController Name MemberType Definition ---- ---------- ---------- Name AliasProperty Name = ServiceName Description ----------- This command gets the methods and properties of service objects that were e xtended by using the Types.ps1xml file or the Add-Member cmdlet. The Get-Member command uses the View parameter to get only the extended mem bers of the service objects. In this case, the extended member is the Name property, which is an alias property of the ServiceName property. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-eventlog -log system | gm -membertype scriptproperty TypeName: System.Diagnostics.EventLogEntry Name MemberType Definition ---- ---------- ---------- EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;} Description ----------- This command gets the script properties of event log objects in the System log in Event Viewer. In this case, the only script property is the EventID. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-eventlog -log system | get-member -membertype scriptproperty TypeName: System.Diagnostics.EventLogEntry Name MemberType Definition ---- ---------- ---------- EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;} Description ----------- This command gets the script properties of event log objects in the System log in Event Viewer. The command uses the MemberType parameter to get only objects with a value of AliasProperty for their MemberType property. The command returns the EventID property of the EventLog object. -------------------------- EXAMPLE 6 -------------------------- C:\PS>$a = "get-process", "get-service", "get-culture", "get-psdrive", "get -executionpolicy" C:\PS> foreach ($cmdlet in $a) {invoke-expression $cmdlet | get-member -nam e machinename} TypeName: System.Diagnostics.Process Name MemberType Definition ---- ---------- ---------- MachineName Property System.String MachineName {get;} TypeName: System.ServiceProcess.ServiceController Name MemberType Definition ---- ---------- ---------- MachineName Property System.String MachineName {get;set;} Description ----------- This command gets objects that have a MachineName property from a list of c mdlets. The first command stores the names of several cmdlets in the $a variable. The second command uses a ForEach statement to invoke each command, send th e results to Get-Member, and limit the results from Get-Member to members t hat have the name "MachineName." The results show that only process objects (System.Diagnostics.Process) and service objects (System.ServiceProcess.ServiceController) have a MachineNa me property. -------------------------- EXAMPLE 7 -------------------------- C:\PS>$a = get-member -inputobject @(1) C:\PS>$a.count 1 C:\PS> $a = get-member -inputobject 1,2,3 TypeName: System.Object[] Name MemberType Definition ---- ---------- ---------- Count AliasProperty Count = Length Address Method System.Object& Address(Int32 ) Clone Method System.Object Clone() ... C:\PS>$a.count 1 Description ----------- This example demonstrates how to find the properties and methods of an arra y of objects when you have only one object of the given type. Because the goal of the command is to find the properties of an array, the first command uses the InputObject parameter. It uses the "at" symbol (@) t o indicate an array. In this case, the array contains only one object, the integer 1. The third command uses the Get-Member cmdlet to get the properties and meth ods of an array of integers, and the command saves them in the $a variable. The fourth command uses the Count property of the array to find the number of objects in the $a variable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113322 Add-Member Get-Help Get-Command Get-PSDrive Get-Module NAME Get-Module SYNOPSIS Gets the modules that have been imported or that can be imported into the c urrent session. SYNTAX Get-Module [-All] [-ListAvailable] [-Name <string[]>] [<CommonParameters>] Get-Module [[-Name] <string[]>] [<CommonParameters>] DESCRIPTION The Get-Module cmdlet gets the modules that have been imported, or that can be imported, into the session. Get-Module only gets modules; it does not import them. To import the module s into your session, use Import-Module. PARAMETERS -All [<SwitchParameter>] Gets module objects for all module files. Without the All parameter, Get-Module gets only the module object for t he default module file. The cmdlet selects file types in the following order: manifest (.psd1) files, script module (.psm1) files, and binary module (.dll) files. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ListAvailable [<SwitchParameter>] Gets all of the modules that can be imported into the session. Get-Modu le gets the modules in the paths specified by the $env:PSModulePath env ironment variable. Without this parameter, Get-Module gets only the modules that have been imported into the session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Gets only modules with the specified names or name patterns. Wildcards are permitted. You can also pipe the names to Get-Module. Required? false Position? 1 Default value All imported or available modules. Accept pipeline input? true (ByValue) Accept wildcard characters? true <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe module names to Get-Module. OUTPUTS System.Management.Automation.PSModuleInfo Get-Module returns objects that represent the modules. NOTES You can also refer to Get-Module by its alias, "gmo". For more informat ion, see about_Aliases. The All parameter returns module objects for all files with a .dll file name extension, even if they do not implement cmdlets or providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-module Description ----------- This command gets the modules that have been imported into the current sess ion. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-module -listAvailable Description ----------- This command gets the modules that can be imported into the current session . Get-Module looks for available modules in the path specified by the $env:PS ModulePath environment variable. For more information about PSModulePath, s ee about_Modules and about_Environment_Variables. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-module -listAvailable -all Description ----------- This command gets all of the exported files for all available modules. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-module | get-member -type property TypeName: System.Management.Automation.PSModuleInfo Name MemberType Definition ---- ---------- ---------- AccessMode Property System.Management.Automation.ModuleAcc Description Property System.String Description {get;set;} ExportedAliases Property System.Collections.Generic.Dictionary` ExportedCmdlets Property System.Collections.Generic.Dictionary` ExportedFunctions Property System.Collections.Generic.Dictionary` ExportedVariables Property System.Collections.Generic.Dictionary` Guid Property System.Guid Guid {get;} ModuleBase Property System.String ModuleBase {get;} ModuleType Property System.Management.Automation.ModuleTyp Name Property System.String Name {get;} NestedModules Property System.Collections.ObjectModel.ReadOnl OnRemove Property System.Management.Automation.ScriptBlo Path Property System.String Path {get;} PrivateData Property System.Object PrivateData {get;set;} SessionState Property System.Management.Automation.SessionSt Version Property System.Version Version {get;} Description ----------- This command get the properties of the PSModuleInfo object that Get-Module returns. There is one object for each module file. You can use the properties to format and filter the module objects. For mor e information about the properties, see "PSModule Properties" in the MSDN ( Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?Lin kId=143624. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-module -listAvailable -all | format-table -property name, modulet ype, path -groupby name -auto Name: MyTestCmdlets Name ModuleType Path ---- ---------- ---- MyTestCmdlets Script C:\Windows\system32\WindowsPowerShell\v1.0\Modules \TestCmdlets\TestCmdlets.dll Name: PSDiagnostics Name ModuleType Path ---- ---------- ---- PSDiagnostics Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules \PSDiagnostics\PSDiagnostics.psd1 PSDiagnostics Script C:\Windows\system32\WindowsPowerShell\v1.0\Modules \PSDiagnostics\PSDiagnostics.psm1 Name: FileTransfer Name ModuleType Path ---- ---------- ---- FileTransfer Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ FileTransfer\FileTransfer.psd1 Description ----------- This command gets all module files (imported and available) and groups them by module name. This lets you see the module files that each script is exp orting. -------------------------- EXAMPLE 6 -------------------------- C:\PS>$m = get-module -list -name FileTransfer | where {$_.moduletype -eq " Manifest"} C:\PS> get-content $m.path @{ GUID="{8FA5064B-8479-4c5c-86EA-0D311FE48875}" Author="Microsoft Corporation" CompanyName="Microsoft Corporation" Copyright="¸ Microsoft Corporation. All rights reserved." ModuleVersion="1.0.0.0" Description="Windows Powershell File Transfer Module" PowerShellVersion="2.0" CLRVersion="2.0" NestedModules="Microsoft.BackgroundIntelligentTransfer.Management" FormatsToProcess="FileTransfer.Format.ps1xml" RequiredAssemblies=Join-Path $psScriptRoot "Microsoft.BackgroundIntelligent Transfer.Management.Interop.dll" } Description ----------- These commands display the contents of the module manifest for the Windows PowerShell File Transfer module. The first command gets the PSModuleInfo object that represent the module ma nifest for the File Transfer module. It saves the object in the $m variable . The second command uses dot notation to get the path to the manifest file, which is stored in the Path property of the object. Then, it uses the Get-C ontent cmdlet to get the content of the manifest file in the specified path . Modules are not required to have manifest files. When they do have a manife st file, a manifest is required only to include a version number. However, manifest files often provide useful information about a module, its require ments, and its contents. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-module -listAvailable -name FileTransfer | format-list -property * Name : FileTransfer Path : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\File Transfer\FileTransfer.psd1 Description : Powershell File Transfer Module Guid : 8fa5064b-8479-4c5c-86ea-0d311fe48875 ModuleBase : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\File Transfer PrivateData : Version : 1.0.0.0 ModuleType : Manifest AccessMode : ReadWrite ExportedFunctions : {} ExportedCmdlets : {} NestedModules : {} ExportedVariables : {} ExportedAliases : {} SessionState : System.Management.Automation.SessionState OnRemove : Description ----------- This command displays all of the properties of the FileTransfer module in a list. Because the module has not yet been imported into the session, the Exported * properties and the NestedModules property are not yet populated. These pr operties are populated only after the elements have been exported and the n ested modules have been instantiated. -------------------------- EXAMPLE 8 -------------------------- C:\PS>dir (get-module -listavailable FileTransfer).modulebase Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules\FileTrans fer Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 12/16/2008 12:36 PM en-US -a--- 11/19/2008 11:30 PM 16184 FileTransfer.Format.ps1xml -a--- 11/20/2008 11:30 PM 1044 FileTransfer.psd1 -a--- 12/16/2008 12:20 AM 108544 Microsoft.BackgroundIntelligen tTransfer.Management.Interop.dll Description ----------- This command lists the files in the module's directory. This is another way to determine what is in a module before you import it. Some modules might have help files or ReadMe files that describe the module. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=141552 Import-Module New-Module Remove-Module about_Modules Get-PfxCertificate NAME Get-PfxCertificate SYNOPSIS Gets information about .pfx certificate files on the computer. SYNTAX Get-PfxCertificate [-FilePath] <string[]> [<CommonParameters>] DESCRIPTION The Get-PfxCertificate cmdlet gets an object representing each specified .p fx certificate file. A .pfx file includes both the certificate and a privat e key. PARAMETERS -FilePath <string[]> The full path to the .pfx file of the secured file. The parameter name ("FilePath") is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a file path to Get-PfxCertificate. OUTPUTS System.Security.Cryptography.X509Certificates Get-PfxCertificate returns an object for each certificate that it gets. NOTES When using the Invoke-Command cmdlet to run a Get-PfxCertificate comman d remotely, and the .pfx certificate file is not password protected, th e value of the Authentication parameter of Invoke-Command must be "Cred SSP". -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-pfxcertificate -filepath C:\windows\system32\Test.pfx Password: ****** Signer Certificate: Matt Berg (Self Certificate) Time Certificate: Time Stamp: Path: C:\windows\system32\zap.pfx Description ----------- This command gets information about the Test.pfx certificate on the system. -------------------------- EXAMPLE 2 -------------------------- C:\PS>invoke-command -computername Server01 -scriptblock {get-pfxcertificat e -filepath C:\Text\TestNoPassword.pfx} -authentication CredSSP Description ----------- This command gets a .pfx certificate file from the Server01 remote computer . It uses the Invoke-Command to run a Get-PfxCertificate command remotely. When the .pfx certificate file is not password-protected, the value of the Authentication parameter of Invoke-Command must be "CredSSP". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113323 Get-AuthenticodeSignature Set-AuthenticodeSignature about_Signing Get-Process NAME Get-Process SYNOPSIS Gets the processes that are running on the local computer or a remote compu ter. SYNTAX Get-Process [[-Name] <string[]>] [-ComputerName <string[]>] [-FileVersionIn fo] [-Module] [<CommonParameters>] Get-Process -Id <Int32[]> [-ComputerName <string[]>] [-FileVersionInfo] [-M odule] [<CommonParameters>] Get-Process -InputObject <Process[]> [-ComputerName <string[]>] [-FileVersi onInfo] [-Module] [<CommonParameters>] DESCRIPTION The Get-Process cmdlet gets the processes on a local or remote computer. Without parameters, Get-Process gets all of the processes on the local comp uter. You can also specify a particular process by process name or process ID (PID) or pass a process object through the pipeline to Get-Process. By default, Get-Process returns a process object that has detailed informat ion about the process and supports methods that let you start and stop the process. You can also use the parameters of Get-Process to get file version information for the program that runs in the process and to get the module s that the process loaded. PARAMETERS -ComputerName <string[]> Gets the processes running on the specified computers. The default is t he local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more computers. To specify the local computer, type the compu ter name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Get-Process even if your computer is no t configured to run remote commands. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -FileVersionInfo [<SwitchParameter>] Gets the file version information for the program that runs in the proc ess. On Windows Vista and later versions of Windows, you must open Windows P owerShell with the "Run as administrator" option to use this parameter on processes that you do not own. Using this parameter is equivalent to getting the MainModule.FileVersio nInfo property of each process object. When you use this parameter, Get -Process returns a FileVersionInfo object (System.Diagnostics.FileVersi onInfo), not a process object. So, you cannot pipe the output of the co mmand to a cmdlet that expects a process object, such as Stop-Process. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Id <Int32[]> Specifies one or more processes by process ID (PID). To specify multipl e IDs, use commas to separate the IDs. To find the PID of a process, ty pe "get-process". Required? true Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InputObject <Process[]> Specifies one or more process objects. Enter a variable that contains t he objects, or type a command or expression that gets the objects. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Module [<SwitchParameter>] Gets the modules that have been loaded by the processes. On Windows Vista and later versions of Windows, you must open Windows P owerShell with the "Run as administrator" option to use this parameter on processes that you do not own. This parameter is equivalent to getting the Modules property of each pr ocess object. When you use this parameter, Get-Process returns a Proces sModule object (System.Diagnostics.ProcessModule), not a process object . So, you cannot pipe the output of the command to a cmdlet that expect s a process object, such as Stop-Process. When you use both the Module and FileVersionInfo parameters in the same command, Get-Process returns a FileVersionInfo object with information about the file version of all modules. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies one or more processes by process name. You can type multiple process names (separated by commas) or use wildcard characters. The par ameter name ("Name") is optional. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Diagnostics.Process You can pipe a process object to Get-Process. OUTPUTS System.Diagnostics.Process, System.Diagnotics.FileVersionInfo, System.Diagn ostics.ProcessModule By default, Get-Process returns a System.Diagnostics.Process object. If you use the FileVersionInfo parameter, it returns a System.Diagnotics. FileVersionInfo object. If you use the Module parameter (without the F ileVersionInfo parameter), it returns a System.Diagnostics.ProcessModul e object. NOTES You cannot use the Name, ID, and InputObject parameters in the same com mand. You can also refer to Get-Process by its built-in aliases, "ps" and "gp s". For more information, see about_Aliases. You can also use the properties and methods of the WMI Win32_Process ob ject in Windows PowerShell. For information, see Get-WmiObject and the Windows Management Instrumentation (WMI) SDK. The default display of a process is a table that includes the following columns: -- Handles: The number of handles that the process has opened. -- NPM(K): The amount of non-paged memory that the process is using, in kilobytes. -- PM(K): The amount of pageable memory that the process is using, in k ilobytes. -- WS(K): The size of the working set of the process, in kilobytes. The working set consists of the pages of memory that were recently referen ced by the process. -- VM(M): The amount of virtual memory that the process is using, in me gabytes. Virtual memory includes storage in the paging files on disk. -- CPU(s): The amount of processor time that the process has used on al l processors, in seconds. -- ID: The process ID (PID) of the process. -- ProcessName: The name of the process. For explanations of the concepts related to processes, see the Glossary in Help and Support Center and the Help for Task Manager. You can also use the built-in alternate views of the processes availabl e with Format-Table, such as "StartTime" and "Priority", and you can de sign your own views. For more information, see Format-Table. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Get-Process Description ----------- This command gets a list of all of the running processes running on the loc al computer. For a definition of each column, see the "Additional Notes" se ction of the Help topic for Get-Help. -------------------------- EXAMPLE 2 -------------------------- C:\PS>Get-Process winword, explorer | format-list * Description ----------- This command gets all available data about the Winword and Explorer process es on the computer. It uses the Name parameter to specify the processes, bu t it omits the optional parameter name. The pipeline operator (|) passes th e data to the Format-List cmdlet, which displays all available properties ( *) of the Winword and Explorer process objects. You can also identify the processes by their process IDs. For example, "get -process -id 664, 2060". -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-process | where-object {$_.WorkingSet -gt 20000000} Description ----------- This command gets all processes that have a working set greater than 20 MB. It uses the Get-Process cmdlet to get all running processes. The pipeline operator (|) passes the process objects to the Where-Object cmdlet, which s elects only the object with a value greater than 20,000,000 bytes for the W orkingSet property. WorkingSet is one of many properties of process objects. To see all of the properties, type "Get-Process | Get-Member". By default, the values of all amount properties are in bytes, even though the default display lists them in kilobytes and megabytes. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$a = get-process C:\PS> get-process -inputobject $a | format-table -view priority Description ----------- These commands list the processes on the computer in groups based on their priority class. The first command gets all the processes on the computer and then stores th em in the $a variable. The second command uses the InputObject parameter to pass the process objec ts that are stored in the $a variable to the Get-Process cmdlet. The pipel ine operator passes the objects to the Format-Table cmdlet, which formats t he processes by using the Priority view. The priority view, and other views, are defined in the PS1XML format files in the Windows PowerShell home directory ($pshome). -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-process powershell -computername S1, localhost | ft @{Label="NPM( K)";Expression={[int]($_.NPM/1024)}}, @{Label="PM(K)";Expression={[int]($_. PM/1024)}},@{Label="WS(K)";Expression={[int]($_.WS/1024)}},@{Label="VM(M)"; Expression={[int]($_.VM/1MB)}}, @{Label="CPU(s)";Expression={if ($_.CPU -ne $()) { $_.CPU.ToString("N")}}}, Id, MachineName, ProcessName -auto NPM(K) PM(K) WS(K) VM(M) CPU(s) Id MachineName ProcessName ------ ----- ----- ----- ------ -- ----------- ----------- 6 23500 31340 142 1980 S1 powershell 6 23500 31348 142 4016 S1 powershell 27 54572 54520 576 4428 localhost powershell Description ----------- This example provides a Format-Table (alias = ft) command that adds the Mac hineName property to the standard Get-Process output display. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-process powershell -fileversioninfo ProductVersion FileVersion FileName -------------- ----------- -------- 6.1.6713.1 6.1.6713.1 (f... C:\WINDOWS\system32\WindowsPowerShell\v1. 0\powershell.exe Description ----------- This command uses the FileVersionInfo parameter to get the version informat ion for the PowerShell.exe file that is the main module for the PowerShell process. To run this command with processes that you do not own on Windows Vista and later versions of Windows, you must open Windows PowerShell with the "Run as administrator" option. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-process sql* -module Description ----------- This command uses the Module parameter to get the modules that have been lo aded by the process. This command gets the modules for the processes that h ave names that begin with "sql". To run this command on Windows Vista (and later versions of Windows) with p rocesses that you do not own, you must start Windows PowerShell with the "R un as administrator" option. -------------------------- EXAMPLE 8 -------------------------- C:\PS>$p = get-wmiobject win32_process -filter "name='powershell.exe'" C:\PS> $p.getowner() __GENUS : 2 __CLASS : __PARAMETERS __SUPERCLASS : __DYNASTY : __PARAMETERS __RELPATH : __PROPERTY_COUNT : 3 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : Domain : DOMAIN01 ReturnValue : 0 User : user01 Description ----------- This command shows how to find the owner of a process. Because the System.D iagnostics.Process object that Get-Process returns does not have a property or method that returns the process owner, the command uses the Get-WmiObject cmdlet to get a Win32_Process object that represents the same process. The first command uses Get-WmiObject to get the PowerShell process. It save s it in the $p variable. The second command uses the GetOwner method to get the owner of the process in $p. The command reveals that the owner is Domain01\user01. -------------------------- EXAMPLE 9 -------------------------- C:\PS>get-process powershell C:\PS> get-process -id $pid C:\PS> get-process powershell Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 308 26 52308 61780 567 3.18 5632 powershell 377 26 62676 63384 575 3.88 5888 powershell C:\PS> get-process -id $pid Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 396 26 56488 57236 575 3.90 5888 powershell Description ----------- These commands show how to use the $pid automatic variable to identify the process that is hosting the current Windows PowerShell session. You can use this method to distinguish the host process from other PowerShell processe s that you might want to stop or close. The first command gets all of the PowerShell processes in the current sessi on. The second command gets the PowerShell process that is hosting the current session. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113324 Get-Process Start-Process Stop-Process Wait-Process Debug-Process Get-PSBreakpoint NAME Get-PSBreakpoint SYNOPSIS Gets the breakpoints that are set in the current session. SYNTAX Get-PSBreakpoint [[-Script] <string[]>] [<CommonParameters>] Get-PSBreakpoint -Command <string[]> [-Script <string[]>] [<CommonParameter s>] Get-PSBreakpoint [-Id] <Int32[]> [<CommonParameters>] Get-PSBreakpoint [-Type] <BreakpointType[]> [-Script <string[]>] [<CommonPa rameters>] Get-PSBreakpoint -Variable <string[]> [-Script <string[]>] [<CommonParamete rs>] DESCRIPTION The Get-PSBreakPoint cmdlet gets the breakpoints that are set in the curren t session. You can use the cmdlet parameters to get particular breakpoints. A breakpoint is a point in a command or script where execution stops tempor arily so that you can examine the instructions. Get-PSBreakpoint is one of several cmdlets designed for debugging Windows PowerShell scripts and comma nds. For more information about the Windows PowerShell debugger, see about_ Debuggers. PARAMETERS -Command <string[]> Gets command breakpoints that are set on the specified command names. E nter the command names, such as the name of a cmdlet or function. Required? true Position? named Default value All breakpoints Accept pipeline input? false Accept wildcard characters? false -Id <Int32[]> Gets the breakpoints with the specified breakpoint IDs. Enter the IDs i n a comma-separated list. You can also pipe breakpoint IDs to Get-PSBre akpoint. Required? true Position? 1 Default value All breakpoints Accept pipeline input? true (ByValue) Accept wildcard characters? false -Script <string[]> Gets only the breakpoints in the specified scripts. Enter the path (op tional) and names of one or more script files. The default location is the current directory. Required? false Position? named Default value All breakpoints Accept pipeline input? false Accept wildcard characters? false -Type <BreakpointType[]> Gets only breakpoints of the specified types. Enter one or more types. Valid values are Line, Command, and Variable. You can also pipe breakpo int types to Get-PSBreakpoint. Required? true Position? 1 Default value All breakpoints Accept pipeline input? true (ByValue) Accept wildcard characters? false -Variable <string[]> Gets variable breakpoints that are set on the specified variable names. Enter the variable names without dollar signs. Required? true Position? named Default value All breakpoints Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Int32, Microsoft.PowerShell.Commands.BreakpointType You can pipe breakpoint IDs and breakpoint types to Get-PSBreakpoint. OUTPUTS Breakpoint object (System.Management.Automation.LineBreakpoint, System.Mana gement.Automation.VariableBreakpoint, System.Management.Automation.CommandB reakpoint) Get-PSBreakPoint returns objects that represent the breakpoints in the session. NOTES You can use Get-PSBreakpoint or its alias, "gbp". -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-psbreakpoint Description ----------- This command gets all breakpoints set on all scripts and functions in the c urrent session. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-psbreakpoint -Id 2 Function : Increment Action : Enabled : True HitCount : 0 Id : 2 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Description ----------- This command gets the breakpoint with breakpoint ID 2. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$b = set-psbreakpoint -script sample.ps1 -function increment C:\PS> $b.Id | get-psbreakpoint Description ----------- These commands show how to get a breakpoint by piping a breakpoint ID to Ge t-PSBreakpoint. The first command uses the Set-PSBreakpoint cmdlet to create a breakpoint o n the Increment function in the Sample.ps1 script. It saves the breakpoint object in the $b variable. The second command uses the dot operator (.) to get the Id property of the breakpoint object in the $b variable. It uses a pipeline operator (|) to se nd the ID to the Get-PSBreakpoint cmdlet. As a result, Get-PSBreakpoint gets the breakpoint with the specified ID. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-psbreakpoint -script Sample.ps1, SupportScript.ps1 Description ----------- This command gets all of the breakpoints in the Sample.ps1 and SupportScrip t.ps1 files. This command does not get other breakpointS that might be set in other scri pts or on functions in the session. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-psbreakpoint -command Read-Host, Write-Host -script Sample.ps1 Description ----------- This command gets all Command breakpoints that are set on Read-Host or Writ e-Host commands in the Sample.ps1 file. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-psbreakpoint -type Command -script Sample.ps1 Description ----------- This command gets all Command breakpoints in the Sample.ps1 file. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-psbreakpoint -variable Index, Swap Description ----------- This command gets breakpoints that are set on the $index and $swap variable s in the current session. -------------------------- EXAMPLE 8 -------------------------- C:\PS>get-psbreakpoint -type line, variable -script Sample.ps1 Description ----------- This command gets all line and variable breakpoints in the Sample.ps1 scrip t. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113325 about_Debuggers Set-PSBreakpoint Disable-PSBreakpoint Enable-PSBreakpoint Remove-PSBreakpoint Get-PSCallStack Get-PSCallStack NAME Get-PSCallStack SYNOPSIS Displays the current call stack. SYNTAX Get-PSCallStack [<CommonParameters>] DESCRIPTION The Get-PSCallStack cmdlet displays the current call stack. Although it is designed to be used with the Windows PowerShell debugger, yo u can use this cmdlet to display the call stack in a script or function out side of the debugger. To run a Get-PSCallStack command while in the debugger, type "k" or "get-p scallstack". PARAMETERS <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS System.Management.Automation.CallStackFrame Get-PSCallStack returns an object that represents the items in the call stack. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>function my-alias { $p = $args[0] get-alias | where {$_.definition -like "*$p"} | ft definition, name -aut o } PS C:\ps-test> set-psbreakpoint -command my-alias Command : my-alias Action : Enabled : True HitCount : 0 Id : 0 Script : prompt PS C:\ps-test> my-alias get-content Entering debug mode. Use h or ? for help. Hit Command breakpoint on 'prompt:my-alias' my-alias get-content [DBG]: PS C:\ps-test> s $p = $args[0] DEBUG: Stepped to ': $p = $args[0] ' [DBG]: PS C:\ps-test> s get-alias | Where {$_.Definition -like "*$p*"} | ft Definition, [DBG]: PS C:\ps-test>get-pscallstack Name CommandLineParameters UnboundArguments Loc ation ---- --------------------- ---------------- --- ----- prompt {} {} pro mpt my-alias {} {get-content} pro mpt prompt {} {} pro mpt [DBG]: PS C:\ps-test> o Definition Name ---------- ---- Get-Content gc Get-Content cat Get-Content type Description ----------- This command uses the Get-PSCallStack cmdlet to display the call stack for My-Alias, a simple function that gets the aliases for a cmdlet name. The first command enters the function at the Windows PowerShell prompt. The second command uses the Set-PSBreakpoint cmdlet to set a breakpoint on the My-Alias function. The third command uses the My-Alias function to get all of the aliases in the current session for the Get-Content cmdlet. The debugger breaks in at the function call. Two consecutive step-into (s) commands begin executing the function line by line. Then, a Get-PSCallStack command is used to retrieve the call stack. The final command is a Step-Out command (o) that exits the debugger and con tinues executing the script to completion. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113326 about_Debuggers Set-PSBreakpoint Get-PSBreakpoint Enable-PSBreakpoint Disable-PSBreakpoint Remove-PSBreakpoint Get-PSDrive NAME Get-PSDrive SYNOPSIS Gets the Windows PowerShell drives in the current session. SYNTAX Get-PSDrive [-LiteralName] <string[]> [-PSProvider <string[]>] [-Scope <str ing>] [-UseTransaction] [<CommonParameters>] Get-PSDrive [[-Name] <string[]>] [-PSProvider <string[]>] [-Scope <string>] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Get-PSDrive cmdlet gets the Windows PowerShell drives in the current se ssion. You can get a particular drive or all drives in the console. Get-PSDrive gets the following drives: -- Windows logical drives on the computer, including drives mapped to netwo rk shares. -- Drives exposed by Windows PowerShell providers (such as the Certificate: , Function:, and Alias: drives) and the HKLM: and HKCU: drives that are exp osed by the Windows PowerShell Registry provider. -- Drives that you create by using New-PSDrive. Get-PSDrive does not get Windows mapped drives that are added or created af ter the Windows PowerShell console is opened. PARAMETERS -LiteralName <string[]> Specifies the name of the Windows PowerShell drive. The value of LiteralName is used exactly as it is typed. No characters are interpreted as wildcards. If the name includes escape characters, e nclose it in single quotation marks. Single quotation marks tell Window s PowerShell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Gets only the specified drives. Type the drive name or letter without a colon (:). Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PSProvider <string[]> Gets only the drives supported by the specified Windows PowerShell prov ider. Type the name of a provider, such as FileSystem, Registry, or Cer tificate. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Scope <string> Gets only the Windows PowerShell drives in the specified scope. Valid v alues are "Global", "Local", or "Script", or a number relative to the c urrent scope (0 through the number of scopes, where 0 is the current sc ope and 1 is its parent). "Local" is the default. For more information, see about_Scopes. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Get-PSDrive. OUTPUTS System.Management.Automation.PSDriveInfo Get-PSDrive returns objects that represent the Windows PowerShell drive s in the session. NOTES The Get-PSDrive cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "get-p sprovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-psdrive Name Provider Root ---- -------- ---- Alias Alias C FileSystem C:\ cert Certificate \ D FileSystem D:\ Env Environment Function Function HKCU Registry HKEY_CURRENT_USER HKLM Registry HKEY_LOCAL_MACHINE Variable Variable X FileSystem X:\ Description ----------- This command gets the Windows PowerShell drives in the current session. The output shows the hard drive (C:) and CD-ROM drive (D:) on the computer, the drives exposed by the Windows PowerShell providers (Alias:, Cert:, Env :, Function:, HKCU:, HKLM:, and Variable:), and a drive mapped to a network share (X:). -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-psdrive d Name Provider Root ---- -------- ---- D FileSystem D:\ Description ----------- This command displays the D: drive on the computer. Note that the drive let ter is not followed by a colon. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-psdrive -psprovider filesystem Name Provider Root ---- -------- ---- C FileSystem C:\ D FileSystem D:\ X FileSystem X:\ Y FileSystem \\Server01\Public Z FileSystem C:\Windows\System32 Description ----------- This command displays all of the drives that are supported by the Windows P owerShell FileSystem provider. This includes fixed drives, logical partitio ns, mapped network drives, and drives that you create by using New-PSDrive that are mapped to the file system drives. This example shows that drives created by New-PSDrive have the name of the mapped location in the value of the Root property. Windows drives just have the root of the drive letter. -------------------------- EXAMPLE 4 -------------------------- C:\PS>if ((get-psdrive X)) { new-psdrive -name X -psprovider Registry -root HKLM:\Network } else { write-host "The X: drive is already in use." } Description ----------- This command checks to see whether the X drive is already in use as the Win dows PowerShell drive name. If it is not, the command uses the New-PSDrive cmdlet to create a Windows PowerShell drive that is mapped to the HKLM:\Net work registry key. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-psdrive -provider filesystem C:\PS> get-psdrive -provider filesystem Name Provider Root ---- -------- ---- C FileSystem C:\ D FileSystem D:\ X FileSystem X:\ Y FileSystem \\Server01\Public Z FileSystem C:\Windows\System32 C:\PS> net use New connections will be remembered. Status Local Remote Network --------------------------------------------------------------------------- ---- X: \\Server01\Public Microsoft Windows Network C:\PS> [System.IO.DriveInfo]::getdrives() Name : C:\ DriveType : Fixed DriveFormat : NTFS IsReady : True AvailableFreeSpace : 39831498752 TotalFreeSpace : 39831498752 TotalSize : 79900368896 RootDirectory : C:\ VolumeLabel : Name : D:\ DriveType : CDRom DriveFormat : IsReady : False AvailableFreeSpace : TotalFreeSpace : TotalSize : RootDirectory : D:\ VolumeLabel : Name : X:\ DriveType : Network DriveFormat : NTFS IsReady : True AvailableFreeSpace : 36340559872 TotalFreeSpace : 36340559872 TotalSize : 36413280256 RootDirectory : X:\ VolumeLabel : D_Drive C:\PS> get-wmiobject win32_logicaldisk DeviceID : C: DriveType : 3 ProviderName : FreeSpace : 39831252992 Size : 79900368896 VolumeName : DeviceID : D: DriveType : 5 ProviderName : FreeSpace : Size : VolumeName : DeviceID : X: DriveType : 4 ProviderName : \\server01\public FreeSpace : 36340559872 Size : 36413280256 VolumeName : D_Drive C:\PS> get-wmiobject win32_networkconnection LocalName RemoteName -------------- ------------ x: \\server01\public Description ----------- This example compares the types of file system drives that are displayed by Get-PSDrive to those displayed by using other methods. This example demons trates different ways to display drives in Windows PowerShell, and it shows that the drives created by using New-PSDrive are accessible only in Window s PowerShell. The first command uses Get-PSDrive to get all of the file system drives in the Windows PowerShell console. This includes the fixed drives (C: and D:), the mapped network drive (X:), and two Windows PowerShell drives (Y: and Z :) that were created by using New-PsDrive. A "net use" command, which displays Windows mapped network drives, displays only the X drive. It does not display drives that are created by New-PSDri ve. It shows that the X: drive is also mapped to \\Server01\Public. The third command uses the GetDrives method of the Microsoft .NET Framework System.IO.DriveInfo class. This command gets the Windows file system drive s, including drive X:, but it does not get the drives created by New-PSDriv e. The fourth command uses the Get-WmiObject cmdlet to display the instances o f the Win32_LogicalDisk class. It returns the C:, D:, and X: drives, but no t the drives created by New-PSDrive. The last command uses the Get-WmiObject cmdlet to display the instances of the Win32_NetworkConnection class. Like "net use", it returns only the X: d rive. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113327 about_Providers New-PSDrive Remove-PSDrive Get-Help Get-Command Get-Member Get-PSProvider NAME Get-PSProvider SYNOPSIS Gets information about the specified Windows PowerShell provider. SYNTAX Get-PSProvider [[-PSProvider] <string[]>] [<CommonParameters>] DESCRIPTION The Get-PSProvider cmdlet gets the Windows PowerShell providers in the curr ent session. You can get a particular drive or all drives in the session. Windows PowerShell providers let you access a variety of data stores as tho ugh they were file system drives. For information about Windows PowerShell providers, see about_Providers. PARAMETERS -PSProvider <string[]> Specifies the name or names of the Windows PowerShell providers about w hich to retrieve information. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS System.Management.Automation.ProviderInfo Get-PSProvider returns objects that represent the Windows PowerShell pr oviders in the session. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-psprovider Description ----------- This command displays a list of all available Windows PowerShell providers. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-psprovider f*, r* | format-list Description ----------- This command displays a list of all Windows PowerShell providers with names that begin with the letter "f" or "r". -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-psprovider | format-table name, module, pssnapin -auto Name Module PSSnapIn ---- ------ -------- Test TestModule WSMan Microsoft.WSMan.Management Alias Microsoft.PowerShell.Core Environment Microsoft.PowerShell.Core FileSystem Microsoft.PowerShell.Core Function Microsoft.PowerShell.Core Registry Microsoft.PowerShell.Core Variable Microsoft.PowerShell.Core Certificate Microsoft.PowerShell.Security C:\PS> get-psprovider | where {$_.pssnapin -eq "Microsoft.PowerShell.Securi ty"} Name Capabilities Drives ---- ------------ ------ Certificate ShouldProcess {cert} Description ----------- These commands find the Windows PowerShell snap-ins or modules that added p roviders to your session. All Windows PowerShell elements, including provid ers, originate in a snap-in or in a module. These commands use the PSSnapin and Module properties of the ProviderInfo o bject that Get-PSProvider returns. The values of these properties contain t he name of the snap-in or module that adds the provider. The first command gets all of the providers in the session and formats them in a table with the values of their Name, Module, and PSSnapin properties. The second command uses the Where-Object cmdlet to get the providers that c ome from the Microsoft.PowerShell.Security snap-in. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113329 about_Providers Get-PSSession NAME Get-PSSession SYNOPSIS Gets the Windows PowerShell sessions (PSSessions) in the current session. SYNTAX Get-PSSession [[-ComputerName] <string[]>] [<CommonParameters>] Get-PSSession [-Id] <Int32[]> [<CommonParameters>] Get-PSSession [-InstanceId <Guid[]>] [<CommonParameters>] Get-PSSession [-Name <string[]>] [<CommonParameters>] DESCRIPTION The Get-PSSession cmdlet gets the Windows PowerShell sessions (PSSessions) that were created in the current session. Without parameters, Get-PSSession gets all of the PSSessions created in the current session. You can use the parameters of Get-PSSession to get the se ssions that are connected to particular computers, or you can identify sess ions by their names, IDs, or instance IDs. For more information about Windows PowerShell sessions, see about_PSSession s. PARAMETERS -ComputerName <string[]> Gets only the PSSessions that are connected to the specified computers. Wildcards are permitted. Type the NetBIOS name, an IP address, or a fully-qualified domain name of one or more computers. To specify the local computer, type the compu ter name, "localhost", or a dot (.). Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Id <Int32[]> Gets only the PSSessions with the specified IDs. Type one or more IDs ( separated by commas), or use the range operator (..) to specify a range of IDs. An ID is an integer that uniquely identifies the PSSession in the curre nt session. It is easier to remember and type than the InstanceId, but it is unique only within the current session. To find the ID of a PSSe ssion, use Get-PSSession without parameters. Required? true Position? 1 Default value All sessions in the shell Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InstanceId <Guid[]> Gets only the PSSessions with the specified instance IDs. The instance ID is a GUID that uniquely identifies a PSSession on a loc al or remote computer. The InstanceID is unique, even when you have mul tiple sessions running in Windows PowerShell. The InstanceID is stored in the InstanceID property of the object that represents a PSSession. To find the InstanceID of the PSSessions in the current session, type "get-pssession | format-table Name, ComputerName , InstanceId". Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Name <string[]> Gets only the PSSessions with the specified friendly names. Wildcards a re permitted. To find the names of the PSSessions in the current session, type "get-p ssession" without parameters. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.Runspaces.PSSession Get-PSSession returns a PSSession object for each PSSession that it get s. NOTES Get-PSSession gets the PSSessions that were created in the current sess ion. It does not get the session that is created when you open Windows PowerShell, and it does not get PSSessions that were created in other s essions or on other computers, even if they connect to the local comput er. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-pssession Description ----------- This command gets all of the PSSessions that were created in the current se ssion. It does not get PSSessions that were created in other sessions or on other computers, even if they connect to this computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$s = get-pssession -computername Server02 Description ----------- This command gets the PSSessions that are connected to the Server02 compute r and saves them in the $p variable. -------------------------- EXAMPLE 3 -------------------------- C:\PS>new-pssession -computername Server01, Server02, Server03 C:\PS> $s1, $s2, $s3 = get-pssession Description ----------- This example shows how to save the results of a Get-PSSession command in mu ltiple variables. The first command uses the New-PSSession cmdlet to create PSSessions on thr ee remote computers. The second command uses a Get-PSSession cmdlet to get the three PSSessions. It then saves each of the PSSessions in a separate variable. When Windows PowerShell assigns an array of objects to an array of variable s, it assigns the first object to the first variable, the second object to the second variable, and so on. If there are more objects than variables, i t assigns all remaining objects to the last variable in the array. If there are more variables than objects, the extra variables are not used. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-pssession | format-table -property computername, InstanceID C:\PS> $s = get-pssession -InstanceID a786be29-a6bb-40da-80fb-782c67f7db0f C:\PS> remove-pssession -session $s Description ----------- This example shows how to get a PSSession by using its instance ID, and the n to delete the PSSession. The first command gets all of the PSSessions on the local computer. It send s the PSSessions to the Format-Table cmdlet, which displays the ComputerNam e and InstanceID properties of each PSSession. The second command uses the Get-PSSession cmdlet to get a particular PSSess ion and to save it in the $s variable. The command uses the InstanceID para meter to identify the PSSession. The third command uses the Remove-PSSession cmdlet to delete the PSSession in the $s variable. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-pssession -computername Serv* Description ----------- This command gets all the PSSessions that connect to computers that have co mputer names that begin with "Serv". -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-pssession -name Test*, Ux* Description ----------- This command gets PSSessions that have names that begin with "Test" or "Ux" . -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-pssession 2 Description ----------- This command gets the PSSession with ID 2. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135219 about_PSSessions about_Remote New-PSSession Remove-PSSession Enter-PSSession Exit-PSSession Invoke-Command Get-PSSessionConfiguration NAME Get-PSSessionConfiguration SYNOPSIS Gets the registered session configurations on the computer. SYNTAX Get-PSSessionConfiguration [[-Name] <string[]>] [<CommonParameters>] DESCRIPTION The Get-PSSessionConfiguration cmdlet gets the session configurations that have been registered on the local computer. This is an advanced cmdlet that is designed to be used by system administrators to manage customized sessi on configurations for their users. To create and register a session configuration, use the Register-PSSessionC onfiguration cmdlet. PARAMETERS -Name <string[]> Gets only the session configurations with the specified name or name pa ttern. Enter one or more session configuration names. Wildcards are per mitted. Required? false Position? 1 Default value All session configurations on the local co mputer Accept pipeline input? false Accept wildcard characters? true <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfi guration NOTES To run this cmdlet on Windows Vista, Windows Server 2008, and later ver sions of Windows, you must open Windows PowerShell with the "Run as adm inistrator" option. To view the session configurations on the computer, you must be a membe r of the Administrators group on the computer. To run a Get-PSSessionConfiguration command on a remote computer, Crede ntial Security Service Provider (CredSSP) authentication must be enable d in the client settings on the local computer (by using the Enable-WSM anCredSSP cmdlet) and in the service settings on the remote computer, a nd you must use the CredSSP value of the Authentication parameter when establishing the remote session. Otherwise, access is denied. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-pssessionconfiguration Description ----------- This command gets the session configurations on the computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-pssessionconfiguration -name Microsoft* Name PSVersion StartupScript Permission ---- --------- ------------- ---------- microsoft.powershell 2.0 BUILTIN\Administr ators AccessAll... microsoft.powershell32 2.0 BUILTIN\Administr ators AccessAll... Description ----------- This command uses the Name parameter of Get-PSSessionConfiguration to get o nly the session configurations with names that begin with "Microsoft". This command gets the two default session configurations that come with Win dows PowerShell. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Get-PSSessionConfiguration -name microsoft.powershell | get-member TypeName: Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#P SSessionConfiguration Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Capability NoteProperty System.Object[] Capability=System.Obj ect[] ExactMatch NoteProperty System.String ExactMatch=False Filename NoteProperty System.String Filename=%windir%\syste m32\pwrshplugin.dll lang NoteProperty System.String lang=en-US Name NoteProperty System.String Name=microsoft.powershe ll PSVersion NoteProperty System.String PSVersion=2.0 ResourceUri NoteProperty System.String ResourceUri=http://sche mas.microsoft.com/powershell/microsoft.powershell SDKVersion NoteProperty System.String SDKVersion=1 SecurityDescriptorSddl NoteProperty System.String SecurityDescriptorSddl= O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD) SupportsOptions NoteProperty System.String SupportsOptions=true Uri NoteProperty System.String Uri=http://schemas.micr osoft.com/powershell/microsoft.powershell xmlns NoteProperty System.String xmlns=http://schemas.mi crosoft.com/wbem/wsman/1/config/PluginConfiguration XmlRenderingType NoteProperty System.String XmlRenderingType=text Permission ScriptProperty System.Object Permission {get=trap { continue; }... C:\PS> Get-PSSessionConfiguration -name microsoft.powershell | format-list -property * Name : microsoft.powershell Filename : %windir%\system32\pwrshplugin.dll SDKVersion : 1 XmlRenderingType : text lang : en-US PSVersion : 2.0 ResourceUri : http://schemas.microsoft.com/powershell/microsoft. powershell SupportsOptions : true Capability : {Shell} Uri : http://schemas.microsoft.com/powershell/microsoft. powershell SecurityDescriptorSddl : O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GX GW;;;WD) ExactMatch : False xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/P luginConfiguration Permission : BUILTIN\Administrators AccessAllowed Description ----------- These commands examine the PSSessionConfiguration object that Get-PSSession Configuration returns. The first command uses the Get-PSSessionConfiguration cmdlet to get the Mic rosoft.PowerShell default configuration. The second command uses a pipeline operator (|) to send the object that Get -PSSessionConfiguration returns to the Get-Member cmdlet. The output shows the properties and methods of the object. The third command sends the same object to the Format-List cmdlet. The Prop erty parameter with a value of * (all) directs Format-List to display all o f the properties and property values of the object in a list. The output of this command has very useful information, including the locat ion of the .dll that implements the configuration type, the resource Unifor m Resource Identifier (URI) for the endpoint that is created, and the Secur ity Descriptor Definition Language (SDDL) for the configuration. -------------------------- EXAMPLE 4 -------------------------- C:\PS>dir wsman:\localhost\plugin WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin Name Type Keys ---- ---- ---- Event Forwarding Plugin Container {Name=Event Forwarding Plugi n} MaintenanceShell Container {Name=MaintenanceShell} microsoft.powershell Container {Name=microsoft.powershell} microsoft.powershell32 Container {Name=microsoft.powershell32 } WMI Provider Container {Name=WMI Provider} Description ----------- This command uses the Get-ChildItem cmdlet (alias = dir) in the WSMan: prov ider drive to look at the content of the Plugin node. This is another way to look at the session configurations on the computer. The PlugIn node contains ContainerElement objects (Microsoft.WSMan.Manageme nt.WSManConfigContainerElement) that represent the registered Windows Power Shell session configurations, along with other plug-ins for WS-Management. -------------------------- EXAMPLE 5 -------------------------- C:\PS>enable-wsmanCredSSP -delegate server02 C:\PS> connect-wsman server02 C:\PS> set-item wsman:\server02*\service\auth\credSSP -value $true C:\PS> invoke-command -scriptblock {Get-PSSessionConfiguration} -computerna me Server02 -authentication CredSSP -credential Domain01\Admin01 Name PSVersion StartupScript Permission PSComputerName ---- --------- ------------- ---------- -------------- microsoft.powershell 2.0 BUILTIN\Administr ators AccessAll... server02.corp.fabrikam.com microsoft.powershell32 2.0 BUILTIN\Administr ators AccessAll... server02.corp.fabrikam.com MyX86Shell 2.0 c:\test\x86Shell.ps1 BUILTIN\Administr ators AccessAll... server02.corp.fabrikam.com Description ----------- This example shows how to run a Get-PSSessionConfiguration command on a rem ote computer. The command requires that CredSSP delegation be enabled in th e client settings on the local computer and in the service settings on the remote computer. To run the commands in this example, you must be a member of the Administrators group on the local computer and the remote computer. The first command uses the Enable-WSManCredSSP cmdlet to enable CredSSP del egation from the Server01 local computer to the Server02 remote computer. T his configures the CredSSP client setting on the local computer. The second command uses the Connect-WSMan cmdlet to connect to the Server02 computer. This action adds a node for the Server02 computer to the WSMan: drive on the local computer, allowing you to view and change the WS-Managem ent settings on the Server02 computer. The third command uses the Set-Item cmdlet to change the value of the CredS SP item in the Service node of the Server02 computer to True. This configur es the service settings on the remote computer. The fourth command uses the Invoke-Command cmdlet to run a Get-PSSessionCon figuration command on the Server02 computer. The command uses the Credentia l parameter, and it uses the Authentication parameter with a value of CredS SP. -------------------------- EXAMPLE 6 -------------------------- C:\PS>(get-PSSessionConfiguration -name CustomShell).resourceURI http://schemas.microsoft.com/powershell/microsoft.CustomShell Description ----------- This command uses the Get-PSSessionConfiguration cmdlet to get the resource URI of a session configuration. This command is useful when setting the value of the $PSSessionConfiguratio nName preference variable, which takes a resource URI. The $PSSessionConfiguationName variable specifies the default configuration that is used when you create a session. This variable is set on the local computer, but it specifies a configuration on the remote computer. For more information about the $PSSessionConfiguration variable, see about_Preferen ce_Variables. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144304 about_Session_Configurations Disable-PSSessionConfiguration Enable-PSSessionConfiguration Register-PSSessionConfiguration Set-PSSessionConfiguration Unregister-PSSessionConfiguration WS-Management Provider Get-PSSnapin NAME Get-PSSnapin SYNOPSIS Gets the Windows PowerShell snap-ins on the computer. SYNTAX Get-PSSnapin [[-Name] <string[]>] [-Registered] [<CommonParameters>] DESCRIPTION The Get-PSSnapin cmdlet gets the Windows PowerShell snap-ins that have been added to the current session or that have been registered on the system. T he snap-ins are listed in the order in which they are detected. Get-PSSnapin gets only registered snap-ins. To register a Windows PowerShel l snap-in, use the InstallUtil tool included with the Microsoft .NET Framew ork 2.0. For more information, see "How to Register Cmdlets, Providers, and Host Applications" in the MSDN (Microsoft Developer Network) library at ht tp://go.microsoft.com/fwlink/?LinkId=143619. PARAMETERS -Name <string[]> Gets only the specified Windows PowerShell snap-ins. Enter the names of one or more Windows PowerShell snap-ins. Wildcards are permitted. The parameter name ("Name") is optional. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Registered [<SwitchParameter>] Gets the Windows PowerShell snap-ins that have been registered on the s ystem (even if they have not yet been added to the session). The snap-ins that are installed with Windows PowerShell do not appear i n this list. Without this parameter, Get-PSSnapin gets the Windows PowerShell snap-i ns that have been added to the session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to Get-PSSnapin. OUTPUTS System.Management.Automation.PSSnapInInfo Get-PSSnapin returns an object for each snap-in that it gets. NOTES You can refer to Get-PSSnapin by its built-in alias, "psnp". For more i nformation, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-PSSnapIn Description ----------- This command gets the Windows PowerShell snap-ins that are currently loaded in the session. This includes the snap-ins that are installed with Windows PowerShell and those that have been added to the session. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-PSSnapIn -registered Description ----------- This command gets the Windows PowerShell snap-ins that have been registered on the computer, including those that have already been added to the sessi on. The output does not include snap-ins that are installed with Windows Po werShell or Windows PowerShell snap-in dynamic-link libraries (DLLs) that h ave not yet been registered on the system. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-PSSnapIn smp* Description ----------- This command gets the Windows PowerShell snap-ins in the current session th at have names that begin with "smp". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113330 Add-PSSnapin Remove-PSSnapin Get-Random NAME Get-Random SYNOPSIS Gets a random number, or selects objects randomly from a collection. SYNTAX Get-Random [-InputObject] <Object[]> [-Count <int>] [-SetSeed <int>] [ onParameters>] Get-Random [[-Maximum] <Object>] [-Minimum <Object>] [-SetSeed <int>] [ monParameters>] DESCRIPTION The Get-Random cmdlet gets a randomly selected number. If you submit a coll ection of objects to Get-Random, it gets one or more randomly selected obje cts from the collection. Without parameters or input, a Get-Random command returns a randomly select ed 32-bit unsigned integer between 0 (zero) and Int32.MaxValue (0x7FFFFFFF, 2,147,483,647). You can use the parameters of Get-Random to specify a seed number, minimum and maximum values, and the number of objects returned from a submitted col lection. PARAMETERS -Count <int> Determines how many objects are returned. The default is 1. If the valu e of Count exceeds the number of objects in the collection, Get-Random returns all of the objects in random order. Required? false Position? named Default value 1 Accept pipeline input? false Accept wildcard characters? false -InputObject <Object[]> Specifies a collection of objects. Get-Random gets randomly selected ob jects in random order from the collection. Enter the objects, a variabl e that contains the objects, or a command or expression that gets the o bjects. You can also pipe a collection of objects to Get-Random. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Maximum <Object> Specifies a maximum value for the random number. Get-Random returns a v alue that is less than the maximum (not equal). Enter a 32-bit integer or a double-precision floating-point number, or an object that can be c onverted to an integer or double, such as a numeric string ("100"). The value of Maximum must be greater than (not equal to) the value of Mini mum. If the value of Maximum or Minimum is a floating-point number, Get-Rand om returns a randomly selected floating-point number. If the value of Minimum is a double (a floating-point number), the defa ult value of Maximum is Double.MaxValue. Otherwise, the default value i s Int32.MaxValue (2,147,483,647 or 0x7FFFFFFF). Required? false Position? 1 Default value Int32.MaxValue Accept pipeline input? false Accept wildcard characters? false -Minimum <Object> Specifies a minimum value for the random number. Enter a 32-bit integer or a double-precision floating-point number, or an object that can be converted to an integer or double, such as a numeric string ("100"). Th e default value is 0 (zero). The value of Minimum must be less than (not equal to) the value of Maxi mum. If the value of Maximum or Minimum is a floating-point number, Get -Random returns a randomly selected floating-point number. Required? false Position? named Default value 0 Accept pipeline input? false Accept wildcard characters? false -SetSeed <int> Specifies a seed value for the random number generator. This seed value is used for the current command and for all subsequent Get-Random comm ands in the current session until you use SetSeed again or close the se ssion. You cannot reset the seed to its default, clock-based value. The SetSeed parameter is not required. By default, Get-Random uses the system clock to generate a seed value. Because SetSeed results in non-r andom behavior, it is typically used only when trying to reproduce beha vior, such as when debugging or analyzing a script that includes Get-Ra ndom commands. Required? false Position? named Default value System clock Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe one or more objects to Get-Random. Get-Random selects valu es randomly from the piped objects. OUTPUTS System.Object Get-Random returns an integer or floating-point number, or an object se lected randomly from a submitted collection. NOTES Get-Random sets a default seed for each session based on the system tim e clock when the session starts. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-random 3951433 Description ----------- This command gets a random integer between 0 (zero) and Int32.MaxValue. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-random -maximum 100 47 Description ----------- This command gets a random integer between 0 (zero) and 99. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-random -minimum -100 -maximum 100 -56 Description ----------- This command gets a random integer between -100 and 99. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-random -min 10.7 -max 20.93 18.08467273887 Description ----------- This command gets a random floating-point number greater than or equal to 1 0.7 and less than 20.92. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-random -input 1, 2, 3, 5, 8, 13 8 Description ----------- This command gets a randomly selected number from the specified array. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-random -input 1, 2, 3, 5, 8, 13 -count 3 3 1 13 Description ----------- This command gets three randomly selected numbers in random order from the array. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-random -input 1, 2, 3, 5, 8, 13 -count ([int]::MaxValue) 2 3 5 1 8 13 Description ----------- This command returns the entire collection in random order. The value of th e Count parameter is the MaxValue static property of integers. To return an entire collection in random order, enter any number that is gr eater than or equal to the number of objects in the collection. -------------------------- EXAMPLE 8 -------------------------- C:\PS>get-random -input "red", "yellow", "blue" yellow Description ----------- This command returns a random value from a non-numeric collection. -------------------------- EXAMPLE 9 -------------------------- C:\PS>get-process | get-random Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 144 4 2080 488 36 0.48 3164 wmiprvse Description ----------- This command gets a randomly selected process from the collection of proces ses on the computer. -------------------------- EXAMPLE 10 -------------------------- C:\PS>get-content servers.txt | get-random -count (get-content servers.txt) .count | foreach {invoke-expression -computer $_ -command 'get-process powe rshell'} Description ----------- This command runs a command on a series of remote computers in random order . -------------------------- EXAMPLE 11 -------------------------- C:\PS>get-random -max 100 -setseed 23 # Commands with the default seed are pseudorandom PS C:\ps-test> get-random -max 100 59 PS C:\ps-test> get-random -max 100 65 PS C:\ps-test> get-random -max 100 21 # Commands with the same seed are not random PS C:\ps-test> get-random -max 100 -setseed 23 74 PS C:\ps-test> get-random -max 100 -setseed 23 74 PS C:\ps-test> get-random -max 100 -setseed 23 74 # SetSeed results in a repeatable series PS C:\ps-test> get-random -max 100 -setseed 23 74 PS C:\ps-test> get-random -max 100 56 PS C:\ps-test> get-random -max 100 84 PS C:\ps-test> get-random -max 100 46 PS C:\ps-test> get-random -max 100 -setseed 23 74 PS C:\ps-test> get-random -max 100 56 PS C:\ps-test> get-random -max 100 84 PS C:\ps-test> get-random -max 100 46 Description ----------- This example shows the effect of using the SetSeed parameter. Because SetSe ed produces non-random behavior, it is typically used only to reproduce res ults, such as when debugging or analyzing a script. -------------------------- EXAMPLE 12 -------------------------- C:\PS>$files = dir -path c:\* -recurse C:\PS> $sample = $files | get-random -count 50 Description ----------- These commands get a randomly selected sample of 50 files from the C: drive of the local computer. -------------------------- EXAMPLE 13 -------------------------- C:\PS>get-random 10001 7600 Description ----------- This command gets a random integer less than 10001. Because the Maximum par ameter has position 1, you can omit the parameter name when the value is th e first or only unnamed parameter in the command. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113446 Get-Service NAME Get-Service SYNOPSIS Gets the services on a local or remote computer. SYNTAX Get-Service [[-Name] <string[]>] [-ComputerName <string[]>] [-DependentServ ices] [-Exclude <string[]>] [-Include <string[]>] [-RequiredServices] [<Com monParameters>] Get-Service -DisplayName <string[]> [-ComputerName <string[]>] [-DependentS ervices] [-Exclude <string[]>] [-Include <string[]>] [-RequiredServices] [ CommonParameters>] Get-Service [-InputObject <ServiceController[]>] [-ComputerName <string[]>] [-DependentServices] [-Exclude <string[]>] [-Include <string[]>] [-Require dServices] [<CommonParameters>] DESCRIPTION The Get-Service cmdlet gets objects that represent the services on a local computer or on a remote computer, including running and stopped services. You can direct Get-Service to get only particular services by specifying th e service name or display name of the services, or you can pipe service obj ects to Get-Service. PARAMETERS -ComputerName <string[]> Gets the services running on the specified computers. The default is th e local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Get-Service even if your computer is no t configured to run remote commands. Required? false Position? named Default value Localhost Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -DependentServices [<SwitchParameter>] Gets only the services that depend upon the specified service. By default, Get-Service gets all services. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -DisplayName <string[]> Specifies the display names of services to be retrieved. Wildcards are permitted. By default, Get-Service gets all services on the computer. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Retrieves only the specified services. The value of this parameter qual ifies the Name parameter. Enter a name element or pattern, such as "s*" . Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ServiceController[]> Specifies ServiceController objects representing the services to be ret rieved. Enter a variable that contains the objects, or type a command o r expression that gets the objects. You can also pipe a service object to Get-Service. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the service names of services to be retrieved. Wildcards are permitted. By default, Get-Service gets all of the services on the comp uter. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true -RequiredServices [<SwitchParameter>] Gets only the services that this service requires. This parameter gets the value of the ServicesDependedOn property of the service. By default, Get-Service gets all services. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.ServiceProcess.ServiceController, System.String You can pipe a service object or a service name to Get-Service. OUTPUTS System.ServiceProcess.ServiceController Get-Service returns objects that represent the services on the computer . NOTES You can also refer to Get-Service by its built-in alias, "gsv". For mor e information, see about_Aliases. Get-Service can display services only when the current user has permiss ion to see them. If Get-Service does not display services, you might no t have permission to see them. To find the service name and display name of each service on your syste m, type "get-service". The service names appear in the Name column, and the display names appear in the DisplayName column. When you sort in ascending order by status value, "Stopped" services ap pear before "Running" services. The Status property of a service is an enumerated value in which the names of the statuses represent integer v alues. The sort is based on the integer value, not the name. "Running" appears before "Stopped" because "Stopped" has a value of "1", and "Run ning" has a value of "4". -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-service Description ----------- This command retrieves all of the services on the system. It behaves as tho ugh you typed "get-service *". The default display shows the status, servic e name, and display name of each service. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-service wmi* Description ----------- This command retrieves services with service names that begin with "WMI" (t he acronym for Windows Management Instrumentation). -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-service -displayname *network* Description ----------- This command displays services with a display name that includes the word "network". Searching the display name finds network-related services even w hen the service name does not include "Net", such as xmlprov, the Network P rovisioning Service. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-service -name win* -exclude winrm Description ----------- These commands get only the services with service names that begin with "wi n", except for the WinRM service. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-service | where-object {$_.Status -eq "Running"} Description ----------- This command displays only the services that are currently running. It uses the Get-Service cmdlet to get all of the services on the computer. The pip eline operator (|) passes the results to the Where-Object cmdlet, which sel ects only the services with a Status property that equals "Running". Status is only one property of service objects. To see all of the propertie s, type "get-service | get-member". -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-service -computername Server02 Description ----------- This command gets the services on the Server02 remote computer. Because the ComputerName parameter of Get-Service does not use Windows Powe rShell remoting, you can use this parameter even if the computer is not con figured for remoting in Windows PowerShell. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-service | where-object {$_.DependentServices} | format-list -prop erty Name, DependentServices, @{Label="NoOfDependentS ervices"; Expression={$_.dependentservices.count}} Name : AudioEndpointBuilder DependentServices : {AudioSrv} NoOfDependentServices : 1 Name : Dhcp DependentServices : {WinHttpAutoProxySvc} NoOfDependentServices : 1 ... Description ----------- These commands list the services on the computer that have dependent servic es. The first command uses the Get-Service cmdlet to get the services on the co mputer. A pipeline operator (|) sends the services to the Where-Object cmdl et, which selects the services whose DependentServices property is not null . Another pipeline operator sends the results to the Format-List cmdlet. The command uses its Property parameter to display the name of the service, the name of the dependent services, and a calculated property that displays th e number of dependent services that each service has. -------------------------- EXAMPLE 8 -------------------------- C:\PS>C:\PS> get-service s* | sort-object status Status Name DisplayName ------ ---- ----------- Stopped stisvc Windows Image Acquisition (WIA) Stopped SwPrv MS Software Shadow Copy Provider Stopped SysmonLog Performance Logs and Alerts Running Spooler Print Spooler Running srservice System Restore Service Running SSDPSRV SSDP Discovery Service Running ShellHWDetection Shell Hardware Detection Running Schedule Task Scheduler Running SCardSvr Smart Card Running SamSs Security Accounts Manager Running SharedAccess Windows Firewall/Internet Connectio... Running SENS System Event Notification Running seclogon Secondary Logon C:\PS> get-service s* | sort-object status -descending Status Name DisplayName ------ ---- ----------- Running ShellHWDetection Shell Hardware Detection Running SharedAccess Windows Firewall/Internet Connectio... Running Spooler Print Spooler Running SSDPSRV SSDP Discovery Service Running srservice System Restore Service Running SCardSvr Smart Card Running SamSs Security Accounts Manager Running Schedule Task Scheduler Running SENS System Event Notification Running seclogon Secondary Logon Stopped SysmonLog Performance Logs and Alerts Stopped SwPrv MS Software Shadow Copy Provider Stopped stisvc Windows Image Acquisition (WIA) Description ----------- This command shows that when you sort services in ascending order by the va lue of their Status property, stopped services appear before running servic es. This happens because the value of Status is an enumeration, in which "S topped" has a value of "1", and "Running" has a value of 4. To list running services first, use the Descending parameter of the Sort-Ob ject cmdlet. -------------------------- EXAMPLE 9 -------------------------- C:\PS>get-service -name winrm -computername localhost, Server01, Server02 | format-table -property MachineName, Status, Name, DisplayName -auto MachineName Status Name DisplayName ------------ ------ ---- ----------- localhost Running WinRM Windows Remote Management (WS-Management) Server01 Running WinRM Windows Remote Management (WS-Management) Server02 Running WinRM Windows Remote Management (WS-Management) Description ----------- This command uses the Get-Service cmdlet to run a "Get-Service Winrm" comma nd on two remote computers and the local computer ("localhost"). The Get-Service command runs on the remote computers, and the results are r eturned to the local computer. A pipeline operator (|) sends the results to the Format-Table cmdlet, which formats the services as a table. The Format -Table command uses the Property parameter to specify the properties displa yed in the table, including the MachineName property. -------------------------- EXAMPLE 10 -------------------------- C:\PS>get-service winrm -requiredServices Description ----------- This command gets the services that the WinRM service requires. The command returns the value of the ServicesDependedOn property of the ser vice. -------------------------- EXAMPLE 11 -------------------------- C:\PS>"winrm" | get-service Description ----------- This command gets the WinRM service on the local computer. This example sho ws that you can pipe a service name string (enclosed in quotation marks) to Get-Service. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113332 Start-Service Stop-Service Restart-Service Resume-Service Suspend-Service Set-Service New-Service Get-TraceSource NAME Get-TraceSource SYNOPSIS Gets the Windows PowerShell components that are instrumented for tracing. SYNTAX Get-TraceSource [[-Name] <string[]>] [<CommonParameters>] DESCRIPTION The Get-TraceSource cmdlet gets the trace sources for Windows PowerShell co mponents that are currently in use. You can use the data to determine which Windows PowerShell components you can trace. When tracing, the component g enerates detailed messages about each step in its internal processing. Deve lopers use the trace data to monitor data flow, program execution, and erro rs. The tracing cmdlets were designed for Windows PowerShell developers, bu t they are available to all users. PARAMETERS -Name <string[]> Gets only the specified trace sources. Wildcards are permitted. The par ameter name ("Name") is optional. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains the name of a trace source to Get-T raceSource. OUTPUTS System.Management.Automation.PSTraceSource Get-TraceSource returns objects that represent the trace sources. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-traceSource *provider* Description ----------- This command gets all of the trace sources that have names that include "pr ovider". -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-tracesource Description ----------- This command gets all of the Windows PowerShell components that can be trac ed. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113333 Set-TraceSource Trace-Command Get-Transaction NAME Get-Transaction SYNOPSIS Gets the current (active) transaction. SYNTAX Get-Transaction [<CommonParameters>] DESCRIPTION The Get-Transaction cmdlet gets an object that represents the current trans action in the session. This cmdlet never returns more than one object, because only one transactio n is active at a time. If you start one or more independent transactions (b y using the Independent parameter of Start-Transaction), the most recently started transaction is active, and that is the transaction that Get-Transac tion returns. When all active transactions have either been rolled back or committed, Get -Transaction shows the transaction that was most recently active in the ses sion. The Get-Transaction cmdlet is one of a set of cmdlets that support the tran sactions feature in Windows PowerShell. For more information, see about_Tra nsactions. PARAMETERS <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS System.Management.Automation.PSTransaction Get-Transaction returns an object that represents the current transacti on. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>start-transaction C:\PS> get-transaction RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active Description ----------- This command uses the Get-Transaction cmdlet to get the current transaction . -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-transaction | get-member Name MemberType Definition ---- ---------- ---------- Dispose Method System.Void Dispose(), System.Void Dispose(Bo olean disposing) Equals Method System.Boolean Equals(Object obj) GetHashCode Method System.Int32 GetHashCode() GetType Method System.Type GetType() ToString Method System.String ToString() IsCommitted Property System.Boolean IsCommitted {get;} IsRolledBack Property System.Boolean IsRolledBack {get;} RollbackPreference Property System.Management.Automation.RollbackSeverity RollbackPreference {get;} SubscriberCount Property System.Int32 SubscriberCount {get;set;} Description ----------- This command uses the Get-Member cmdlet to show the properties and methods of the transaction object. -------------------------- EXAMPLE 3 -------------------------- C:\PS>cd hklm:\software HKLM:\SOFTWARE> Start-Transaction HKLM:\SOFTWARE> New-Item MyCompany -UseTransaction HKLM:\SOFTWARE> Undo-Transaction HKLM:\SOFTWARE> Get-Transaction RollbackPreference SubscriberCount Status ------------------ --------------- ---------- Error 0 RolledBack Description ----------- This command shows the property values of a transaction object for a transa ction that has been rolled back. -------------------------- EXAMPLE 4 -------------------------- C:\PS>cd hklm:\software HKLM:\SOFTWARE> Start-Transaction HKLM:\SOFTWARE> New-Item MyCompany -UseTransaction HKLM:\SOFTWARE> Complete-Transaction HKLM:\SOFTWARE> Get-Transaction RollbackPreference SubscriberCount Status ------------------ --------------- --------- Error 1 Committed Description ----------- This command shows the property values of a transaction object for a transa ction that has been committed. -------------------------- EXAMPLE 5 -------------------------- C:\PS>cd hklm:\software HKLM:\SOFTWARE> Start-Transaction HKLM:\SOFTWARE> New-Item MyCompany -UseTransaction HKLM:\SOFTWARE> Start-Transaction HKLM:\SOFTWARE> New-Item MyCompany2 -UseTransaction HKLM:\SOFTWARE> Get-Transaction RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 2 Active HKLM:\SOFTWARE> Complete-Transaction HKLM:\SOFTWARE> Get-Transaction RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active HKLM:\SOFTWARE> Complete-Transaction HKLM:\SOFTWARE> Get-Transaction RollbackPreference SubscriberCount Status ------------------ --------------- --------- Error 1 Committed Description ----------- This example shows the effect on the transaction object of starting a trans action while another transaction is in progress. Typically, this happens wh en a script that runs a transaction includes a function or calls a script t hat contains another complete transaction. Unless the second Start-Transaction command includes the Independent parame ter, Start-Transaction does not create a new transaction. Instead, it adds a second subscriber to the original transaction. The first Start-Transaction command starts the transaction. A New-Item comm and with the UseTransaction parameter is part of the transaction. A second Start-Transaction command adds a subscriber to the transaction. Th e next New-Item command is also part of the transaction. The first Get-Transaction command shows the multi-subscriber transaction. N otice that the subscriber count is 2. The first Complete-Transaction command does not commit the transaction, but it reduces the subscriber count to 1. The second Complete-Transaction command commits the transaction. -------------------------- EXAMPLE 6 -------------------------- C:\PS>HKLM:\SOFTWARE> Start-Transaction HKLM:\SOFTWARE> Get-Transaction RollbackPreference SubscriberCount IsRolledBack IsCommitted ------------------ --------------- ------------ ----------- Error 1 False False HKLM:\SOFTWARE> Start-Transaction -Independent HKLM:\SOFTWARE> Get-Transaction RollbackPreference SubscriberCount IsRolledBack IsCommitted ------------------ --------------- ------------ ----------- Error 1 False False HKLM:\SOFTWARE> Complete-Transaction HKLM:\SOFTWARE> Get-Transaction HKLM:\SOFTWARE> Complete-Transaction HKLM:\SOFTWARE> Get-Transaction Description ----------- This example shows the effect on the transaction object of starting an inde pendent transaction while another transaction is in progress. The first Start-Transaction command starts the transaction. A New-Item comm and with the UseTransaction parameter is part of the transaction. A second Start-Transaction command adds a subscriber to the transaction. Th e next New-Item command is also part of the transaction. The first Get-Transaction command shows the multi-subscriber transaction. N ote that the subscriber count is 2. The Complete-Transaction command reduces the subscriber count to 1, but it does not commit the transaction. The second Complete-Transaction command commits the transaction. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135220 about_Transactions about_Providers Start-Transaction Complete-Transaction Undo-Transaction Use-Transaction Get-UICulture NAME Get-UICulture SYNOPSIS Gets the current user interface (UI) culture settings in the operating syst em. SYNTAX Get-UICulture [<CommonParameters>] DESCRIPTION The Get-UICulture cmdlet gets information about the current UI culture sett ings for Windows. The UI culture determines which text strings are used for user interface elements, such as menus and messages. You can also use the Get-Culture cmdlet, which gets the current culture on the system. The culture determines the display format of items such as numb ers, currency, and dates. PARAMETERS <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Globalization.CultureInfo Get-UICulture returns an object that represents the current UI culture. NOTES You can also use the $PsCulture and $PsUICulture variables. The $PsCult ure variable stores the name of the current culture, and the $PsUICultu re variable stores the name of the current UI culture. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-uiculture Description ----------- This command gets the current UI culture information. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-uiculture | format-list * Description ----------- This command displays the values of all of the properties of the current UI culture in a list. -------------------------- EXAMPLE 3 -------------------------- C:\PS>(get-uiculture).calendar Description ----------- This command displays the current values for the Calendar property of the c urrent UI culture. Calendar is just one property of UI culture. To see all of the properties, type "get-uiculture | get-member". -------------------------- EXAMPLE 4 -------------------------- C:\PS>(get-uiculture).datetimeformat.shortdatepattern Description ----------- This command displays the short date pattern for the current UI culture. To see all of the subproperties of the DateTimeFormat property of the UI cult ure, type "(get-uiculture).datetimeformat | gm". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113334 Get-Unique NAME Get-Unique SYNOPSIS Returns the unique items from a sorted list. SYNTAX Get-Unique [-AsString] [-InputObject <psobject>] [<CommonParameters>] Get-Unique [-OnType] [-InputObject <psobject>] [<CommonParameters>] DESCRIPTION The Get-Unique cmdlet compares each item in a sorted list to the next item, eliminates duplicates, and returns only one instance of each item. The lis t must be sorted for the cmdlet to work properly. PARAMETERS -AsString [<SwitchParameter>] Treats the data as a string. Without this parameter, data is treated as an object, so when you submit a collection of objects of the same type to Get-Unique, such as a collection of files, it returns just one (the first). You can use this parameter to find the unique values of object properties, such as the file names. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Accepts input for Get-Unique. Enter a variable that contains the object s or type a command or expression that gets the objects. Get-Unique treats the input submitted by using InputObject as a collect ion; it does not enumerate individual items in the collection. Because the collection is a single item, input submitted by using InputObject i s always returned unchanged. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -OnType [<SwitchParameter>] Returns only one object of each type. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any type of object to Get-Unique. OUTPUTS System.Management.Automation.PSObject The type of object that Get-Unique returns is determined by the input. NOTES You can also refer to Get-Unique by its built-in alias, "gu". For more information, see about_Aliases. To sort a list, use Sort-Object. You can also use the Unique parameter of Sort-Object to find the unique items in a list. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$a = $(foreach ($line in get-content C:\Test1\File1.txt) {$line.tolow er().split(" ")}) | sort | get-unique C:\PS> $a.count Description ----------- These commands find the number of unique words in a text file. The first command gets the content of the File.txt file. It converts each l ine of text to lowercase letters and then splits each word onto a separate line at the space (" "). Then, it sorts the resulting list alphabetically ( the default) and uses the Get-Unique cmdlet to eliminate any duplicate word s. The results are stored in the $a variable. The second command uses the Count property of the collection of strings in $a to determine how many items are in $a. -------------------------- EXAMPLE 2 -------------------------- C:\PS>1,1,1,1,12,23,4,5,4643,5,3,3,3,3,3,3,3 | sort-object | Get-Unique Description ----------- This command finds the unique members of the set of integers. The first com mand takes an array of integers typed at the command line, pipes them to th e Sort-Object cmdlet to be sorted, and then pipes them to Get-Unique, which eliminates duplicate entries. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-childitem | sort-object {$_.GetType()} | unique -OnType Description ----------- This command uses the Get-ChildItem cmdlet to retrieve the contents of the local directory, which includes files and directories. The pipeline operato r (|) sends the results to the Sort-Object cmdlet. The "$_.GetType()" state ment applies the GetType method to each file or directory. Then, Sort-Objec t sorts the items by type. Another pipeline operator sends the results to G et-Unique. The OnType parameter directs Get-Unique to return only one objec t of each type. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-process | sort-object | select processname | get-unique -asstring Description ----------- This command gets the names of processes running on the computer with dupli cates eliminated. The Get-Process command gets all of the processes on the computer. The pipe line operator (|) passes the result to Sort-Object, which, by default, sort s the processes alphabetically by ProcessName. The results are piped to the Select-Object cmdlet, which selects only the values of the ProcessName pro perty of each object. The results are then piped to Get-Unique to eliminate duplicates. The AsString parameter tells Get-Unique to treat the ProcessName values as strings. Without this parameter, Get-Unique treats the ProcessName values a s objects and returns only one instance of the object, that is, the first p rocess name in the list. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113335 Select-Object Sort-Object Get-Variable NAME Get-Variable SYNOPSIS Gets the variables in the current console. SYNTAX Get-Variable [[-Name] <string[]>] [-Exclude <string[]>] [-Include <string[] >] [-Scope <string>] [-ValueOnly] [<CommonParameters>] DESCRIPTION The Get-Variable cmdlet gets the Windows PowerShell variables in the curren t console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name. PARAMETERS -Exclude <string[]> Omits the specified items. Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Specifies only the items upon which the cmdlet will act, excluding all others. Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the name of the variable. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Scope <string> Gets only the variables in the specified scope. Valid values are "Globa l", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scope s. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ValueOnly [<SwitchParameter>] Gets only the value of the variable. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains the variable name to Get-Variable. OUTPUTS Variable object Get-Variable returns a System.Management.Automation variable object for each variable that it gets. The object type depends on the variable. NOTES This cmdlet does not manage environment variables. To manage environmen t variables, you can use the environment variable provider. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-variable m* Description ----------- This command displays variables with names that begin with the letter "m". The value of the variables is also displayed. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-variable m* -valueonly Description ----------- This command displays only the values of the variables with names that begi n with the letter "m". -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-variable -include M*,P* | sort-object name Description ----------- This command gets information about the variables that begin with either th e letter "M" or the letter "P". The results are piped to the Sort-Object cm dlet, sorted by name, and displayed. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-variable -scope 0 C:\PS> compare-object (get-variable -scope 0) (get-variable -scope 1) Description ----------- The first command gets only the variables that are defined in the local sco pe. It is equivalent to "get-variable -scope local" and can be abbreviated as "gv -s 0". The second command uses the Compare-Object cmdlet to find the variables tha t are defined in the parent scope (Scope 1) but are visible only in the loc al scope (Scope 0). RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113336 Set-Variable New-Variable Clear-Variable Remove-Variable Get-Verb Get-Verb [[-verb] <String[]>] [-Verbose] [-Debug] [-ErrorAction <ActionPreferen ce>] [-WarningAction <ActionPreference>] [-ErrorVariable <String>] [-WarningVar iable <String>] [-OutVariable <String>] [-OutBuffer <Int32>] Get-WinEvent NAME Get-WinEvent SYNOPSIS Gets events from event logs and event tracing log files on local and remote computers. SYNTAX Get-WinEvent [-LogName] <string[]> [-ComputerName <string>] [-Credential <P SCredential>] [-FilterXPath <string>] [-Force <switch>] [-MaxEvents <int64> ] [-Oldest] [<CommonParameters>] Get-WinEvent [-Path] <string[]> [-ComputerName <string>] [-Credential <PSCr edential>] [-FilterXPath <string>] [-Force <switch>] [-MaxEvents <int64>] [ -Oldest] [<CommonParameters>] Get-WinEvent [-ProviderName] <string[]> [-ComputerName <string>] [-Credenti al <PSCredential>] [-FilterXPath <string>] [-Force <switch>] [-MaxEvents nt64>] [-Oldest] [<CommonParameters>] Get-WinEvent -FilterHashTable <Hashtable[]> [-ComputerName <string>] [-Cred ential <PSCredential>] [-Force <switch>] [-MaxEvents <int64>] [-Oldest] [ ommonParameters>] Get-WinEvent [-ListLog] <string[]> [-ComputerName <string>] [-Credential <P SCredential>] [<CommonParameters>] Get-WinEvent [-ListProvider] <string[]> [-ComputerName <string>] [-Credenti al <PSCredential>] [<CommonParameters>] Get-WinEvent -FilterXml <XmlDocument> [-ComputerName <string>] [-Credential <PSCredential>] [-Force <switch>] [-MaxEvents <int64>] [-Oldest] [ arameters>] DESCRIPTION The Get-WinEvent cmdlet gets events from event logs, including classic logs , such as the System and Application logs, and the event logs that are gene rated by the new Windows Event Log technology introduced in Windows Vista. It also gets events in log files generated by Event Tracing for Windows (ET W). Without parameters, a Get-WinEvent command gets all the events from all the event logs on the computer. To interrupt the command, press CTRL + C. Get-WinEvent also lists event logs and event log providers. You can get eve nts from selected logs or from logs generated by selected event providers. And, you can combine events from multiple sources in a single command. Get- WinEvent allows you to filter events by using XPath queries, structured XML queries, and simplified hash-table queries. Note: Get-WinEvent requires Windows Vista, Windows Server 2008 R2, or later versions of Windows. And, it requires the Microsoft .NET Framework 3.5 or a later version. PARAMETERS -ComputerName <string> Gets events from the event logs on the specified computer. Type the Net BIOS name, an Internet Protocol (IP) address, or the fully qualified do main name of the computer. The default value is the local computer. This parameter accepts only one computer name at a time. To find event logs or events on multiple computers, use a ForEach statement. For more information about this parameter, see the examples. To get events and event logs from remote computers, the firewall port f or the event log service must be configured to allow remote access. This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter even if your computer is not configured to run remote commands. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default value is the current user. Type a user name, such as User01 or Domain01\User01. Or, enter a PSCred ential object, such as one generated by the Get-Credential cmdlet. If y ou type a user name, you will be prompted for a password. If you type o nly the parameter name, you will be prompted for both a user name and a password. Required? false Position? named Default value Current user Accept pipeline input? false Accept wildcard characters? false -FilterHashTable <Hashtable[]> Uses a query in hash table format to select events from one or more eve nt logs. The query contains a hash table with one or more key-value pai rs. Hash table queries have the following rules: -- Keys and values are case-insensitive. -- Wildcard characters are valid only in the values associated with the LogName and ProviderName keys. -- Each key can be listed only once in each hash-table. -- The Path value takes paths to .etl, .evt, and .evtx log files. -- The LogName, Path, and ProviderName keys can be used in the same que ry. -- The UserID key can take a valid security identifier (SID) or a domai n account name that can be used to construct a valid System.Security.Pr incipal.NTAccount object. -- The Data value takes event data in an unnamed field. This is for eve nts in classic event logs. -- The * key represents a named event data field. When Get-WinEvent cannot interpret a key-value pair, it interprets the key as a case-sensitive name for the event data in the event. The valid key-value pairs are as follows: -- LogName=<String[]> -- ProviderName=<String[]> -- Path=<String[]> -- Keywords=<Long[]> -- ID=<Int32[]> -- Level=<Int32[]> -- StartTime=<DateTime> -- EndTime=<DataTime> -- UserID=<SID> -- Data=<String[]> -- *=<String[]> Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -FilterXml <XmlDocument> Uses a structured XML query to select events from one or more event log s. To generate a valid XML query, use the Create Custom View and Filter Cu rrent Log features in Event Viewer. Use the items in the dialog box to create a query, and then click the XML tab to view the query in XML for mat. You can copy the XML from the XML tab into the value of the Filter Xml parameter. For more information about the Event Viewer features, se e Event Viewer Help. Typically, you use an XML query to create a complex query that contains several XPath statements. The XML format also allows you to use a "Sup press" XML element that excludes events from the query. For more inform ation about the XML schema for event log queries, see the following top ics in the MSDN (Microsoft Developer Network) library. -- "Query Schema": http://go.microsoft.com/fwlink/?LinkId=143685 -- "XML Event Queries" in "Event Selection": http://go.microsoft.com/fw link/?LinkID=143608 Required? true Position? named Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? false -FilterXPath <string> Uses an XPath query to select events from one or more logs. For more information about the XPath language, see "Selection Filters" in "Event Selection" and in the "XPath Reference" in the MSDN library. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Force <switch> Gets debug and analytic logs, in addition to other event logs. The Forc e parameter is required to get a debug or analytic log when the value o f the name parameter includes wildcard characters. By default, Get-WinEvent excludes these logs unless you specify the ful l name of a debug or analytic log. Required? false Position? named Default value Debugging and analytic logs are not return ed in response to queries that use wildcard characters. Accept pipeline input? false Accept wildcard characters? false -ListLog <string[]> Gets the specified event logs. Enter the event log names in a comma-sep arated list. Wildcards are permitted. To get all the logs, enter a valu e of *. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? true -ListProvider <string[]> Gets the specified event log providers. An event log provider is a prog ram or service that writes events to the event log. Enter the provider names in a comma-separated list. Wildcards are permi tted. To get the providers of all the event logs on the computer, enter a value of *. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? true -LogName <string[]> Gets events from the specified event logs. Enter the event log names in a comma-separated list. Wildcards are permitted. You can also pipe log names to Get-WinEvent. Required? true Position? 1 Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? true -MaxEvents <int64> Specifies the maximum number of events that Get-WinEvent returns. Enter an integer. The default is to return all the events in the logs or fil es. Required? false Position? named Default value All events Accept pipeline input? false Accept wildcard characters? false -Oldest [<SwitchParameter>] Returns the events in oldest-first order. By default, events are retur ned in newest-first order. This parameter is required to get events from .etl and .evt files and f rom debug and analytic logs. In these files, events are recorded in old est-first order, and the events can be returned only in oldest-first or der. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Gets events from the specified event log files. Enter the paths to the log files in a comma-separated list, or use wildcard characters to crea te file path patterns. Get-WinEvent supports files with the .evt, .evtx, and .etl file name ex tensions. You can include events from different files and file types in the same command. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? true -ProviderName <string[]> Gets events written by the specified event log providers. Enter the pro vider names in a comma-separated list, or use wildcard characters to cr eate provider name patterns. An event log provider is a program or service that writes events to the event log. It is not a Windows PowerShell provider. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? true <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String, System.Xml.XmlDocument, System.Collections.Hashtable. You can pipe a LogName (string), a FilterXML query, or a FilterHashTabl e query to Get-WinEvent. OUTPUTS System.Diagnostics.Eventing.Reader.EventLogConfiguration, System.Diagnostic s.Eventing.Reader.EventLogRecord, System.Diagnostics.Eventing.Reader.Provid erMetadata With the ListLog parameter, Get-WinEvent returns System.Diagnostics.Eve nting.Reader.EventLogConfiguration objects. With the ListProvider para meter, Get-WinEvent returns System.Diagnostics.Eventing.Reader.ProviderMetadata objects. With all other parameters, Get-WinEvent returns System.Diagnostics.Eventing.Read er.EventLogRecord objects. NOTES Get-WinEvent is designed to replace the Get-EventLog cmdlet on computer s running Windows Vista and later versions of Windows. Get-EventLog get s events only in classic event logs. Get-EventLog is retained in Window s PowerShell 2.0 for systems earlier than Windows Vista. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-winevent -listlog * Description ----------- This command gets all the logs on the local computer. Logs are listed in the order that Get-WinEvent gets them. Classic logs are usually retrieved first, followed by the new Windows Eventing logs. Because there are typically more than a hundred event logs, this parameter requires a log name or name pattern. To get all the logs, use *. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-winevent -listlog Setup | format-list -property * FileSize : 69632 IsLogFull : False LastAccessTime : 2/14/2008 12:55:12 AM LastWriteTime : 7/9/2008 3:12:05 AM OldestRecordNumber : 1 RecordCount : 3 LogName : Setup LogType : Operational LogIsolation : Application IsEnabled : True IsClassicLog : False SecurityDescriptor : O:BAG:SYD:(A;;0xf0007;;;SY)(A; (A;;0x1;;;S-1-5-32-573) LogFilePath : %SystemRoot%\System32\Winevt\L MaximumSizeInBytes : 1052672 LogMode : Circular OwningProviderName : Microsoft-Windows-Eventlog ProviderNames : {Microsoft-Windows-WUSA, Micro ProviderLevel : ProviderKeywords : ProviderBufferSize : 64 ProviderMinimumNumberOfBuffers : 0 ProviderMaximumNumberOfBuffers : 64 ProviderLatency : 1000 ProviderControlGuid : Description ----------- These commands get an object that represents the classic System log on the local computer. The object includes useful information about the log, inclu ding its size, event log provider, file path, and whether it is enabled. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-winevent -listlog * -computername Server01| where {$_.recordcount } Description ----------- This command gets only event logs on the Server01 computer that contain eve nts. Many logs might be empty. The command uses the RecordCount property of the EventLogConfiguration obje ct that Get-WinEvent returns when you use the ListLog parameter. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$s = "Server01", "Server02", "Server03" C:\PS> foreach ($server in $s) {$server; get-winevent -listlog "Windows PowerShell" -computername $se rver} Description ----------- The commands in this example get objects that represent the Windows PowerSh ell event logs on the Server01, Server02, and Server03 computers. This comm and uses the Foreach keyword because the ComputerName parameter takes only one value. The first command saves the names of the computers in the $s variable. The second command uses a Foreach statement. For each of the computers in t he $s variable, it performs the command in the script block (within the bra ces). First, the command prints the name of the computer. Then, it runs a G et-WinEvent command to get an object that represents the Windows PowerShell log. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-winevent -listprovider * Description ----------- This command gets the event log providers on the local computer and the log s to which they write, if any. -------------------------- EXAMPLE 6 -------------------------- C:\PS>(get-winevent -listlog Application).providernames Description ----------- This command gets all of the providers that write to the Application log on the local computer. -------------------------- EXAMPLE 7 -------------------------- C:\PS>>get-winevent -listprovider *policy* Description ----------- This command gets the event log providers whose names include the word "pol icy." -------------------------- EXAMPLE 8 -------------------------- C:\PS>(get-winevent -listprovider microsoft-windows-grouppolicy).events | f ormat-table id, description -auto Description ----------- This command lists the event IDs that the Microsoft-Windows-GroupPolicy eve nt provider generates along with the event description. It uses the Events property of the object that Get-WinEvent returns when yo u use the ListProvider parameter, and it uses the ID and Description proper ties of the object in the Events property. -------------------------- EXAMPLE 9 -------------------------- C:\PS>$events = get-winevent -logname "Windows PowerShell" C:\PS> $events.count 195 C:\PS> $events | group-object id -noelement | sort-object count -desc Count Name ----- ---- 147 600 22 400 21 601 3 403 2 103 C:\PS> $events | group-object leveldisplayname -noelement Count Name ----- ---- 2 Warning 193 Information Description ----------- This example shows how to use the properties of the event objects that Get- WinEvent returns to learn about the events in an event log. The first command uses the Get-WinEvent cmdlet to get all of the events in the Windows PowerShell event log. Then, it saves them in the $events variab le. The log name is enclosed in quotation marks because it contains a space . The second command uses the Count property of object collections to find th e number of entries in the event log. The third command displays the incidence of each event in the log, with the most frequent events first. In this example, event ID 600 is the most freq uent event. The fourth command groups the items by the value of their LevelDisplayName property to show how many Error, Warning, and Information events are in the log. -------------------------- EXAMPLE 10 -------------------------- C:\PS>get-winevent -logname *disk*, Microsoft-Windows-Kernel-WHEA Description ----------- This command gets the error events whose names include "disk" from all of t he event logs on the computer and from the Microsoft-Windows-Kernel-WHEA ev ent log. -------------------------- EXAMPLE 11 -------------------------- C:\PS>get-winevent -path 'c:\ps-test\Windows PowerShell.evtx' Description ----------- This command gets events from a copy of the Windows PowerShell event log fi le in a test directory. The path is enclosed in quotation marks because the log name includes a space. -------------------------- EXAMPLE 12 -------------------------- C:\PS>get-winevent -path 'c:\tracing\tracelog.etl' -maxevents 100 -oldest C:\PS> get-winevent -path 'c:\tracing\tracelog.etl' -oldest | sort-object - property timecreated -desc | select-object -first 100 Description ----------- These commands get the first 100 events from an Event Tracing for Windows ( ETW) event trace log file. The first command gets the 100 oldest events in the log. It uses the Get-Wi nEvent cmdlet to get events from the Tracelog.etl file. It uses the MaxEven ts parameter to limit the retrieval to 100 events. Because the events are l isted in the order in which they are written to the log (oldest first), the Oldest parameter is required. The second command gets the 100 newest events in the log. It uses the Get-W inEvent cmdlet to get all the events from the Tracing.etl file. It passes the events to the Sort-Object cmdlet, which sorts them in descending order by the value of the TimeCreated property. Then, it sends the sorted events to the Select-Object cmdlet to select the newest 100 events. -------------------------- EXAMPLE 13 -------------------------- C:\PS>get-winevent -path "c:\tracing\tracelog.etl", "c:\Logs\Windows PowerS hell.evtx" -oldest | where {$_.id -eq "103"} Description ----------- This example shows how to get the events from an event trace log file (.etl ) and from a copy of the Windows PowerShell log file (.evtx) that was saved to a test directory. You can combine multiple file types in a single command. Because the files contain the same type of .NET Framework object (an EventLogRecord object), you can use the same properties to filter them. Note that the command requires the Oldest parameter because it is reading f rom an .etl file, but the Oldest parameter applies to both of the files. -------------------------- EXAMPLE 14 -------------------------- C:\PS># Use the Where-Object cmdlet C:\PS> $yesterday = (get-date) - (new-timespan -day 1) C:\PS> get-winevent -logname "Windows PowerShell" | where {$_.timecreated - ge $yesterday} # Uses FilterHashTable C:\PS> $yesterday = (get-date) - (new-timespan -day 1) C:\PS> get-winevent -FilterHashTable @{LogName='Windows PowerShell'; Level= 3; StartTime=$yesterday} # Use FilterXML C:\PS> get-winevent -FilterXML "<QueryList><Query><Select Path='Windows Pow erShell'>*[System[Level=3 and TimeCreated[timediff(@SystemTime) <= 86400000 ]]]</Select></Query></QueryList>" # Use FilterXPath C:\PS> get-winevent -LogName "Windows Powershell" -FilterXPath "*[System[Le vel=3 and TimeCreated[timediff(@SystemTime) <= 86400000]]]" Description ----------- This example shows different filtering methods for selecting events from an event log. All of these commands get events that occurred in the last 24 h ours from the Windows PowerShell event log. The filter methods are more efficient than using the Where-Object cmdlet be cause the filters are applied while the objects are being retrieved, rather than retrieving all the objects and then filtering them. Because dates are difficult to formulate in the XML and XPath formats, to c reate the XML content for the date, the Filter Current Log feature of Event Viewer is used. For more information about this feature, see Event Viewer Help. -------------------------- EXAMPLE 15 -------------------------- C:\PS>$date = (get-date).AddDays(-2) C:\PS> $events = get-winevent -FilterHashTable @{ logname = "Microsoft-Wind ows-Diagnostics-Performance/Operational"; StartTime = $date; ID = 100 } Description ----------- This example uses a filter hash table to get events from the performance lo g. The first command uses the Get-Date cmdlet and the AddDays method to get a date that is two days before the current date. It saves the date in the $da te variable. The second command uses the Get-WinEvent cmdlet with the FilterHashTable pa rameter. The keys in the hash table define a filter that selects events fro m the performance log that occurred within the last two days and that have event ID 100. The LogName key specifies the event log, the StartTime key specifies the da te, and the ID key specifies the event ID. -------------------------- EXAMPLE 16 -------------------------- C:\PS>$starttime = (get-date).adddays(-7) C:\PS> $ie-error = Get-WinEvent -FilterHashtable @{logname="application"; p rovidername="Application Error"; data="iexplore.exe"; starttime=$starttime} Description ----------- This example uses a filter hash table to find Internet Explorer application errors that occurred within the last week. The first command gets the date that is seven days before the current date and stores it in the $starttime variable. The second command uses the Get-WinEvent cmdlet with the FilterHashTable pa rameter. The keys in the hash table define a filter that selects events fro m the Application log that were written by the Application Error provider a nd include the phrase "iexplore.exe". The LogName key specifies the event log. The ProviderName key specifies the event provider, the StartTime key specifies the starting date of the event s, and the Data key specifies the text in the event message. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=138336 Get-EventLog Get-Counter about_EventLogs Get-WmiObject NAME Get-WmiObject SYNOPSIS Gets instances of Windows Management Instrumentation (WMI) classes or infor mation about the available classes. SYNTAX Get-WmiObject [-Authority <string>] [-Amended] [-AsJob] [-Authentication {D efault | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-Enab leAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Imperson ate | Delegate}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit int>] [<CommonParameters>] Get-WmiObject [[-Class] <string>] [-Authority <string>] [-List] [-Recurse] [-Amended] [-AsJob] [-Authentication {Default | None | Connect | Call | Pac ket | PacketIntegrity | PacketPrivacy | Unchanged}] [-ComputerName <string[ ]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {De fault | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit <int>] [<CommonParameters>] Get-WmiObject [-Authority <string>] [-Amended] [-AsJob] [-Authentication {D efault | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-Enab leAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Imperson ate | Delegate}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit int>] [<CommonParameters>] Get-WmiObject [-Class] <string> [[-Property] <string[]>] [-Authority <strin g>] [-DirectRead] [-Filter <string>] [-Amended] [-AsJob] [-Authentication { Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-ComputerName <string[]>] [-Credential <PSCredential>] [-Ena bleAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Imperso nate | Delegate}] [-Locale <string>] [-Namespace <string>] [-ThrottleLimit <int>] [<CommonParameters>] Get-WmiObject -Query <string> [-Authority <string>] [-DirectRead] [-Amended ] [-AsJob] [-Authentication {Default | None | Connect | Call | Packet | Pac ketIntegrity | PacketPrivacy | Unchanged}] [-ComputerName <string[]>] [-Cre dential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | A nonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespa ce <string>] [-ThrottleLimit <int>] [<CommonParameters>] DESCRIPTION The Get-WmiObject cmdlet gets instances of WMI classes or information about the available WMI classes. The ComputerName parameter can always be used t o specify a remote computer. If the List parameter is specified, the cmdle t gets information about the WMI classes that are available in a specified namespace. If the Query parameter is specified, the cmdlet runs a WMI query language (WQL) statement. The Get-WmiObject cmdlet does not use the Windows PowerShell remoting infra structure to perform remote operations. You can use the ComputerName parame ter of the Get-WmiObject cmdlet even if your computer does not meet the req uirements for Windows PowerShell remoting and even if your computer is not configured for remoting in Windows PowerShell. PARAMETERS -Amended [<SwitchParameter>] Gets or sets a value that indicates whether the objects that are return ed from WMI should contain amended information. Typically, amended info rmation is localizable information, such as object and property descrip tions, that is attached to the WMI object.. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -AsJob [<SwitchParameter>] Runs the command as a background job. Use this parameter to run command s that take a long time to finish. When you use the AsJob parameter, the command returns an object that re presents the background job and then displays the command prompt. You c an continue to work in the session while the job finishes. If Get-WmiOb ject is used against a remote computer, the job is created on the local computer, and the results from remote computers are automatically retu rned to the local computer. To manage the job, use the cmdlets that con tain the Job noun (the Job cmdlets). To get the job results, use the Re ceive-Job cmdlet. Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must star t Windows PowerShell by using the "Run as administrator" option in Wind ows Vista and later versions of Windows,. For more information, see abo ut_Remote_Requirements. For more information about Windows PowerShell background jobs, see abo ut_Jobs and about_Remote_Jobs. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationLevel> Specifies the authentication level to be used with the WMI connection. Valid values are: -1: Unchanged 0: Default 1: None (No authentication in performed.) 2: Connect (Authentication is performed only when the client establishe s a relationship with the application.) 3: Call (Authentication is performed only at the beginning of each call when the application receives the request.) 4: Packet (Authentication is performed on all the data that is received from the client.) 5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.) 6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.) Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authority <string> Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to ntlmdomain:<DomainName>, where <DomainName> id entifies a valid NTLM domain name. To use Kerberos, specify kerberos:<D omainName>\<ServerName>". You cannot include the authority setting when you connect to the local computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Class <string> Specifies the name of a WMI class. When this parameter is used, the cmd let retrieves instances of the WMI class. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name. This parameter can also be pi ped to the cmdlet. This parameter does not rely on Windows PowerShell remoting, which uses WS-Management ). You can use the ComputerName parameter of Get-WmiObje ct even if your computer is not configured to run WS-Management remote commands. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or User@Contoso.com. Or, enter a PSCredential object, su ch as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DirectRead [<SwitchParameter>] Specifies whether direct access to the WMI provider is requested for th e specified class without any regard to its base class or to its derive d classes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -EnableAllPrivileges [<SwitchParameter>] Enables all the privileges of the current user before the command makes the WMI call. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a Where clause to use as a filter. Uses the syntax of the WMI Query Language (WQL). Important: Do not include the Where keyword in the value of the paramet er. For example, the following commands return only the logical disks t hat where the DeviceID equals 'c:' and the services where the name equa ls 'WinRM', without using the Where keyword: get-WmiObject Win32_LogicalDisk -filter "DeviceID = 'c:' " get-wmiobject win32_service -filter "name='WinRM'" Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Impersonation <ImpersonationLevel> Specifies the impersonation level to use. Valid values are: 0: Default (reads the local registry for the default impersonation leve l , which is usually set to "3: Impersonate".) 1: Anonymous (Hides the credentials of the caller.) 2: Identify (Allows objects to query the credentials of the caller.) 3: Impersonate (Allows objects to use the credentials of the caller.) 4: Delegate (Allows objects to permit other objects to use the credenti als of the caller.) Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -List [<SwitchParameter>] Specifies whether to retrieve and display the names of the WMI classes in the WMI repository namespace that is specified in the Namespace para meter. The Default Namespace registry entry in the HKEY_LOCAL_MACHINE\ SOFTWARE\Microsoft\WBEM\Scripting registry key is not used by this cmdl et to determine the default namespace. If you specify the List paramete r but not the Namespace parameter, the root\CIMV2 namespace is used by default. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Locale <string> Specifies the preferred locale for WMI objects. Specify the value of th e Locale parameter as an array in the MS_<LCID> format in the preferred order . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Namespace <string> When used with the Class parameter, this parameter specifies the WMI re pository namespace where the referenced WMI class is located. When used with the List parameter, it specifies the namespace from which to gath er WMI class information. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Property <string[]> Specifies the WMI class property or set of properties to retrieve. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Query <string> Specifies a WMI Query Language (WQL) statement to run. Event queries ar e not supported by this parameter. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Recurse [<SwitchParameter>] Makes the command search the current namespace and all other namespaces for the class name that is specified in the Class parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Allows the user to specify a throttling value for the number of WMI ope rations that can be executed simultaneously. This parameter is used tog ether with the AsJob parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to Get-WmiObject. OUTPUTS PSObject or System.Management.Automation.RemotingJob When you use the AsJob parameter, the cmdlet returns a job object. Othe rwise, the object that Get-WmiObject returns depends on the value of th e Class parameter. NOTES To access WMI information on a remote computer, the cmdlet must run und er an account that is a member of the local administrators group on the remote computer. Alternatively, the default access control on the WMI namespace of the remote repository can be changed to give other account access rights. By default, only some of the properties of a WMI class are displayed. T he set of properties that will be displayed for each WMI class is speci fied in the Types.ps1xml configuration file. One of the examples includ ed in this Help topic demonstrates how to override this behavior by usi ng the Format-List cmdlet. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-wmiobject win32_process __GENUS : 2 __CLASS : Win32_Process __SUPERCLASS : CIM_Process __DYNASTY : CIM_ManagedSystemElement __RELPATH : Win32_Process.Handle="0" __PROPERTY_COUNT : 45 __DERIVATION : {CIM_Process, CIM_LogicalElement, CIM_ManagedS ystemElement} __SERVER : SYSTEM01 __NAMESPACE : root\cimv2 __PATH : \\SYSTEM01\root\cimv2:Win32_Process.Handle="0" Caption : System Idle Process CommandLine : CreationClassName : Win32_Process CreationDate : CSCreationClassName : Win32_ComputerSystem CSName : SYSTEM01 Description : System Idle Process ExecutablePath : ExecutionState : Handle : 0 HandleCount : 0 InstallDate : KernelModeTime : 6138394740432 MaximumWorkingSetSize : MinimumWorkingSetSize : Name : System Idle Process OSCreationClassName : Win32_OperatingSystem OSName : Microsoftr Windows VistaT Ultimate |C:\Windows |\Device\Harddisk0\Partition3 OtherOperationCount : 0 OtherTransferCount : 0 PageFaults : 0 PageFileUsage : 0 ParentProcessId : 0 PeakPageFileUsage : 0 PeakVirtualSize : 0 PeakWorkingSetSize : 0 Priority : 0 PrivatePageCount : 0 ProcessId : 0 QuotaNonPagedPoolUsage : 0 QuotaPagedPoolUsage : 0 QuotaPeakNonPagedPoolUsage : 0 QuotaPeakPagedPoolUsage : 0 ReadOperationCount : 0 ReadTransferCount : 0 SessionId : 0 Status : TerminationDate : ThreadCount : 2 UserModeTime : 0 VirtualSize : 0 WindowsVersion : 6.0.6001 WorkingSetSize : 24576 WriteOperationCount : 0 WriteTransferCount : 0 ProcessName : System Idle Process Handles : 0 VM : 0 WS : 24576 Path : ... Description ----------- This command displays information about all the processes that are running on a computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-wmiobject win32_service -computername 127.0.0.1 __GENUS : 2 __CLASS : Win32_Process __SUPERCLASS : CIM_Process __DYNASTY : CIM_ManagedSystemElement __RELPATH : Win32_Process.Handle="0" __PROPERTY_COUNT : 45 __DERIVATION : {CIM_Process, CIM_LogicalElement, CIM_ManagedS ystemElement} __SERVER : SYSTEM02 __NAMESPACE : root\cimv2 __PATH : \\SYSTEM02\root\cimv2:Win32_Process.Handle="0" Caption : System Idle Process CommandLine : CreationClassName : Win32_Process CreationDate : CSCreationClassName : Win32_ComputerSystem CSName : SYSTEM02 Description : System Idle Process ExecutablePath : ExecutionState : Handle : 0 HandleCount : 0 InstallDate : KernelModeTime : 6138394740432 MaximumWorkingSetSize : MinimumWorkingSetSize : Name : System Idle Process OSCreationClassName : Win32_OperatingSystem OSName : Microsoftr Windows VistaT Ultimate |C:\Windows |\Device\Harddisk0\Partition3 OtherOperationCount : 0 OtherTransferCount : 0 PageFaults : 0 PageFileUsage : 0 ParentProcessId : 0 PeakPageFileUsage : 0 PeakVirtualSize : 0 PeakWorkingSetSize : 0 Priority : 0 PrivatePageCount : 0 ProcessId : 0 QuotaNonPagedPoolUsage : 0 QuotaPagedPoolUsage : 0 QuotaPeakNonPagedPoolUsage : 0 QuotaPeakPagedPoolUsage : 0 ReadOperationCount : 0 ReadTransferCount : 0 SessionId : 0 Status : TerminationDate : ThreadCount : 2 UserModeTime : 0 VirtualSize : 0 WindowsVersion : 6.0.6001 WorkingSetSize : 24576 WriteOperationCount : 0 WriteTransferCount : 0 ProcessName : System Idle Process Handles : 0 VM : 0 WS : 24576 Path : ... Description ----------- This command displays information about the services on the remote computer . It displays the information by specifying the Internet Protocol (IP) addr ess 127.0.0.1. You can change this IP address to any other valid IP address on your network so that you can display information about the services on that remote computer. By default, the account you are running under must be a member of the local administrators group on the remote computer that you specify . -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-wmiobject -namespace "root/default" -list NameSpace: ROOT\default Name Methods Properties ---- ------- ---------- __NotifyStatus {} {StatusCode} __ExtendedStatus {} {Description, Oper ation, ParameterInfo, ProviderName...} __SecurityRelatedClass {} {} __Trustee {} {Domain, Name, SID , SidLength...} __NTLMUser9X {} {Authority, Flags, Mask, Name...} __ACE {} {AccessMask, AceFl ags, AceType, GuidInheritedObjectType...} __SecurityDescriptor {} {ControlFlags, DAC L, Group, Owner...} __PARAMETERS {} {} __SystemClass {} {} __ProviderRegistration {} {provider} __EventProviderRegistration {} {EventQueryList, p rovider} __ObjectProviderRegistration {} {InteractionType, provider, QuerySupportLevels, SupportsBat... __ClassProviderRegistration {} {CacheRefreshInter val, InteractionType, PerUserSchema, prov... __InstanceProviderRegistration {} {InteractionType, provider, QuerySupportLevels, SupportsBat... __MethodProviderRegistration {} {provider} __PropertyProviderRegistration {} {provider, Support sGet, SupportsPut} __EventConsumerProviderRegistration {} {ConsumerClassName s, provider} __thisNAMESPACE {} {SECURITY_DESCRIPT OR} __NAMESPACE {} {Name} __IndicationRelated {} {} __FilterToConsumerBinding {} {Consumer, Creator SID, DeliverSynchronously, DeliveryQoS...} __EventConsumer {} {CreatorSID, Machi neName, MaximumQueueSize} LogFileEventConsumer {} {CreatorSID, Filen ame, IsUnicode, MachineName...} ActiveScriptEventConsumer {} {CreatorSID, KillT imeout, MachineName, MaximumQueueSize...} NTEventLogEventConsumer {} {Category, Creator SID, EventID, EventType...} SMTPEventConsumer {} {BccLine, CcLine, CreatorSID, FromLine...} CommandLineEventConsumer {} {CommandLineTempla te, CreateNewConsole, CreateNewProcessGro... __AggregateEvent {} {NumberOfEvents, R epresentative} __TimerNextFiring {} {NextEvent64BitTim e, TimerId} __EventFilter {} {CreatorSID, Event Access, EventNamespace, Name...} __Event {} {SECURITY_DESCRIPT OR, TIME_CREATED} __NamespaceOperationEvent {} {SECURITY_DESCRIPT OR, TargetNamespace, TIME_CREATED} __NamespaceModificationEvent {} {PreviousNamespace , SECURITY_DESCRIPTOR, TargetNamespace, T... __NamespaceDeletionEvent {} {SECURITY_DESCRIPT OR, TargetNamespace, TIME_CREATED} __NamespaceCreationEvent {} {SECURITY_DESCRIPT OR, TargetNamespace, TIME_CREATED} __ClassOperationEvent {} {SECURITY_DESCRIPT OR, TargetClass, TIME_CREATED} __ClassDeletionEvent {} {SECURITY_DESCRIPT OR, TargetClass, TIME_CREATED} __ClassModificationEvent {} {PreviousClass, SE CURITY_DESCRIPTOR, TargetClass, TIME_CREA... __ClassCreationEvent {} {SECURITY_DESCRIPT OR, TargetClass, TIME_CREATED} __InstanceOperationEvent {} {SECURITY_DESCRIPT OR, TargetInstance, TIME_CREATED} __InstanceCreationEvent {} {SECURITY_DESCRIPT OR, TargetInstance, TIME_CREATED} ... Description ----------- This command displays the WMI classes in the root or default namespace of t he local computer. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-wmiobject -query "select * from win32_service where name='WinRM'" -computername server01, server02 ExitCode : 0 Name : WinRM ProcessId : 1708 StartMode : Auto State : Running Status : OK ExitCode : 0 Name : WinRM ProcessId : 948 StartMode : Auto State : Running Status : OK Description ----------- This command displays information about the WinRM service on the computers that are specified in the ComputerName parameter. -------------------------- EXAMPLE 5 -------------------------- C:\PS>(get-wmiobject win32_service -filter "name='WinRM'" -computername ser ver01).StopService() __GENUS : 2 __CLASS : __PARAMETERS __SUPERCLASS : __DYNASTY : __PARAMETERS __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : ReturnValue : 0 Another query using get-wmiobject -query "select * from win32_service where name='WinRM'" -computername server01, shows the service as stopped. ExitCode : 0 Name : WinRM ProcessId : 0 StartMode : Auto State : Stopped Status : OK Description ----------- This command stops the WinRM service on the Server01 remote computer. The c ommand uses the standard Get-WmiObject command and adds a call to the StopS ervice method of the Win32_Service WMI class. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-wmiobject win32_bios | format-list * Status : OK Name : Phoenix ROM BIOS PLUS Version 1.10 2.3.1 Caption : Phoenix ROM BIOS PLUS Version 1.10 2.3.1 SMBIOSPresent : True __GENUS : 2 __CLASS : Win32_BIOS __SUPERCLASS : CIM_BIOSElement __DYNASTY : CIM_ManagedSystemElement __RELPATH : Win32_BIOS.Name="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",SoftwareElementID="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",SoftwareElementState=3,T argetOperatingSystem=0,Version="DELL - 14" __PROPERTY_COUNT : 27 __DERIVATION : {CIM_BIOSElement, CIM_SoftwareElement, CIM_LogicalE lement, CIM_ManagedSystemElement} __SERVER : SERVER01 __NAMESPACE : root\cimv2 __PATH : \\SERVER01\root\cimv2:Win32_BIOS.Name="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",Software ElementID="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",SoftwareElementState=3,TargetOperatingSys tem=0,Version="DELL - 14" BiosCharacteristics : {7, 9, 10, 11...} BIOSVersion : {DELL - 14, Phoenix ROM BIOS PLUS Version 1.10 2. 3.1 , Phoenix ROM BIOS PLUS Version 1.10 2.3 .1 , Phoenix ROM BIOS PLUS Version 1.10 2.3.1 } BuildNumber : CodeSet : CurrentLanguage : en|US|iso8859-1 Description : Phoenix ROM BIOS PLUS Version 1.10 2.3.1 IdentificationCode : InstallableLanguages : 1 InstallDate : LanguageEdition : ListOfLanguages : {en|US|iso8859-1} Manufacturer : Dell Inc. OtherTargetOS : PrimaryBIOS : True ReleaseDate : 20070521000000.000000+000 SerialNumber : 8PWRVD1 SMBIOSBIOSVersion : 2.3.1 SMBIOSMajorVersion : 2 SMBIOSMinorVersion : 3 SoftwareElementID : Phoenix ROM BIOS PLUS Version 1.10 2.3.1 SoftwareElementState : 3 TargetOperatingSystem : 0 Version : DELL - 14 Scope : System.Management.ManagementScope Path : \\SERVER01\root\cimv2:Win32_BIOS.Name="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",Software ElementID="Phoenix ROM BIOS PLUS Version 1.10 2.3.1 ",SoftwareElementState=3,TargetOperatingSys tem=0,Version="DELL - 14" Options : System.Management.ObjectGetOptions ClassPath : \\SERVER01\root\cimv2:Win32_BIOS Properties : {BiosCharacteristics, BIOSVersion, BuildNumber, Cap tion...} SystemProperties : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...} Qualifiers : {dynamic, Locale, provider, UUID} Site : Container : Description ----------- This command displays BIOS information. It displays all the properties of t he WMI class, not just the properties that are specified in the Types.ps1xm l configuration file. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-wmiobject win32_service -credential FABRIKAM\administrator -compu ter fabrikam ExitCode : 0 Name : AeLookupSvc ProcessId : 0 StartMode : Manual State : Stopped Status : OK ExitCode : 1077 Name : ALG ProcessId : 0 StartMode : Manual State : Stopped Status : OK ExitCode : 1077 Name : AppIDSvc ProcessId : 0 StartMode : Manual State : Stopped Status : OK ExitCode : 0 Name : Appinfo ProcessId : 888 StartMode : Manual State : Running Status : OK ExitCode : 1077 Name : AppMgmt ProcessId : 0 StartMode : Manual State : Stopped Status : OK ... Description ----------- This command displays service information on a computer named Fabrikam. It specifies a user account name by using the Credential parameter, which caus es a dialog box to be displayed in which you enter the corresponding passwo rd. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113337 Invoke-WmiMethod Remove-WmiObject Set-WmiInstance Get-WSManInstance Invoke-WSManAction New-WSManInstance Remove-WSManInstance Get-WSManCredSSP NAME Get-WSManCredSSP SYNOPSIS Gets the Credential Security Service Provider-related configuration for the client. SYNTAX Get-WSManCredSSP [<CommonParameters>] DESCRIPTION The Get-WSManCredSPP cmdlet gets the Credential Security Service Provider-r elated configuration of the client and the server. The output indicates whe ther Credential Security Service Provider (CredSSP) authentication is enabl ed or disabled. It also displays configuration information for the AllowFre shCredentials policy of CredSSP. When you use CredSSP authentication, the u ser's credentials are passed to a remote computer to be authenticated. This type of authentication is designed for commands that create a remote sessi on from within another remote session. For example, you use this type of au thentication if you want to run a background job on a remote computer. The cmdlet performs the following actions: - Gets the WS-Management CredSSP setting on the client (<localhost|comp utername>\Client\Auth\CredSSP). - Gets the Windows CredSSP policy setting AllowFreshCredentials. - Gets the WS-Management CredSSP setting on the server (<localhost|comp utername>\Service\Auth\CredSSP). Caution: CredSSP authentication delegates the user's credentials from the l ocal computer to a remote computer. This practice increases the security ri sk of the remote operation. If the remote computer is compromised, when cre dentials are passed to it, the credentials can be used to control the netwo rk session. To disable CredSSP authentication, use the Disable-WSManCredSSP cmdlet. To enable CredSSP authentication, use the Enable-WSManCredSSP cmdlet. PARAMETERS <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-wsmancredssp Description ----------- This command displays CredSSP configuration information for both the client and server. The output identifies that this computer is or is not configured for CredSS P. If the computer is configured for CredSSP, this is the output: "The machine is configured to allow delegating fresh credentials to the fol lowing target(s): wsman/server02.accounting.fabrikam.com" If the computer is not configured for CredSSP, this is the output: "The machine is not configured to allow delegating fresh credentials." RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141443 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan Get-WSManInstance NAME Get-WSManInstance SYNOPSIS Displays management information for a resource instance specified by a Reso urce URI. SYNTAX Get-WSManInstance -SelectorSet <hashtable> [-ApplicationName <string>] [-Co mputerName <string>] [-Credential <PSCredential>] [-Fragment <string>] [-Po rt <int>] [-UseSSL] [-ResourceURI] <Uri> [-Authentication <Authentication>] [-Dialect <Uri>] [-OptionSet <hashtable>] [-SessionOption <hashtable>] [ ommonParameters>] Get-WSManInstance [-ApplicationName <string>] [-BasePropertiesOnly <switch> ] [-ComputerName <string>] [-Credential <PSCredential>] [-Enumerate] [-filt er <string>] [-Port <int>] [-References <switch>] [-ReturnType Shallow <switch>] [-UseSSL] [-ResourceURI] <Uri> [-Authentication <Authenti cation>] [-Dialect <Uri>] [-OptionSet <hashtable>] [-SessionOption <hashtab le>] [<CommonParameters>] Get-WSManInstance -ConnectionURI <Uri> -SelectorSet <hashtable> [-Fragment <string>] [-ResourceURI] <Uri> [-Authentication <Authentication>] [-Dialect <Uri>] [-OptionSet <hashtable>] [-SessionOption <hashtable>] [ eters>] Get-WSManInstance -ConnectionURI <Uri> [-BasePropertiesOnly <switch>] [-Enu merate] [-filter <string>] [-References <switch>] [-ReturnType <string>] [- Shallow <switch>] [-ResourceURI] <Uri> [-Authentication <Authentication>] [ -Dialect <Uri>] [-OptionSet <hashtable>] [-SessionOption <hashtable>] [ monParameters>] DESCRIPTION The Get-WSManInstance cmdlet retrieves an instance of a management resource that is specified by a resource URI. The information that is retrieved can be a complex XML information set (an object) or a simple value. This cmdl et is the equivalent to the standard WS-Management Get command. This cmdlet uses the WS-Management connection/transport layer to retrieve i nformation. PARAMETERS -ApplicationName <string> Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for t he remote endpoint is in the following format: <transport>://<server>:<port>/ For example: http://server01:8080/WSMAN Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is desi gned to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hos ts Web Services for Management (WS-Management) for efficiency. Required? false Position? named Default value wsman Accept pipeline input? false Accept wildcard characters? false -Authentication <Authentication> Specifies the authentication mechanism to be used at the server. Possib le values are: - Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - Default : Use the authentication method implemented by the WS-Managem ent protocol. This is the default. - Digest: Digest is a challenge-response scheme that uses a server-spec ified data string for the challenge. - Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates. - Negotiate: Negotiate is a challenge-response scheme that negotiates w ith the server or proxy to determine the scheme to use for authenticati on. For example, this parameter value allows negotiation to determine w hether the Kerberos protocol or NTLM is used. - CredSSP: Use Credential Security Service Provider (CredSSP) authentic ation, which allows the user to delegate credentials. This option is de signed for commands that run on one remote computer but collect data fr om or run additional commands on other remote computers. Caution: CredSSP delegates the user's credentials from the local comput er to a remote computer. This practice increases the security risk of t he remote operation. If the remote computer is compromised, when creden tials are passed to it, the credentials can be used to control the netw ork session. Required? false Position? named Default value Default Accept pipeline input? false Accept wildcard characters? false -BasePropertiesOnly <switch> Enumerates only the properties that are part of the base class that is specified by the ResourceURI parameter. This parameter has no effect if the Shallow parameter is specified. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name must be used. You can pipe a v alue for this parameter to the cmdlet. Required? false Position? named Default value localhost Accept pipeline input? false Accept wildcard characters? false -ConnectionURI <Uri> Specifies the connection endpoint. The format of this string is: <Transport>://<Server>:<Port>/ The following string is a properly formatted value for this parameter: http://Server01:8080/WSMAN The URI must be fully qualified. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or "User@Domain.com". Or, enter a PSCredential object, s uch as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Dialect <Uri> Specifies the dialect to use in the filter predicate. This can be any d ialect that is supported by the remote service. The following aliases c an be used for the dialect URI: - WQL: http://schemas.microsoft.com/wbem/wsman/1/WQL - Selector: http://schemas.microsoft.com/wbem/wsman/1/wsman/SelectorFil ter - Association: http://schemas.dmtf.org/wbem/wsman/1/cimbinding/associat ionFilter Required? false Position? named Default value http://schemas.microsoft.com/wbem/wsman/1/ WQL Accept pipeline input? false Accept wildcard characters? false -Enumerate [<SwitchParameter>] Returns all of the instances of a management resource. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -filter <string> Specifies the filter expression for the enumeration. If you use this pa rameter, you must also specify the Dialect parameter. The valid values of this parameter depend on the dialect that is specif ied in the Dialect parameter. For example, if the Dialect parameter is set to WQL, the Filter parameter must contain a string, and the string must contain a valid WQL query such as the following query: "Select * from Win32_Service where State = Running" If the Dialect parameter is set to Association, the Filter parameter mu st contain a string, and the string must contain a valid filter, such a s the following filter: -filter:Object=EPR[;AssociationClassName=AssocClassName][;ResultClassNa me=ClassName][;Role=RefPropertyName][;ResultRole=RefPropertyName]} Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Fragment <string> Specifies a section inside the instance that is to be updated or retrie ved for the specified operation. For example, to get the status of a sp ooler service, specify "-Fragment Status". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -OptionSet <hashtable> Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shel ls because they are service specific. Any number of options can be spec ified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: -OptionSet @{a=1;b=2;c=3} Required? false Position? named Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Port <int> Specifies the port to use when the client connects to the WinRM service . When the transport is HTTP, the default port is 80. When the transpor t is HTTPS, the default port is 443. When you use HTTPS as the transpor t, the value of the ComputerName parameter must match the server's cert ificate common name (CN). However, if the SkipCNCheck parameter is spec ified as part of the SessionOption parameter, then the certificate comm on name of the server does not have to match the host name of the serve r. The SkipCNCheck parameter should be used only for trusted computers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -References <switch> Indicates that association instances (not associated instances) should be retrieved. You can use this parameter only when the Dialect paramete r is set to a value of "Association". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ResourceURI <Uri> Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, suc h as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Log icalDisk http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSenso r Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -ReturnType <string> Specifies the type of data to be returned. The valid values are: Object (the default) EPR ObjectAndEPR If Object is specified or if this parameter is not used, only objects a re returned. If EPR (endpoint reference) is specified, only the endpoin t references of the objects are returned. Endpoint references contain i nformation about the resource URI and the selectors for the instance. I f ObjectAndEPR is specified, both the object and its associated endpoin t references are returned. Required? false Position? named Default value Object Accept pipeline input? false Accept wildcard characters? false -SelectorSet <hashtable> Specifies a set of value pairs that are used to select particular manag ement resource instances. The SelectorSet parameter is used when more t han one instance of the resource exists. The value of the SelectorSet p arameter must be a hash table. The following example shows how to enter a value for this parameter: -SelectorSet @{Name="WinRM";ID="yyy"} Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SessionOption <hashtable> Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOpt ion cmdlet. For more information about the options that are available, see New-WSManSessionOption. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Shallow <switch> Causes only instances of the base class that is specified in the resour ce URI to be returned. If this switch is not specified, instances of th e base class that is specified in the URI and in all its derived classe s is returned. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Specifies that the Secure Sockets Layer (SSL) protocol should be used t o establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is tran smitted over the network. The UseSSL parameter lets you specify the add itional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this paramete r, the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This command does not accept any input. OUTPUTS System.Xml.XmlElement The Get-WSManInstance cmdlet generates an XMLElement object. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-wsmaninstance wmicimv2/win32_service -selectorset @{name="winrm"} -computername server01 xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/roo t/cimv2/Win32_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common type : p:Win32_Service_Type lang : en-US AcceptPause : false AcceptStop : true Caption : Windows Remote Management (WS-Management) CheckPoint : 0 CreationClassName : Win32_Service Description : Windows Remote Management (WinRM) service impleme nts the WS-Management protocol for remote management. WS-Management is a standard web servi ces protocol used for remote software and hardware management. The WinRM service listens on the network for WS-Management requests and processes them. The WinRM Service needs to be configured with a listener using the winrm.cmd command line tool or through Group Poli cy in order for it to listen over the network. The WinRM service provides access to WMI data and enables event collection. Event collection and subscription to events require tha t the service is running. WinRM messages use HTTP and HTTPS as transports. The WinRM servi ce does not depend on IIS but is preconfigured to share a port with IIS on the sam e machine. The WinRM service reserves the /wsman URL prefix. To prevent conflicts with IIS, administrators should ensure that any websites hosted on IIS do not use the /wsman URL prefix. DesktopInteract : false DisplayName : Windows Remote Management (WS-Management) ErrorControl : Normal ExitCode : 0 InstallDate : InstallDate Name : winrm PathName : C:\Windows\System32\svchost.exe -k NetworkService ProcessId : 948 ServiceSpecificExitCode : 0 ServiceType : Share Process Started : true StartMode : Auto StartName : NT AUTHORITY\NetworkService State : Running Status : OK SystemCreationClassName : Win32_ComputerSystem SystemName : SERVER01 TagId : 0 WaitHint : 0 Description ----------- This command returns all of the information that Windows Management Instrum entation (WMI) exposes about the WinRM service on the remote server01 compu ter. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-wsmaninstance wmicimv2/win32_service -selectorset @{name="spooler "} -fragment status -computername server01 XmlFragment=OK Description ----------- This command returns only the status of the Spooler service on the remote s erver01 computer. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-wsmaninstance -enumerate wmicimv2/win32_process OSName : Microsoft Windows Vista Ultimate |C:\Windows|\ Device\Harddisk0\Partition3 OtherOperationCount : 11441 OtherTransferCount : 428570 PageFaults : 27346 PageFileUsage : 16428 ParentProcessId : 604 PeakPageFileUsage : 17588 PeakVirtualSize : 93876224 PeakWorkingSetSize : 12472 Priority : 8 PrivatePageCount : 16822272 ProcessId : 1160 QuotaNonPagedPoolUsage : 14 QuotaPagedPoolUsage : 126 QuotaPeakNonPagedPoolUsage : 16 QuotaPeakPagedPoolUsage : 159 ReadOperationCount : 29568 ReadTransferCount : 1660581404 SessionId : 0 Status : Status TerminationDate : TerminationDate ThreadCount : 23 UserModeTime : 763156892 VirtualSize : 80846848 WindowsVersion : 6.0.6001 WorkingSetSize : 11624448 WriteOperationCount : 1913 WriteTransferCount : 6825768 xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/ root/cimv2/Win32_Process cim : http://schemas.dmtf.org/wbem/wscim/1/common type : p:Win32_Process_Type lang : en-US Caption : svchost.exe CommandLine : C:\Windows\System32\svchost.exe -k LocalSystem NetworkRestricted CreationClassName : Win32_Process CreationDate : CreationDate CSCreationClassName : Win32_ComputerSystem CSName : COMPUTER01 Description : svchost.exe ExecutablePath : C:\Windows\System32\svchost.exe ExecutionState : ExecutionState Handle : 1192 HandleCount : 832 ... Description ----------- This command returns all the instances of the WMI Win32_Process class on th e local computer. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-wsmaninstance -enumerate wmicimv2/win32_service -returntype epr xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/roo t/cimv2/Win32_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common type : p:Win32_Service_Type lang : en-US AcceptPause : false AcceptStop : false Caption : Visual Studio 2008 Remote Debugger CheckPoint : 0 CreationClassName : Win32_Service Description : Allows members of the Administrators group to rem otely debug server applications using Visual Studio 2008. Use the Visual Studio 2008 Remote D ebugging Configuration Wizard to enable this service. DesktopInteract : false DisplayName : Visual Studio 2008 Remote Debugger ErrorControl : Ignore ExitCode : 1077 InstallDate : InstallDate Name : msvsmon90 PathName : "C:\Program Files\Microsoft Visual Studio 9.0\Com mon7\IDE\Remote Debugger\x86\msvsmon.exe" /s ervice msvsmon90 ProcessId : 0 ServiceSpecificExitCode : 0 ServiceType : Own Process Started : false StartMode : Disabled StartName : LocalSystem State : Stopped Status : OK SystemCreationClassName : Win32_ComputerSystem SystemName : COMPUTER01 TagId : 0 WaitHint : 0 ... Description ----------- This command returns endpoint references that correspond to all the service s on the local computer. -------------------------- EXAMPLE 5 -------------------------- C:\PS>Get-WSManInstance -Enumerate wmicimv2/* -filter "select * from win32_ service where StartMode = 'Auto' and State = 'Stopped'" -computername serve r01 xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/roo t/cimv2/Win32_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common type : p:Win32_Service_Type lang : en-US AcceptPause : false AcceptStop : false Caption : Windows Media Center Service Launcher CheckPoint : 0 CreationClassName : Win32_Service Description : Starts Windows Media Center Scheduler and Windows Media Center Receiver services at startup if TV is enabled within Windows Media Center. DesktopInteract : false DisplayName : Windows Media Center Service Launcher ErrorControl : Ignore ExitCode : 0 InstallDate : InstallDate Name : ehstart PathName : C:\Windows\system32\svchost.exe -k LocalServiceNo Network ProcessId : 0 ServiceSpecificExitCode : 0 ServiceType : Share Process Started : false StartMode : Auto StartName : NT AUTHORITY\LocalService State : Stopped Status : OK SystemCreationClassName : Win32_ComputerSystem SystemName : Server01 TagId : 0 WaitHint : 0 ... Description ----------- This command lists all of the services that meet the following criteria on the remote server01 computer: - The startup type of the service is "Automatic". - The service is stopped. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-wsmaninstance winrm/config/listener -selectorset @{Address="*";Tr ansport="http"} cfg : http://schemas.microsoft.com/wbem/wsman/1/config/li stener xsi : http://www.w3.org/2001/XMLSchema-instance lang : en-US Address : * Transport : HTTP Port : 80 Hostname : Enabled : true URLPrefix : wsman CertificateThumbprint : ListeningOn : {100.0.0.1, 123.123.123.123, ::1, 2001:4898:0:fff:0 :5efe:123.123.123.123...} Description ----------- This command lists the WS-Management listener configuration on the local co mputer for the listener that matches the criteria in the selector set. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-wsmaninstance winrm/config/listener -selectorset @{Address="*";Tr ansport="http"} -computername server01 cfg : http://schemas.microsoft.com/wbem/wsman/1/config/li stener xsi : http://www.w3.org/2001/XMLSchema-instance lang : en-US Address : * Transport : HTTP Port : 80 Hostname : Enabled : true URLPrefix : wsman CertificateThumbprint : ListeningOn : {100.0.0.1, 123.123.123.124, ::1, 2001:4898:0:fff:0 :5efe:123.123.123.124...} Description ----------- This command lists the WS-Management listener configuration on the remote s erver01 computer for the listener that matches the criteria in the selector set. -------------------------- EXAMPLE 8 -------------------------- C:\PS>Get-WSManInstance -Enumerate -Dialect association -filter "{Object=wi n32_service?name=winrm}" -res wmicimv2/* xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/r oot/cimv2/Win32_ComputerSystem cim : http://schemas.dmtf.org/wbem/wscim/1/common type : p:Win32_ComputerSystem_Type lang : en-US AdminPasswordStatus : 1 AutomaticManagedPagefile : true AutomaticResetBootOption : true AutomaticResetCapability : true BootOptionOnLimit : BootOptionOnLimit BootOptionOnWatchDog : BootOptionOnWatchDog BootROMSupported : true BootupState : Normal boot Caption : SERVER01 ChassisBootupState : 3 CreationClassName : Win32_ComputerSystem CurrentTimeZone : -480 DaylightInEffect : false Description : AT/AT COMPATIBLE DNSHostName : server01 Domain : site01.corp.fabrikam.com DomainRole : 1 EnableDaylightSavingsTime : true FrontPanelResetStatus : 2 InfraredSupported : false InstallDate : InstallDate KeyboardPasswordStatus : 2 LastLoadInfo : LastLoadInfo Manufacturer : Dell Inc. Model : OptiPlex 745 Name : SERVER01 NameFormat : NameFormat NetworkServerModeEnabled : true NumberOfLogicalProcessors : 2 NumberOfProcessors : 1 OEMStringArray : www.dell.com PartOfDomain : true PauseAfterReset : -1 PCSystemType : 5 PowerManagementSupported : PowerManagementSupported PowerOnPasswordStatus : 1 PowerState : 0 PowerSupplyState : 3 PrimaryOwnerContact : PrimaryOwnerContact PrimaryOwnerName : testuser01 ResetCapability : 1 ResetCount : -1 ResetLimit : -1 Roles : {LM_Workstation, LM_Server, SQLServer, NT} Status : OK SystemStartupDelay : SystemStartupDelay SystemStartupSetting : SystemStartupSetting SystemType : X86-based PC ThermalState : 3 TotalPhysicalMemory : 3217760256 UserName : FABRIKAM\testuser01 WakeUpType : 6 Workgroup : Workgroup xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/roo t/cimv2/Win32_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common type : p:Win32_Service_Type lang : en-US AcceptPause : false AcceptStop : false Caption : Remote Procedure Call (RPC) CheckPoint : 0 CreationClassName : Win32_Service Description : Serves as the endpoint mapper and COM Service Con trol Manager. If this service is stopped or disabled, programs using COM or Remote Procedu re Call (RPC) services will not function properly. DesktopInteract : false DisplayName : Remote Procedure Call (RPC) ErrorControl : Normal ExitCode : 0 InstallDate : InstallDate Name : RpcSs PathName : C:\Windows\system32\svchost.exe -k rpcss ProcessId : 1100 ServiceSpecificExitCode : 0 ServiceType : Share Process Started : true StartMode : Auto StartName : NT AUTHORITY\NetworkService State : Running Status : OK SystemCreationClassName : Win32_ComputerSystem SystemName : SERVER01 TagId : 0 WaitHint : 0 xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/roo t/cimv2/Win32_SystemDriver cim : http://schemas.dmtf.org/wbem/wscim/1/common type : p:Win32_SystemDriver_Type lang : en-US AcceptPause : false AcceptStop : true Caption : HTTP CreationClassName : Win32_SystemDriver Description : HTTP DesktopInteract : false DisplayName : HTTP ErrorControl : Normal ExitCode : 0 InstallDate : InstallDate Name : HTTP PathName : C:\Windows\system32\drivers\HTTP.sys ServiceSpecificExitCode : 0 ServiceType : Kernel Driver Started : true StartMode : Manual StartName : State : Running Status : OK SystemCreationClassName : Win32_ComputerSystem SystemName : SERVER01 TagId : 0 Description ----------- This command gets the associated instances that are related to the specifie d instance (winrm). Important: You must enclose the filter in quotation marks, as shown in the example. -------------------------- EXAMPLE 9 -------------------------- C:\PS>Get-WSManInstance -Enumerate -Dialect association -References -filter "{Object=win32_service?name=winrm}" -res wmicimv2/* Description ----------- This command gets association instances that are related to the specified i nstance (winrm). Because the Dialect parameter is set to "association" and the Reference parameter is used, this command returns association instance s, not associated instances. Important: You must enclose the filter in quotation marks, as shown in the example. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141444 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Invoke-WSManAction New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan Group-Object NAME Group-Object SYNOPSIS Groups objects that contain the same value for specified properties. SYNTAX Group-Object [-AsHashTable] [-AsString] [[-Property] <Object[]>] [-CaseSens itive] [-Culture <string>] [-InputObject <psobject>] [-NoElement] [<CommonP arameters>] DESCRIPTION The Group-Object cmdlet displays objects in groups based on the value of a specified property. Group-Object returns a table with one row for each prop erty value and a column that displays the number of items with that value. If you specify more than one property, Group-Object first groups them by th e values of the first property, and then, within each property group, it gr oups by the value of the next property. PARAMETERS -AsHashTable [<SwitchParameter>] Returns the group as a hash table. The keys of the hash table are the property values by which the objects are grouped. The values of the has h table are the objects that have that property value. By itself, the AsHashTable parameter returns each hash table in which e ach key is an instance of the grouped object. When used with the AsStr ing parameter, the keys in the hash table are strings. Required? false Position? named Default value GroupInfo object Accept pipeline input? false Accept wildcard characters? false -AsString [<SwitchParameter>] Converts the hash table keys to strings. By default, the hash table key s are instances of the grouped object. This parameter is valid only whe n used with the AsHashTable parameter. Required? false Position? named Default value GroupInfo objects Accept pipeline input? false Accept wildcard characters? false -CaseSensitive [<SwitchParameter>] Makes the grouping case-sensitive. Without this parameter, the property values of objects in a group might have different cases. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Culture <string> Specifies the culture to use when comparing strings. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to group. Enter a variable that contains the obje cts, or type a command or expression that gets the objects. When you use the InputObject parameter to submit a collection of object s to Group-Object, Group-Object receives one object that represents the collection. As a result, it creates a single group with that object as its member. To group the objects in a collection, pipe the objects to Group-Object. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -NoElement [<SwitchParameter>] Omits the members of a group from the results. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Property <Object[]> Specifies the properties for grouping. The objects are arranged into gr oups based on the value of the specified property. The value of the Property parameter can be a new calculated property. T o create a calculated, property, create a hash table with an Expression key that specifies a string or script block value. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Group-Object OUTPUTS Microsoft.PowerShell.Commands.GroupInfo or System.Collections.Hashtable When you use the AsHashTable parameter, Group-Object returns a hash tab le. Otherwise, it returns a GroupInfo object. NOTES You can also use the GroupBy parameter of the formatting cmdlets (such as Format-Table [m2] and Format-List [m2]) to group objects. Unlike Gro up-Object, which creates a single table with a row for each property va lue, the GroupBy parameters create a table for each property value with a row for each item that has the property value. Group-Object does not require that the objects being grouped be of the same Microsoft .NET Framework type. When grouping objects of different .NET Framework types, Group-Object uses the following rules: -- Same Property Names and Types: If the objects have a property with t he specified name, and the property values have the same .NET Framework type, the property values are grouped by using the same rules that wou ld be used for objects of the same type. -- Same Property Names, Different Types: If the objects have a property with the specified name, but the property values have a different .NET Framework type in different objects, Group-Object uses the .NET Framew ork type of the first occurrence of the property as the .NET Framework type for that property group. When an object has a property with a diff erent type, the property value is converted to the type for that group. If the type conversion fails, the object is not included in the group. -- Missing Properties: Objects that do not have a specified property ar e considered ungroupable. Ungroupable objects appear in the final Group Info object output in a group named AutomationNull.Value. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-childitem *.doc | group-object -property length Description ----------- This command gets the files in the current location that have a .doc extens ion and groups them by size. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-childitem | sort-object -property extension | group-object -prope rty extension Description ----------- This command gets the files in the current location, sorts them by file nam e extension, and then groups them by file name extension. Note that the fil es are sorted before they are grouped. -------------------------- EXAMPLE 3 -------------------------- C:\PS>1..35 | group-object -property {$_ % 2},{$_ % 3} Description ----------- This example shows how to use script blocks as the value of the Property pa rameter. This command displays the integers from 1 to 35, grouped by the remainder l eft when they are divided by 2 or 3. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$events = get-eventlog -logname system -newest 1000 C:\PS> $events | group-object -property eventID Count Name Group ----- ---- ----- 44 Information {System.Diagnostics.EventLogEntry, 5 Error {System.Diagnostics.EventLogEntry, 1 Warning {System.Diagnostics.EventLogEntry} Description ----------- These commands display the 1,000 most recent entries in the System event lo g, grouped by Event ID. The first command uses the Get-EventLog cmdlet to retrieve the events and t he assignment operator (=) to save them in the $events variable. The second command uses a pipeline operator (|) to send the events in the $ events variable to the Group-Object cmdlet. The command uses the Property p arameter to specify that the events should be grouped according to the valu e of their EventID property. In the output, the Count column represents the number of entries in each gr oup, the Name column represents the EventID values that define a group, and the Group column represents the objects in each group. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-process | group-object -property priorityclass Count Name Group ----- ---- ----- 55 Normal {System.Diagnostics.Process (AdtAgent), System.Di agnostics.Process (alg), System.Dia... 1 {System.Diagnostics.Process (Idle)} 3 High {System.Diagnostics.Process (Newproc), System.Dia gnostics.Process (winlogon), System.D... 2 BelowNormal {System.Diagnostics.Process (winperf), C:\PS>get-process | group-object -property company -noelement Count Name ----- ---- 55 Normal 1 3 High 2 BelowNormal Description ----------- This example demonstrates the effect of the NoElement parameter. These comm ands group the processes on the computer by priority class. The first command uses the Get-Process cmdlet to get the processes on the c omputer. It uses a pipeline operator (|) to send the results to Group-Objec t, which groups the objects by the value of the PriorityClass property of t he process. The second command is identical to the first, except that it uses the NoEle ment parameter to eliminate the members of the group from the output. The r esult is a table with only the count and property value name. The results are shown in the following sample output. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-eventlog -logname system -newest 1000 | group-object -property {$ _.TimeWritten - $_.TimeGenerated} Description ----------- This command demonstrates how to provide the value of the Property paramete r as a script block. This command displays the most recent 1,000 entries from the system event l og, grouped according to the time between when they were generated and when they were written to the log. The command uses the Get-EventLog cmdlet to get the event log entries. It u ses a pipeline operator (|) to send the entries to the Group-Object cmdlet. The value of the Property parameter is specified as a script block (an exp ression in braces). The result of evaluating the script block is the time b etween when the log entry was generated and when it was written to the log. That value is used to group the 1,000 most recent events. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-childitem | group-object extension -noelement Count Name ----- ---- 21 82 .txt 9 .cmd 5 .log 12 .xml 5 .htm 36 .ps1 1 .psc1 3 .exe 6 .csv 1 .psd1 2 .bat Description ----------- This command groups the items in the current directory by file name extensi on. It uses the NoElement parameter to omit the members of the group. The results are shown in the following sample output. -------------------------- EXAMPLE 8 -------------------------- C:\PS>"a", "b", "c", "c", "d" | get-unique a b c d C:\PS> "a", "b", "c", "c", "d" | group-object -noelement | where {$_.Count -gt 1} Count Name ----- ---- 2 c C:\PS> get-process | group-object -property Name -noelement | where {$_.cou nt -gt 1} Count Name ----- ---- 2 csrss 5 svchost 2 winlogon 2 wmiprvse Description ----------- This example shows how to find the unique and non-unique (repeated) propert y values in a collection. The first command gets the unique elements of an array by piping the array to the Get-Unique cmdlet. The second command gets the non-unique elements of an array. It pipes the a rray to the Group-Object cmdlet, which groups the objects by value. The res ulting groups are piped to the Where-Object cmdlet, which selects objects w ith groups with more than one member. The third command shows a practical use for this technique. It uses the sam e method to find processes on the computer that have the same process name. The results are shown in the following sample output. -------------------------- EXAMPLE 9 -------------------------- C:\PS>$a = get-command get-*, set-* -type cmdlet | group-object -property v erb -ashashtable -asstring C:\PS> $a Name Value ---- ----- Get {Get-PSCallStack, Get-PSBreakpoint, Get-PSDrive, Get-PSSession...} Set {Set-Service, Set-StrictMode, Set-PSDebug, Set-PSSessionConfigurati on...} C:\PS> $a.get CommandType Name Definition ----------- ---- ---------- Cmdlet Get-PSCallStack Get-PSCallStack [-Verbose] [-Debug] [- ErrorAction <ActionPrefer... Cmdlet Get-PSBreakpoint Get-PSBreakpoint [[-Id] <Int32[]>] [-V erbose] [-Debug] [-ErrorA... Cmdlet Get-PSDrive Get-PSDrive [[-Name] <String[]>] [-Sco pe <String>] [-PSProvider... ... Description ----------- This example uses the AsHashTable and AsString parameters to return the gro ups in a hash table, that is, as a collection of key-value pairs. In the resulting hash table, each property value is a key, and the group el ements are the values. Because each key is a property of the hash table obj ect, you can use dot notation to display the values. The first command gets the Get and Set cmdlets in the session, groups them by verb, returns the groups as a hash table, and saves the hash table in th e $a variable. The second command displays the hash table in $a. There are two key-value p airs, one for the Get cmdlets and one for the Set cmdlets. The third command uses dot notation to display the values of the Get key in $a. The values are CmdletInfo object. The AsString parameter does not conv ert the objects in the groups to strings. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113338 help NAME Get-Help SYNOPSIS Displays information about Windows PowerShell commands and concepts. SYNTAX Get-Help [-Full] [[-Name] <string>] [-Category <string[]>] [-Component <str ing[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role <stri ng[]>] [<CommonParameters>] Get-Help [-Detailed] [[-Name] <string>] [-Category <string[]>] [-Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role string[]>] [<CommonParameters>] Get-Help [-Examples] [[-Name] <string>] [-Category <string[]>] [-Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string>] [-Role string[]>] [<CommonParameters>] Get-Help [-Parameter <string>] [[-Name] <string>] [-Category <string[]>] [- Component <string[]>] [-Functionality <string[]>] [-Online] [-Path <string> ] [-Role <string[]>] [<CommonParameters>] DESCRIPTION The Get-Help cmdlet displays information about Windows PowerShell concepts and commands, including cmdlets, providers, functions and scripts. To get a list of all cmdlet help topic titles, type "get-help *". If you type "Get-Help" followed by the exact name of a help topic, or by a word unique to a help topic, Get-Help displays the topic contents. If you e nter a word or word pattern that appears in several help topic titles, Get- Help displays a list of the matching titles. If you enter a word that does not appear in any help topic titles, Get-Help displays a list of topics tha t include that word in their contents. In addition to "get-help", you can also type "help" or "man", which display s one screen of text at a time, or "<cmdlet-name> -?", which is identical t o Get-Help but works only for cmdlets. You can display the entire help file or selected parts of the file, such as the syntax, parameters, or examples. You can also use the Online parameter to display an online version of a help file in your Internet browser. Thes e parameters have no effect on conceptual help topics. Conceptual help topics in Windows PowerShell begin with "about_", such as " about_Comparison_Operators". To see all "about_" topics, type "get-help abo ut_*". To see a particular topic, type "get-help about_<topic-name>", such as "get-help about_Comparison_Operators". PARAMETERS -Category <string[]> Displays help for items in the specified category. Valid values are Ali as, Cmdlet, Provider, and HelpFile. Conceptual topics are in the HelpFi le category. Category is a property of the MamlCommandHelpInfo object that Get-Help returns. This parameter has no effect on displays of conceptual ("about _") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Component <string[]> Displays a list of tools with the specified component value, such as "E xchange." Enter a component name. Wildcards are permitted. Component is a property of the MamlCommandHelpInfo object that Get-Help returns. This parameter has no effect on displays of conceptual ("Abou t_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Detailed [<SwitchParameter>] Adds parameter descriptions and examples to the basic help display. This parameter has no effect on displays of conceptual ("About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Examples [<SwitchParameter>] Displays only the name, synopsis, and examples. To display only the exa mples, type "(get-help <cmdlet-name>).examples". This parameter has no effect on displays of conceptual ("About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Full [<SwitchParameter>] Displays the entire help file for a cmdlet, including parameter descrip tions and attributes, examples, input and output object types, and addi tional notes. This parameter has no effect on displays of conceptual ("About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Functionality <string[]> Displays help for items with the specified functionality. Enter the fun ctionality. Wildcards are permitted. Functionality is a property of the MamlCommandHelpInfo object that Get- Help returns. This parameter has no effect on displays of conceptual (" About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Requests help about the specified tool or conceptual topic. Enter a cmd let, provider, script, or function name, such as Get-Member, a conceptu al topic name, such as "about_Objects", or an alias, such as "ls". Wild cards are permitted in cmdlet and provider names, but you cannot use wi ldcards to find the names of function help and script help topics. To get help for a script that is not located in a path that is listed i n the Path environment variable, type the path and file name of the scr ipt . If you enter the exact name of a help topic, Get-Help displays the topi c contents. If you enter a word or word pattern that appears in several help topic titles, Get-Help displays a list of the matching titles. If you enter a word that does not match any help topic titles, Get-Help d isplays a list of topics that include that word in their contents. The names of conceptual topics, such as about_Objects, must be entered in English, even in non-English versions of Windows PowerShell. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Online [<SwitchParameter>] Displays the online version of a help topic in the default Internet bro wser. This parameter is valid only for cmdlet, function, and script hel p topics. Get-Help uses the Internet address (Uniform Resource Identifier [URI]) that appears in the first item of the Related Links section of a cmdlet , function, or script help topic. This parameter works only when the he lp topic includes a URI that begins with "Http" or "Https" and an Inter net browser is installed on the system. For information about supporting this feature in help topics that you w rite, see about_Comment_Based_Help, and see "How to Write Cmdlet Help" in the MSDN (Microsoft Developer Network) library at http://go.microsof t.com/fwlink/?LinkID=123415. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Parameter <string> Displays only the detailed descriptions of the specified parameters. Wi ldcards are permitted. This parameter has no effect on displays of conceptual ("About_") help. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Gets help that explains how the cmdlet works in the specified provider path. Enter a Windows PowerShell provider path. This parameter gets a customized version of a cmdlet help topic that ex plains how the cmdlet works in the specified Windows PowerShell provide r path. This parameter is effective only for help about a provider cmdl et and only when the provider includes a custom version of the provider cmdlet help topic. To see the custom cmdlet help for a provider path, go to the provider p ath location and enter a Get-Help command or, from any path location, u se the Path parameter of Get-Help to specify the provider path. For mor e information, see about_Providers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Role <string[]> Displays help customized for the specified user role. Enter a role. Wil dcards are permitted. Enter the role that the user plays in an organization. Some cmdlets dis play different text in their help files based on the value of this para meter. This parameter has no effect on help for the core cmdlets. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS System.String or MamlCommandHelpInfo If you request a conceptual topic, Get-Help returns it as a string. If you specify the name of a cmdlet,, function, or script, it returns a Ma mlCommandHelpInfo object. Otherwise, Get-Help returns one of the format ted views that are specified in the Help.Format.ps1xml file in the $psh ome directory. NOTES Without parameters, "Get-Help" displays information about the Windows P owerShell help system. The full view of help (-full) includes a table of information about the parameters. The table includes the following fields: -- Required: Indicates whether the parameter is required (true) or opt ional (false). -- Position: Indicates whether the parameter is named or positional (n umbered). Positional parameters must appear in a specified place in the command. -- "Named" indicates that the parameter name is required, but that the parameter can appear anywhere in the command. -- <Number> indicates that the parameter name is optional, but when the name is omitted, the parameter must be in the place specified by the n umber. For example, "2" indicates that when the parameter name is omitt ed, the parameter must be the second (2) or only unnamed parameter in t he command. When the parameter name is used, the parameter can appear a nywhere in the command. -- Default value: The parameter value that Windows PowerShell uses if y ou do not include the parameter in the command. -- Accepts pipeline input: Indicates whether you can (true) or cannot ( false) send objects to the parameter through a pipeline. "By Property N ame" means that the pipelined object must have a property with the same name as the parameter name. -- Accepts wildcard characters: Indicates whether the value of a parame ter can include wildcard characters, such as * and ?. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-help Description ----------- This command displays help about the Windows PowerShell help system. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-help * Description ----------- This command displays a list of all help files in the Windows PowerShell he lp system. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-help get-alias C:\PS>help get-alias C:\PS>get-alias -? Description ----------- These commands display basic information about the get-alias cmdlet. The "G et-Help" and "-?" commands display the information on a single page. The "H elp" command displays the information one page at a time. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-help about_* Description ----------- This command displays a list of the conceptual topics included in Windows P owerShell help. All of these topics begin with the characters "about_". To display a particular help file, type "get-help <topic-name>, for example, " get-help about_signing". -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-help ls -detailed Description ----------- This command displays detailed help for the Get-ChildItem cmdlet by specify ing one of its aliases, "ls." The Detailed parameter requests the detailed view of the help file, which includes parameter descriptions and examples. To see the complete help file for a cmdlet, use the Full parameter. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-help format-string -full Description ----------- This command displays the full view help for the Format-String cmdlet. The full view of help includes parameter descriptions, examples, and a table of technical details about the parameters. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-help start-service -examples Description ----------- This command displays examples of using start-service in Windows PowerShell commands. -------------------------- EXAMPLE 8 -------------------------- C:\PS>get-help get-childitem -parameter f* Description ----------- This command displays descriptions of the parameters of the Get-ChildItem c mdlet that begin with "f" (filter and force). For descriptions of all param eters, type "get-help get-childitem parameter*". -------------------------- EXAMPLE 9 -------------------------- C:\PS>(get-help write-output).syntax Description ----------- This command displays only the syntax of the Write-Output cmdlet. Syntax is one of many properties of help objects; others are description, d etails, examples, and parameters. To find all properties and methods of hel p objects, type "get-help <cmdlet-name> | get-member"; for example, "get-he lp start-service | get member". -------------------------- EXAMPLE 10 -------------------------- C:\PS>(get-help trace-command).alertset Description ----------- This command displays the notes about the cmdlet. The notes are stored in t he alertSet property of the help object. The notes include conceptual information and tips for using the cmdlet. By default, the notes are displayed only when you use the Full parameter of Ge t-Help, but you can also display them by using the alertSet property. -------------------------- EXAMPLE 11 -------------------------- C:\PS>get-help add-member -full | out-string -stream | select-string -patte rn clixml Description ----------- This example shows how to search for a word in particular cmdlet help topic . This command searches for the word "clixml" in the full version of the he lp topic for the Add-Member cmdlet. Because the Get-Help cmdlet generates a MamlCommandHelpInfo object, not a s tring, you need to use a command that transforms the help topic content int o a string, such as Out-String or Out-File. -------------------------- EXAMPLE 12 -------------------------- C:\PS>get-help get-member -online Description ----------- This command displays the online version of the help topic for the Get-Memb er cmdlet. -------------------------- EXAMPLE 13 -------------------------- C:\PS>get-help remoting Description ----------- This command displays a list of topics that include the word "remoting" in their contents. When you enter a word that does not appear in any topic title, Get-Help dis plays a list of topics that include that word. -------------------------- EXAMPLE 14 -------------------------- C:\PS>get-help get-item -path SQLSERVER:\DataCollection NAME Get-Item SYNOPSIS Gets a collection of Server objects for the local computer and any comp uters to which you have made a SQL Server PowerShell connection. ... C:\PS> cd SQLSERVER:\DataCollection C:\PS> SQLSERVER:\DataCollection> get-help get-item NAME Get-Item SYNOPSIS Gets a collection of Server objects for the local computer and any comp uters to which you have made a SQL Server PowerShell connection. ... C:\PS> Get-Item NAME Get-Item SYNOPSIS Gets the item at the specified location. ... Description ----------- This example shows how to get help for the Get-Item cmdlet that explains ho w to use the cmdlet in the DataCollection node of the Windows PowerShell SQ L Server provider. The example shows two ways of getting the custom help for Get-Item. The first command uses the Path parameter of Get-Help to specify the provid er path. This command can be entered at any path location. The second command uses the Set-Location cmdlet (alias = "cd") to go to the provider path. From that location, even without the Path parameter, the Ge t-Help command gets the custom help for the provider path. The third command shows that a Get-Help command in a file system path, and without the Path parameter, gets the standard help for the Get-Item cmdlet. -------------------------- EXAMPLE 15 -------------------------- C:\PS>get-help c:\ps-test\MyScript.ps1 Description ----------- This command gets help for the MyScript.ps1 script. For information about w riting help for your functions and scripts, see about_Comment_Based_Help. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113316 about_Comment_Based_Help Get-Command Get-PSDrive Get-Member Import-Alias NAME Import-Alias SYNOPSIS Imports an alias list from a file. SYNTAX Import-Alias [-Path] <string> [-Force] [-PassThru] [-Scope <string>] [-Conf irm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Import-Alias cmdlet imports an alias list from a file. PARAMETERS -Force [<SwitchParameter>] Allows the cmdlet to import an alias that is already defined and is rea d only. You can use the following command to display information about the currently-defined aliases: get-alias | select-object name,Options The value of the Options property will include "ReadOnly" if the corres ponding alias is read only. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the alias. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the path to a file that includes exported alias information. Wildcards are allowed but they must resolve to a single name. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Scope <string> Specifies the scope into which the aliases are imported. Valid values a re "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see ab out_Scopes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Import-Alias. OUTPUTS None or System.Management.Automation.AliasInfo When you use the Passthru parameter, Import-Alias returns a System.Mana gement.Automation.AliasInfo object that represents the alias. Otherwise , this cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>import-alias test.txt Description ----------- This command imports alias information from a file named test.txt. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113339 Export-Alias Get-Alias New-Alias Set-Alias Import-Clixml NAME Import-Clixml SYNOPSIS Imports a CLIXML file and creates corresponding objects within Windows Powe rShell. SYNTAX Import-Clixml [-Path] <string[]> [<CommonParameters>] DESCRIPTION The Import-Clixml cmdlet imports a CLIXML file with data that represents Mi crosoft .NET Framework objects and creates the objects in Windows PowerShel l. PARAMETERS -Path <string[]> Specifies the location of the XML files to be converted into Windows Po werShell objects. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Import-Clixml. OUTPUTS PSObject Import-Clixml returns objects that have been deserialized from the stor ed XML files. NOTES When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>". -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process | export-clixml pi.xml C:\PS> $processes = import-clixml pi.xml Description ----------- This command uses the Export-Clixml cmdlet to save a serialized copy of the process information returned by Get-Process. It then uses Import-Clixml to retrieve the contents of the serialized file and re-create an object that is stored in the $processes variable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113340 Import-Counter NAME Import-Counter SYNOPSIS Imports performance counter log files (.blg, .csv, .tsv) and creates the ob jects that represent each counter sample in the log. SYNTAX Import-Counter [-Path] <string[]> [-Counter <string[]>] [-EndTime <DateTime >] [-MaxSamples <Int64>] [-StartTime <DateTime>] [<CommonParameters>] Import-Counter [-Path] <string[]> -ListSet <string[]> [<CommonParameters>] Import-Counter [-Path] <string[]> -Summary <switch> [<CommonParameters>] DESCRIPTION The Import-Counter cmdlet imports performance counter data from performance counter log files and creates objects for each counter sample in the file. The PerformanceCounterSampleSet objects that it creates are identical to t he objects that Get-Counter returns when it collects performance counter da ta. You can import data from comma-separated value (.csv), tab-separated value ( .tsv), and binary performance log (.blg) performance log files. If you ar e using .blg files, you can import multiple files (up to 32 different files ) in each command. And, you can use the parameters of Import-Counter to fil ter the data that you import. Along with Get-Counter and Export-Counter, this feature lets you collect, e xport, import, combine, filter, manipulate, and re-export performance count er data within Windows PowerShell. PARAMETERS -Counter <string[]> Imports data only for the specified performance counters. By default, I mport-Counter imports all data from all counters in the input files. E nter one or more counter paths. Wildcards are permitted in the Instance part of the path. Each counter path has the following format. Notice that the ComputerNam e value is required in the path, even on the local computer. "\\<ComputerName>\<CounterSet>(<Instance>)\ For example: "\\Server01\Processor(2)\% User Time" "\Processor(*)\% Processor Time Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -EndTime <DateTime> Imports only counter data with a timestamp less than or equal to the sp ecified date and time. Enter a DateTime object, such as one created by the Get-Date cmdlet. By default, Import-Counter imports all counter dat a in the files specified by the Path parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ListSet <string[]> Gets the performance counter sets that are represented in the exported files. Commands with this parameter do not import any data. Enter one or more counter set names. Wildcards are permitted. To get a ll counter sets in the file, type "import-counter -listset *". Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? true -MaxSamples <Int64> Specifies the maximum number of samples of each counter to import. By d efault, Get-Counter imports all of the data in the files specified by t he Path parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the file paths of the files to be imported. This parameter is required. Enter the path and file name of a, .csv,, .tsv, or .blg file that you e xported by using the Export-Counter cmdlet. You can specify only one .c sv or .tsv file, but you can specify multiple .blg files (up to 32) in each command. You can also pipe file path strings (in quotation marks) to Import-Counter. Required? true Position? 2 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? true -StartTime <DateTime> Imports only counter data with a timestamp greater than or equal to the specified date and time. Enter a DateTime object, such as one created by the Get-Date cmdlet. By default, Import-Counter imports all counter data in the files specified by the Path parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Summary <switch> Gets a summary of the imported data, instead of getting individual coun ter data samples. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe performance counter log paths to Import-Counter. OUTPUTS Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet, Micro soft.PowerShell.Commands.GetCounter.CounterSet, Microsoft.PowerShell.Comman ds.GetCounter.CounterFileInfo By default, Import-Counter returns a Microsoft.PowerShell.Commands.GetC ounter.PerformanceCounterSampleSet. If you use the ListSet parameter, I mport-Command returns a Microsoft.PowerShell.Commands.GetCounter.Counte rSet object. If you use the Summary parameter, Import-Command returns a Microsoft.PowerShell.Commands.GetCounter.CounterFileInfo object. NOTES The Import-Counter cmdlet does not have a ComputerName parameter. Howev er, if the computer is configured for Windows PowerShell remoting, you can use the Invoke-Command cmdlet to run an Import-Counter command on a remote computer. -------------------------- EXAMPLE 1 -------------------------- C:\PS># Import-Counter Description ----------- This command imports all of the counter data from the ProcessorData.csv fil e into the $data variable. C:\PS> $data = import-counter -path ProcessorData.csv -------------------------- EXAMPLE 2 -------------------------- C:\PS># Import-Counter Description ----------- This command imports only the Processor(_total)\Interrupts\sec counter data from the ProcessorData.blg file into the $i variable. C:\PS> $i = import-counter -path ProcessorData.blg -counter "\\SERVER01\Pro cessor(_Total)\Interrupts/sec" -------------------------- EXAMPLE 3 -------------------------- C:\PS># Import-Counter Description ----------- This example shows how to select data from a performance counter log file ( .blg) and then export the selected data to a .csv file. The first four commands get the counter paths from the file and save them i n a variable. The last two commands import selected data and then export on ly the selected data. The first command uses Import-Counter to import all of the performance coun ter data from the ProcessorData.blg files. The command saves the data in th e $data variable. C:\PS> $data = import-counter .\processordata.blg The second command displays the counter paths in the $data variable. The di splay is shown in the command output. C:\PS> $data[0].countersamples | format-table path Path ---- \\SERVER01\Processor(_Total)\DPC Rate \\SERVER01\Processor(1)\DPC Rate \\SERVER01\Processor(0)\DPC Rate \\SERVER01\Processor(_Total)\% Idle Time \\SERVER01\Processor(1)\% Idle Time \\SERVER01\Processor(0)\% Idle Time \\SERVER01\Processor(_Total)\% C3 Time \\SERVER01\Processor(1)\% C3 Time ... The third command gets the counter paths that end in "Interrupts/sec" and s aves the paths in the $IntCtrs variable. C:\PS> $IntCtrs = $data[0].countersamples | where {$_.path -like "*interrup ts/sec"} | foreach {$_.path} The fourth command displays the selected counter paths. C:\PS> $IntCtrs \\SERVER01\Processor(_Total)\Interrupts/sec \\SERVER01\Processor(1)\Interrupts/sec \\SERVER01\Processor(0)\Interrupts/sec The fifth command uses the Import-Counter cmdlet to import the data. It use s the Counter parameter with the $IntCtrs variable to import only data for the counter paths in $IntCtrs. C:\PS> $i = import-counter -path .\processordata.blg -counter $intCtrs The sixth command uses the Export-Counter cmdlet to export the data. C:\PS> $i | export-counter -path .\interrupts.csv -format CSV -------------------------- EXAMPLE 4 -------------------------- C:\PS># Import-Counter Description ----------- This example shows how to display all the counter paths in a group of impor ted counter sets. The first command uses the ListSet parameter to get all of the counter sets that are represented in a counter data file. C:\PS> import-counter -path processordata.csv -listset * CounterSetName : Processor MachineName : \\SERVER01 CounterSetType : MultiInstance Description : Paths : {\\SERVER01\Processor(*)\DPC Rate, \\SERVER01\Processo r(*)\% Idle Time, \\SERVER01 \Processor(*)\% C3 Time, \\SERVER01\Processor(*)\% Int errupt Time...} PathsWithInstances : {\\SERVER01\Processor(_Total)\DPC Rate, \\SERVER01\Pro cessor(1)\DPC Rate, \\SERVER01 \Processor(0)\DPC Rate, \\SERVER01\Processor(_Total)\% Idle Time...} Counter : {\\SERVER01\Processor(*)\DPC Rate, \\SERVER01\Processo r(*)\% Idle Time, \\SERVER01 \Processor(*)\% C3 Time, \\SERVER01\Processor(*)\% Int errupt Time...} The second command gets all of the counter paths from the list set. C:\PS> import-counter -path processordata.csv -listset * | foreach {$_.path s} \\SERVER01\Processor(*)\DPC Rate \\SERVER01\Processor(*)\% Idle Time \\SERVER01\Processor(*)\% C3 Time \\SERVER01\Processor(*)\% Interrupt Time \\SERVER01\Processor(*)\% C2 Time \\SERVER01\Processor(*)\% User Time \\SERVER01\Processor(*)\% C1 Time \\SERVER01\Processor(*)\% Processor Time \\SERVER01\Processor(*)\C1 Transitions/sec \\SERVER01\Processor(*)\% DPC Time \\SERVER01\Processor(*)\C2 Transitions/sec \\SERVER01\Processor(*)\% Privileged Time \\SERVER01\Processor(*)\C3 Transitions/sec \\SERVER01\Processor(*)\DPCs Queued/sec \\SERVER01\Processor(*)\Interrupts/sec -------------------------- EXAMPLE 5 -------------------------- C:\PS># Import-Counter Description ----------- This example imports only the counter data that has a time stamp between th e starting an ending ranges specified in the command. The first command lists the time stamps of all of the data in the Processor Data.blg file. C:\PS> import-counter -path .\disk.blg | format-table timestamp The second and third commands save particular time stamps in the $start and $end variables. The strings are cast to DateTime objects. C:\PS> $start = [datetime]"7/9/2008 3:47:00 PM" C:\PS> $end = [datetime]"7/9/2008 3:47:59 PM" The fourth command uses Import-Counter to get only counter data that has a time stamp between the start and end times (inclusive). The command uses th e StartTime and EndTime parameters to specify the range. C:\PS> $t-data = import-counter -path disk.blg -starttime $start -endtime $end -------------------------- EXAMPLE 6 -------------------------- C:\PS># Import-Counter Description ----------- This example shows how to import the five oldest and five newest samples fr om a performance counter log file. The first command uses the Import-Counter cmdlet to import data from the Di sk.blg file. The command uses the MaxSamples parameter to limit the import to five counter samples. This command gets the first (oldest) five samples in the file. C:\PS> import-counter -path disk.blg -maxSamples 5 The second command uses array notation and the Windows PowerShell range ope rator (..) to get the last five counter samples from the file. These are th e five newest samples. C:\PS> (import-counter -path disk.blg)[-1 .. -5] -------------------------- EXAMPLE 7 -------------------------- C:\PS># Import-Counter Description ----------- This command uses the Summary parameter to get a summary of the counter dat a from the Memory.blg file. C:\PS> import-counter D:\Samples\memory.blg -summary OldestRecord NewestRecord SampleCount ------------ ------------ ----------- 7/10/2008 2:59:18 PM 7/10/2008 3:00:27 PM 1000 -------------------------- EXAMPLE 8 -------------------------- C:\PS># Import-Counter Description ----------- This example updates a performance counter log file. The first command uses the ListSet parameter of Import-Counter to get the c ounters in OldData.blg, an existing counter log file. The command uses a pi peline operator (|) to send the data to a Foreach-Object command that gets only the values of the PathsWithInstances property of each object. C:\PS> $counters = import-counter olddata.blg -ListSet * | foreach {$_.Path sWithInstances} The second command uses those same counters in a new Get-Counter command to get a current sample, and export it to the NewData.blg file. C:\PS> get-counter -counter $counters -maxSamples 20 | export-counter c:\Lo gs\newdata.blg -------------------------- EXAMPLE 9 -------------------------- C:\PS># Import-Counter Description ----------- This command imports performance log data from two logs and saves the data in the $counters variable. The command uses a pipeline operator to send per formance log paths to Import-Counter. C:\PS> $counters = "d:\test\pdata.blg", "d:\samples\netlog.blg" | import-co unter Notice that each path is enclosed in quotation marks and that the paths are separated from each other by a comma. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=138338 Get-Counter Export-Counter Import-CSV NAME Import-CSV SYNOPSIS Converts object properties in a comma-separated value (CSV) file into CSV v ersions of the original objects. SYNTAX Import-CSV [[-Delimiter] <char>] [-Path] <string[]> [-Header <string[]>] [ CommonParameters>] Import-CSV -UseCulture [-Path] <string[]> [-Header <string[]>] [<CommonPara meters>] DESCRIPTION The Import-CSV cmdlet creates objects from CSV variable-length files that a re generated by the Export-CSV cmdlet. You can use the parameters of the Import-CSV cmdlet to specify the column h eader row, which determines the property names of the resulting objects; to specify the item delimiter; or to direct Import-CSV to use the list separa tor for the current culture as the item delimiter. The objects that Import-CSV creates are CSV versions of the original object s. The property values of the CSV objects are string versions of the proper ty values of the original objects. The CSV versions of the objects do not h ave any methods. You can also use the ConvertTo-CSV and ConvertFrom-CSV cmdlets to convert o bjects to CSV strings (and back). These cmdlets are the same as the Export- CSV and Import-CSV cmdlets, except that they do not save the CSV strings in a file. PARAMETERS -Delimiter <char> Specifies the delimiter that separates the property values in the CSV f ile. The default is a comma (,). Enter a character, such as a colon (:) . To specify a semicolon (;), enclose it in quotation marks. If you specify a character other than the actual string delimiter in th e file, Import-CSV cannot create objects from the CSV strings. Instead, it returns the strings. Required? false Position? 2 Default value , Accept pipeline input? false Accept wildcard characters? false -Header <string[]> Specifies an alternate column header row for the imported file. The col umn header determines the names of the properties of the object that Im port-CSV creates. Enter a comma-separated list of the column headers. Enclose each item i n quotation marks (single or double). Do not enclose the header string in quotation marks. If you enter fewer column headers than there are co lumns, the remaining columns will have no header. If you enter more hea ders than there are columns, the extra headers are ignored. When using the Header parameter, delete the original header row from th e CSV file. Otherwise, Import-CSV creates an extra object from the item s in the header row. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the CSV file to import. You can also pipe a path to Import-CSV. Required? true Position? 1 Default value None Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -UseCulture [<SwitchParameter>] Use the list separator for the current culture as the item delimiter. T he default is a comma (,). To find the list separator for a culture, use the following command: (G et-Culture).TextInfo.ListSeparator. If you specify a character other th an the delimiter used in the CSV strings, ConvertFrom-CSV cannot create objects from the CSV strings. Instead, it returns the strings. Required? true Position? named Default value Comma Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Import-CSV. OUTPUTS Object. Import-CSV returns the objects described by the content in the CSV file . NOTES Because the imported objects are CSV versions of the object type, they are not recognized and formatted by the Windows PowerShell type formatt ing entries that format the non-CSV versions of the object type. In the CSV file, each object is represented by a comma-separated list o f the property values of the object. The property values are converted to strings (by using the ToString() method of the object), so they are generally represented by the name of the property value. Export-CSV doe s not export the methods of the object. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process | export-csv processes.csv C:\PS> $p = import-CSV processes.csv C:\PS> $p | get-member TypeName: CSV:System.Diagnostics.Process Name MemberType Definition ---- ---------- ---------- Equals Method System.Boolean Equals(Object obj) GetHashCode Method System.Int32 GetHashCode() GetType Method System.Type GetType() ToString Method System.String ToString() BasePriority NoteProperty System.String BasePriority=8 Company NoteProperty System.String Company=Microsoft Cor poration ... C:\PS> $p | out-gridview Description ----------- This example shows how to export and then import a CSV file of Microsoft .N ET Framework objects. The first command uses the Get-Process cmdlet to get the process on the loc al computer. It uses a pipeline operator (|) to send the process objects to the Export-CSV cmdlet, which exports the process objects to the Processes. csv file in the current directory. The second command uses the Import-CSV cmdlet to import the processes in th e Import-CSV file. Then it saves the resulting process objects in the $p va riable. The third command uses a pipeline operator to pipe the imported objects to the Get-Member cmdlets. The result shows that they are CSV:System.Diagnosti c.Process objects, not the System.Diagnostic.Process objects that Get-Proce ss returns. Also, because there is no entry type in the formatting files for the CSV ve rsion of the process objects, these objects are not formatted in the same w ay that standard process objects are formatted. To display the objects, use the formatting cmdlets, such as Format-Table an d Format-List, or pipe the objects to Out-GridView. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-process | export-csv processes.csv -Delimiter : C:\PS> $p = import-csv processes.csv -Delimiter : Description ----------- This example shows how to use the Delimiter parameter of Import-CSV. In thi s example, the processes are exported to a file that uses a colon (:) as a delimiter. When importing, the Import-CSV file uses the Delimiter parameter to indicat e the delimiter that is used in the file. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$p = import-csv processes.csv -UseCulture C:\PS> (get-culture).textinfo.listseparator , Description ----------- This example shows how to use the UseCulture parameter of Import-CSV. The first command imports the objects in the Processes.csv file into the $p variable. It uses the UseCulture parameter to direct Import-CSV to use the list separator defined for the current culture. The second command displays the list separator for the current culture. It uses the Get-Culture cmdlet to get the current culture. It uses the dot (.) method to get the TextInfo property of the current culture and the ListSep arator property of the object in TextInfo. In this example, the command ret urns a comma. -------------------------- EXAMPLE 4 -------------------------- C:\PS>start-job -scriptblock { get-process } | export-csv jobs.csv C:\PS> $header = "MoreData","StatusMessage","Location","Command","State","F inished","InstanceId","SessionId","Name","ChildJobs","Output","Error","Prog ress","Verbose","Debug","Warning","StateChanged" # Delete header from file C:\PS> $a = (get-content jobs.csv) C:\PS> $a = $a[0], $a[2..($a.count - 1)] C:\PS> $a > jobs.csv C:\PS> $j = import-csv jobs.csv -header $header C:\PS> $j MoreData : True StatusMessage : Location : localhost Command : get-process State : Running Finished : System.Threading.ManualResetEvent InstanceId : 135bdd25-40d6-4a20-bd68-05282a59abd6 SessionId : 1 Name : Job1 ChildJobs : System.Collections.Generic.List`1[System.Management.Automat ion.Job] Output : System.Management.Automation.PSDataCollection`1[System.Mana gement.Automation.PSObject] Error : System.Management.Automation.PSDataCollection`1[System.Mana gement.Automation.ErrorRecord] Progress : System.Management.Automation.PSDataCollection`1[System.Mana gement.Automation.ProgressRecord] Verbose : System.Management.Automation.PSDataCollection`1[System.Stri ng] Debug : System.Management.Automation.PSDataCollection`1[System.Stri ng] Warning : System.Management.Automation.PSDataCollection`1[System.Stri ng] StateChanged : Description ----------- This example shows how to use the Header parameter of Import-CSV to change the names of properties in the resulting imported object. The first command uses the Start-Job cmdlet to start a background job that runs a Get-Process command on the local computer. A pipeline operator (|) s ends the resulting job object to the Export-CSV cmdlet, which converts the job object to CSV format. An assignment operator (=) saves the resulting CS V in the Jobs.csv file. The second command saves a header in the $header variable. Unlike the defau lt header, this header uses "MoreData" instead of "HasMoreData" and "State" instead of "JobStateInfo". The next three commands delete the original header (the second line) from t he Jobs.csv file. The sixth command uses the Import-CSV cmdlet to import the Jobs.csv file an d convert the CSV strings into a CSV version of the job object. The command uses the Header parameter to submit the alternate header. The results are stored in the $j variable. The seventh command displays the object in the $j variable. The resulting o bject has "MoreData" and "State" properties, as shown in the command output . -------------------------- EXAMPLE 5 -------------------------- C:\PS>".\processes.csv" | import-csv Description ----------- This command imports the objects from the Processes.csv file. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113341 Export-CSV ConvertTo-CSV ConvertFrom-CSV Import-LocalizedData NAME Import-LocalizedData SYNOPSIS Imports language-specific data into scripts and functions based on the UI c ulture that is selected for the operating system. SYNTAX Import-LocalizedData [-BindingVariable] <string> [[-UICulture] <string>] [- BaseDirectory <string>] [-FileName <string>] [-SupportedCommand <string[]>] [<CommonParameters>] DESCRIPTION The Import-LocalizedData cmdlet dynamically retrieves strings from a subdir ectory whose name matches the UI language set for the current user of the o perating system. It is designed to enable scripts to display user messages in the UI language selected by the current user. Import-LocalizedData imports data from .psd1 files in language-specific sub directories of the script directory and saves them in a local variable that is specified in the command. The cmdlet selects the subdirectory and file based on the value of the $PSUICulture automatic variable. When you use the local variable in the script to display a user message, the message appear s in the user's UI language. You can use the parameters of Import-LocalizedData to specify an alternate UI culture, path, and file name, to add supported commands, and to suppress the error message that appears if the .psd1 files are not found. The Import-LocalizedData cmdlet supports script internationalization in Win dows PowerShell 2.0. This initiative aims to better serve users worldwide b y making it easy for scripts to display user messages in the UI language of the current user. For more information about this and about the format of the .psd1 files, see about_Script_Internationalization. PARAMETERS -BaseDirectory <string> Specifies the base directory where the .psd1 files are located. The def ault is the directory where the script is located. Import-LocalizedData searches for the .psd1 file for the script in a language-specific subd irectory of the base directory. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -BindingVariable <string> Specifies a variable into which the text strings are imported. Enter a variable name without a dollar sign ($). When using Import-LocalizedData to replace default text strings specifi ed in the DATA section of a script, assign the DATA section to a variab le and enter the name of the DATA section variable in the value of the BindingVariable parameter. Then, when Import-LocalizedData saves the im ported content in the BindingVariable, the imported data will replace t he default text strings. If you are not specifying default text strings , you can select any variable name. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -FileName <string> Specifies the name of the .psd1 file to be imported. Enter a file name without the .psd1 file name extension. The default is the name of the script. For example, if the script is Fi ndFiles.ps1, Import-LocalizedData searches for FindFiles.psd1. You can use this parameter to direct Import-LocalizedData to search for a diffe rent .psd1 file. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SupportedCommand <string[]> Specifies cmdlets and functions that generate only data. Use this parameter to include cmdlets and functions that you have writt en or tested. For more information, see about_Script_Internationalizati on. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -UICulture <string> Specifies an alternate UI culture. The default is the value of the $PsU ICulture automatic variable. Enter a UI culture in "<language>-<region> " format, such as en-US, de-DE, or ar-SA. The value of the UICulture parameter determines the language-specific s ubdirectory (within the base directory) from which Import-LocalizedData gets the .psd1 file for the script. The cmdlet searches for a subdirectory with the same name as the value of the UICulture parameter or the $PsUICulture automatic variable, suc h as "de-DE" or "ar-SA". If it cannot find the directory, or the direct ory does not contain a .psd1 file for the script, it searches for a sub directory with the name of the language code, such as "de" or "ar". If it cannot find the subdirectory or .psd1 file, the command fails and th e data is displayed in the default language specified in the script. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Collections.Hashtable Import-LocalizedData saves the hash table in the variable that is speci fied by the value of the BindingVariable parameter. NOTES Before using Import-LocalizedData, localize your user messages. Format the messages for each locale (UI culture) in a hash table of key/value pairs, and save the hash table in a file with the same name as the scri pt and a .psd1 file name extension. Create a directory under the script directory for each supported UI culture, and then save the .psd1 file for each UI culture in the directory with the UI culture name. For example, localize your user messages for the de-DE locale and forma t them in a hash table. Save the hash table in a <ScriptName>.psd1 file . Then create a de-DE subdirectory under the script directory, and save the de-DE <ScriptName>.psd1 file in the de-DE subdirectory. Repeat thi s method for each locale that you support. Import-LocalizedData performs a structured search for the localized use r messages for a script. Import-LocalizedData begins the search in the directory where the scrip t file is located (or the value of the BaseDirectory parameter). It the n searches within the base directory for a subdirectory with the same n ame as the value of the $PsUICulture variable (or the value of the UICu lture parameter), such as "de-DE" or "ar-SA". Then, it searches in that subdirectory for a .psd1 file with the same name as the script (or the value of the FileName parameter). If Import-LocalizedData cannot find a subdirectory with the name of the UI culture, or the subdirectory does not contain a .psd1 file for the script, it searches for a .psd1 file for the script in a subdirectory w ith the name of the language code, such as "de" or "ar". If it cannot f ind the subdirectory or .psd1 file, the command fails, the data is disp layed in the default language in the script, and an error message is di splayed explaining that the data could not be imported. To suppress the message and fail gracefully, use the ErrorAction common parameter with a value of SilentlyContinue. If Import-LocalizedData finds the subdirectory and the .psd1 file, it i mports the hash table of user messages into the value of the BindingVar iable parameter in the command. Then, when you display a message from t he hash table in the variable, the localized message is displayed. For more information, see about_Script_Internationalization. -------------------------- EXAMPLE 1 -------------------------- C:\PS>import-localizeddata -bindingVariable messages Description ----------- This command imports text strings into the $messages variable. It uses all of the default values for the cmdlet parameters. If the command is included in the Archives.ps1 script in the C:\test direct ory, and the value of the $PsUICulture automatic variable is zh-CN, Import- LocalizedData imports the Archives.psd1 file in the C:\test\zh-CN directory . -------------------------- EXAMPLE 2 -------------------------- C:\PS>import-localizeddata -bindingVariable msgTbl -uiculture ar-SA -filena me Simple -baseDirectory C:\Data\Localized Description ----------- This command imports text strings into the $msgTbl variable of a script. It uses the UICulture parameter to direct the cmdlet to import data from th e Simple.psd1 file in the ar-SA subdirectory of C:\Data\Localized. -------------------------- EXAMPLE 3 -------------------------- C:\PS># In C:\Test\en-US\test.psd1: ConvertFrom-StringData @' # English strings Msg1 = "The Name parameter is missing from the command." Msg2 = "This command requires the credentials of a member of the Administra tors group on the computer." Msg3 = "Use $_ to represent the object that is being processed." '@ # In C:\Test\Test.ps1 import-localizeddata -bindingvariable messages write-host $messages.msg2 # In Windows PowerShell C:\PS> .\test.ps1 This command requires the credentials of a member of the Administrators gro up on the computer. Description ----------- This example shows how to use localized data in a simple script. The first part of the example shows the contents of the Test.psd1 file. It contains a ConvertFrom-StringData command that converts a series of named t ext strings into a hash table. The test.psd1 file is located in the en-US s ubdirectory of the C:\Test directory that contains the script. The second part of the example shows the contents of the Test.ps1 script. I t contains an Import-LocalizedData command that imports the data from the m atching .psd1 file into the $Messages variable and a Write-Host command tha t writes one of the messages in the $Messages variable to the host program. The last part of the example runs the script. The output shows that it disp lays the correct user message in the UI language set for the current user o f the operating system. -------------------------- EXAMPLE 4 -------------------------- C:\PS># In TestScript.ps1 $UserMessages = DATA { ConvertFrom-StringData @' # English strings Msg1 = "Enter a name." Msg2 = "Enter your employee ID." Msg3 = "Enter your building number." '@ } Import-LocalizedData -bindingVariable UserMessages $UserMessages.Msg1 ... Description ----------- This example shows how to use Import-LocalizedData to replace default text strings defined in the DATA section of a script. In this example, the DATA section of the TestScript.ps1 script contains a C onvertFrom-StringData command that converts the contents of the DATA sectio n to a hash table and stores in the value of the $UserMessages variable. The script also includes an Import-LocalizedData command, which imports a h ash table of translated text strings from the TestScript.psd1 file in the s ubdirectory specified by the value of the $PsUICulture variable. If the com mand finds the .psd1 file, it saves the translated strings from the file in the value of the same $UserMessages variable, overwriting the hash table s aved by the DATA section logic. The third command displays the first message in the $UserMessages variable. If the Import-LocalizedData command finds a .psd1 file for the $PsUICulture language, the value of the $UserMessages variable contains the translated text strings. If the command fails for any reason, the command displays the default text strings defined in the DATA section of the script. -------------------------- EXAMPLE 5 -------------------------- C:\PS># In Day1.ps1 Import-LocalizedData -bindingVariable Day Day.MessageDate # In Day2.ps1 Import-LocalizedData -bindingVariable Day -errorAction:silentlycontinue Day.MessageDate C:\PS> .\Day1.ps1 Import-LocalizedData : Cannot find PowerShell data file 'Day1.psd1' in dire ctory 'C:\ps-test\fr-BE\' or any parent culture directories. At C:\ps-test\Day1.ps1:17 char:21 + Import-LocalizedData < Day Today is Tuesday C:\PS> .\Day2.ps1 Today is Tuesday Description ----------- This example shows how to suppress the error messages that appear when Impo rt-LocalizedData cannot find the directories that match the user's UI cultu re or cannot find a .psd1 file for the script in those directories. You can use the ErrorAction common parameter with a value of "SilentlyConti nue" to suppress the error message. This is especially useful when you have provided user messages in a default or "fallback" language, and no error m essage is needed. This example compares two scripts, Day1.ps1 and Day2.ps1, that include an I mport-LocalizedData command. The scripts are identical, except that Day2 us es the ErrorAction common parameter with a value of SilentlyContinue. The sample output shows the results of running both scripts when the UI cul ture is set to fr-BE and there are no matching files or directories for tha t UI culture. Day1.ps1 displays an error message and English output. Day2.p s1 just displays the English output. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113342 about_Script_Internationalization Import-Module NAME Import-Module SYNOPSIS Adds modules to the current session. SYNTAX Import-Module [-Name] <string[]> [-Alias <string[]>] [-ArgumentList <Object []>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <string[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]>] [-Version <Version>] [<CommonParameters>] Import-Module [-Assembly] <Assembly[]> [-Alias <string[]>] [-ArgumentList Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <stri ng[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]>] [-Ve rsion <Version>] [<CommonParameters>] Import-Module [-ModuleInfo] <PSModuleInfo[]> [-Alias <string[]>] [-Argument List <Object[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Force] [-Function <string[]>] [-Global] [-PassThru] [-Prefix <string>] [-Variable <string[]> ] [-Version <Version>] [<CommonParameters>] DESCRIPTION The Import-Module cmdlet adds one or more modules to the current session. A module is a package that contains members (such as cmdlets, providers, sc ripts, functions, variables, and other tools and files) that can be used in Windows PowerShell. After a module is imported, you can use the module mem bers in your session. To import a module, use the Name, Assembly, or ModuleInfo parameter to iden tify the module to import. By default, Import-Module imports all members th at the module exports, but you can use the Alias, Function, Cmdlet, and Var iable parameters to restrict the members that are imported. Import-Module imports a module only into the current session. To import the module into all sessions, add an Import-Module command to your Windows Pow erShell profile. For more information about profiles, see about_Profiles. For more information about modules, see about_Modules. PARAMETERS -Alias <string[]> Imports only the specified aliases from the module into the current ses sion. Enter a comma-separated list of aliases. Wildcard characters are permitted. Some modules automatically export selected aliases into your session wh en you import the module. This parameter lets you select from among the exported aliases. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -ArgumentList <Object[]> Specifies arguments (parameter values) that are passed to a script modu le during the Import-Module command. This parameter is valid only when you are importing a script module. You can also refer to ArgumentList by its alias, "args". For more infor mation, see about_Aliases. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -AsCustomObject [<SwitchParameter>] Returns a custom object with members that represent the imported module members. This parameter is valid only for script modules. When you use the AsCustomObject parameter, Import-Module imports the mo dule members into the session and then returns a PSCustomObject object instead of a PSModuleInfo object. You can save the custom object in a v ariable and use dot notation to invoke the members. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Assembly <Assembly[]> Imports the cmdlets and providers implemented in the specified assembly objects. Enter a variable that contains assembly objects or a command that creates assembly objects. You can also pipe an assembly object to Import-Module. When you use this parameter, only the cmdlets and providers implemented by the specified assemblies are imported. If the module contains other files, they are not imported, and you might be missing important membe rs of the module. Use this parameter for debugging and testing the modu le, or when you are instructed to use it by the module author. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Cmdlet <string[]> Imports only the specified cmdlets from the module into the current ses sion. Enter a list of cmdlets. Wildcard characters are permitted. Some modules automatically export selected cmdlets into your session wh en you import the module. This parameter lets you select from among the exported cmdlets. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -Force [<SwitchParameter>] Re-imports a module and its members, even if the module or its members have an access mode of read-only. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Function <string[]> Imports only the specified functions from the module into the current s ession. Enter a list of functions. Wildcard characters are permitted. Some modules automatically export selected functions into your session when you import the module. This parameter lets you select from among t he exported functions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -Global [<SwitchParameter>] When used in a script module (.psm1), this parameter imports modules in to the global session state. This parameter is effective only when it appears in a script module. Ot herwise, it is ignored. By default, the commands in a script module, including commands from ne sted modules, are imported into the caller's session state. To restrict the commands that a module exports, use an Export-ModuleMember command in the script module. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ModuleInfo <PSModuleInfo[]> Specifies module objects to import. Enter a variable that contains the module objects, or a command that gets the module objects, such as a "g et-module -listavailable" command. You can also pipe module objects to Import-Module. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the names of the modules to import. Enter the name of the mod ule or the name of a file in the module, such as a .psd1, .psm1, .dll, or ps1 file. File paths are optional. Wildcards are not permitted. You can also pipe module names and file names to Import-Module. If you omit a path, Import-Module looks for the module in the paths sav ed in the PSModulePath environment variable ($env:PSModulePath). Specify only the module name whenever possible. When you specify a file name, only the members that are implemented in that file are imported. If the module contains other files, they are not imported, and you mig ht be missing important members of the module. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns objects that represent the modules that were imported. By defau lt, this cmdlet does not generate any output. Notes -- When you pipe the output of a "get-module -listavailable" command to an Import-Module command with the PassThru parameter, Import-Module re turns the object that Get-Module passed to it without updating the obje ct. As a result, the Exported and NestedModules properties are not yet populated. -- When you use the Prefix parameter to specify a prefix for the member , the prefix does not appear in the member names in the properties of t he module object. The object records what was exported before the prefi x was applied. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Prefix <string> Adds the specified prefix to the nouns in the names of imported module members. Use this parameter to avoid name conflicts that might occur when differ ent members in the session have the same name. This parameter does not change the module, and it does not affect files that the module imports for its own use (known as "nested modules"). It affects only the names of members in the current session. For example, if you specify the prefix "UTC" and then import a Get-Date cmdlet, the cmdlet is known in the session as Get-UTCDate, and it is n ot confused with the original Get-Date cmdlet. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Variable <string[]> Imports only the specified variables from the module into the current s ession. Enter a list of variables. Wildcard characters are permitted. Some modules automatically export selected variables into your session when you import the module. This parameter lets you select from among t he exported variables. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -Version <Version> Specifies the version of the module to import. Use this parameter when you have different versions of the same module on your system. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String, System.Management.Automation.PSModuleInfo, System.Reflection .Assembly You can pipe a module name, module object, or assembly object to Import -Module. OUTPUTS None, System.Management.Automation.PSModuleInfo, or System.Management.Autom ation.PSCustomObject By default, Import-Module does not generate any output. If you use the PassThru parameter, it generates a System.Management.Automation.PSModul eInfo object that represents the module. If you use the AsCustomObject parameter, it generates a PSCustomObject object. NOTES You can also refer to Import-Module by its alias, "ipmo". For more info rmation, see about_Aliases. Before you can import a module, the module directory must be copied to a directory that is accessible to your local computer. For more informa tion, see about_Modules. Module members run in their own private module session state, so the co mmands that they use for internal processing do not affect your session state. If you import members with the same name and the same type into your se ssion, Windows PowerShell uses the member imported last by default. Var iables and aliases are replaced, and the originals are not accessible. Functions, cmdlets and providers are merely "shadowed" by the new membe rs, and they can be accessed by qualifying the command name with the na me of its snap-in, module, or function path. To update the formatting data for commands that have been imported from a module, use the Update-FormatData cmdlet. Update-FormatData also upd ates the formatting data for commands in the session that were imported from modules. If the formatting file for a module changes, you can run an Update-FormatData command to update the formatting data for importe d commands. You do not need to import the module again. To import a module that is created by Import-PSSession or Export-PSSess ion, the execution policy in the current session cannot be Restricted o r AllSigned, because the modules that Import-PSSession and Export-PSSes sion create contains unsigned script files that are prohibited by these policies. To use Import-Module without changing the execution policy f or the local computer, use the Scope parameter of Set-ExecutionPolicy t o set a less restrictive execution policy for a single process. -------------------------- EXAMPLE 1 -------------------------- C:\PS>import-module -name BitsTransfer Description ----------- This command imports the members of the BitsTransfer module into the curren t session. The Name parameter name (-Name) is optional and can be omitted. By default, Import-Module does not generate any output when it imports a mo dule. To request output, use the PassThru or AsCustomObject parameter, or t he Verbose common parameter. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-module -listAvailable | import-module Description ----------- This command imports all available modules in the path specified by the PSM odulePath environment variable ($env:psmodulepath) into the current session . -------------------------- EXAMPLE 3 -------------------------- C:\PS>$m = get-module -ListAvailable BitsTransfer, ServerBackup C:\PS> import-module -moduleInfo $m Description ----------- These commands import the members of the BitsTransfer and ServerBackup modu les into the current session. The first command uses the Get-Module cmdlet to get PSModuleInfo objects th at represent the BitsTransfer and ServerBackup modules. It saves the object s in the $m variable. The ListAvailable parameter is required when you are getting modules that are not yet imported into the session. The second command uses the ModuleInfo parameter of Import-Module to import the modules into the current session. These commands are equivalent to using a pipeline operator (|) to send the output of a Get-Module command to Import-Module. -------------------------- EXAMPLE 4 -------------------------- C:\PS>import-module -name c:\ps-test\modules\test -verbose VERBOSE: Loading module from path 'C:\ps-test\modules\Test\Test.psm1'. VERBOSE: Exporting function 'my-parm'. VERBOSE: Exporting function 'get-parm'. VERBOSE: Exporting function 'get-spec'. VERBOSE: Exporting function 'get-specDetails'. Description ----------- This command uses an explicit path to identify the module to import. It also uses the Verbose common parameter to get a list of the items import ed from the module. Without the Verbose, PassThru, or AsCustomObject parame ter, Import-Module does not generate any output when it imports a module. -------------------------- EXAMPLE 5 -------------------------- C:\PS>import-module BitsTransfer -cmdlet Add-BitsTransferFile, Get-BitsTran sfer C:\PS> get-module BitsTransfer Name : BitsTransfer Path : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Bits Transfer\BitsTransfer.psd1 Description : Guid : 8fa5064b-8479-4c5c-86ea-0d311fe48875 Version : 1.0.0.0 ModuleBase : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Bits Transfer ModuleType : Manifest PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {[Add-BitsTransfer, Add-BitsTransfer], [Complete-BitsTr ansfer, Complete-BitsTransfer], [Get-BitsTransfer, Get-BitsTransfer], [Rem ove-BitsTransfer, Remove-BitsTransfer]...} ExportedFunctions : {} ExportedVariables : {} NestedModules : {Microsoft.BackgroundIntelligentTransfer.Management} C:\PS> get-command -module BitsTransfer CommandType Name Definition ----------- ---- ---------- Cmdlet Add-BitsTransfer Add-BitsTransfer [-BitsJob] <BitsJob[]> [-S ource] <String[]> [[-Destination] <String[]>] [-Verbose] [-Debug] [-ErrorA. .. Cmdlet Get-BitsTransfer Get-BitsTransfer [[-Name] <String[]>] [-All Users] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningActi. .. Description ----------- This example shows how to restrict the module members that are imported int o the session and the effect of this command on the session. The first command imports only the Add-BitsTransfer and Get-BitsTransfer cm dlets from the BitsTransfer module. The command uses the Cmdlet parameter t o restrict the cmdlets that the module imports. You can also use the Alias, Variable, and Function parameters to restrict other members that a module imports. The second command uses the Get-Module cmdlet to get the object that repres ents the BitsTransfer module. The ExportedCmdlets property lists all of the cmdlets that the module exports, even when they were not all imported. The third command uses the Module parameter of the Get-Command cmdlet to ge t the commands that were imported from the BitsTransfer module. The results confirm that only the Add-BitsTransfer and Get-BitsTransfer cmdlets were i mported. -------------------------- EXAMPLE 6 -------------------------- C:\PS>import-module BitsTransfer -prefix PS -passthru Name : bitstransfer Path : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\bits transfer\bitstransfer.psd1 Description : Guid : 8fa5064b-8479-4c5c-86ea-0d311fe48875 Version : 1.0.0.0 ModuleBase : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\bits transfer ModuleType : Manifest PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {[Add-BitsTransfer, Add-BitsTransfer], [Remove-BitsTran sfer, Remove-BitsTransfer], [Complete-BitsTransfer, Complete-BitsTransfer] , [Get-BitsTransfer, Get-BitsTransfer]...} ExportedFunctions : {} ExportedVariables : {} NestedModules : {Microsoft.BackgroundIntelligentTransfer.Management} C:\PS> get-command -module bitstransfer CommandType Name Definition ----------- ---- ---------- Cmdlet Add-PSBitsTransfer Add-PSBitsTransfer [-BitsJob] BitsJob[]> [-Source] <String[]> ... Cmdlet Complete-PSBitsTransfer Complete-PSBitsTransfer [-BitsJ ob] <BitsJob[]> [-Verbose] [-Deb... Cmdlet Get-PSBitsTransfer Get-PSBitsTransfer [[-Name] <St ring[]>] [-AllUsers] [-Verbose] ... Cmdlet Remove-PSBitsTransfer Remove-PSBitsTransfer [-BitsJob ] <BitsJob[]> [-Verbose] [-Debug... Cmdlet Resume-PSBitsTransfer Resume-PSBitsTransfer [-BitsJob ] <BitsJob[]> [-Asynchronous] [-... Cmdlet Set-PSBitsTransfer Set-PSBitsTransfer [-BitsJob] BitsJob[]> [-DisplayName <String... Cmdlet Start-PSBitsTransfer Start-PSBitsTransfer [[-Source] <String[]>] [[-Destination] <St... Cmdlet Suspend-PSBitsTransfer Suspend-PSBitsTransfer [-BitsJo b] <BitsJob[]> [-Verbose] [-Debu... Description ----------- These commands import the BitsTransfer module into the current session, add a prefix to the member names, and then display the prefixed member names. The first command uses the Import-Module cmdlet to import the BitsTransfer module. It uses the Prefix parameter to add the PS prefix to all members th at are imported from the module and the PassThru parameter to return a modu le object that represents the imported module. The module object that the command returns has an ExportedCmdlets property that lists the exported members. The prefix does not appear in the cmdlet n ames, because it is applied after the members are exported (but before they are imported). The second command uses the Get-Command cmdlet to get the members that have been imported from the module. It uses the Module parameter to specify the module. The output shows that the module members were correctly prefixed. The prefix that you use applies only to the members in the current session. It does not change the module. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-module -list | format-table -property name, moduletype -auto Name ModuleType ---- ---------- Show-Calendar Script BitsTransfer Manifest PSDiagnostics Manifest TestCmdlets Script C:\PS> $a = import-module -name Show-Calendar -asCustomObject C:\PS> $a | get-member TypeName: System.Management.Automation.PSCustomObject Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Show-Calendar ScriptMethod System.Object Show-Calendar(); C:\PS> $a."show-calendar"() Description ----------- These commands demonstrate how to get and use the custom object that Import -Module returns. Custom objects include synthetic members that represent each of the importe d module members. For example, the cmdlets and functions in a module are co nverted to script methods of the custom object. Custom objects are very useful in scripting. They are also useful when seve ral imported objects have the same names. Using the script method of an obj ect is equivalent to specifying the fully qualified name of an imported mem ber, including its module name. The AsCustomObject parameter can be used only with a script module, so the first task is to determine which of the available modules is a script modul e. The first command uses the Get-Module cmdlet to get the available modules. The command uses a pipeline operator (|) to pass the module objects to the Format-Table cmdlet, which lists the Name and ModuleType of each module in a table. The second command uses the Import-Module cmdlet to import the Show-Calenda r script module. The command uses the AsCustomObject parameter to request a custom object. The command saves the resulting custom object in the $a var iable. The third command uses a pipeline operator to send the $a variable to the G et-Member cmdlet, which gets the properties and methods of the PSCustomObje ct in $a. The output shows a Show-Calendar script method. The last command uses the Show-Calendar script method. The method name must be enclosed in quotation marks, because it includes a hyphen. -------------------------- EXAMPLE 8 -------------------------- C:\PS>import-module BitsTransfer C:\PS> import-module BitsTransfer -force -prefix PS Description ----------- This example shows how to use the Force parameter of Import-Module when you are re-importing a module into the same session. The first command imports the BitsTransfer module. The second command impor ts the module again, this time using the Prefix parameter. The second command also includes the Force parameter, which removes the mod ule and then imports it again. Without this parameter, the session would in clude two copies of each BitsTransfer cmdlet, one with the standard name an d one with the prefixed name. -------------------------- EXAMPLE 9 -------------------------- C:\PS>get-date Saturday, September 12, 2009 6:47:04 PM C:\PS> import-module TestModule C:\PS> get-date 09255 C:\PS> get-command get-date | format-table -property commandtype, name, pss napin, module -auto CommandType Name pssnapin Module ----------- ---- -------- ------ Function Get-Date TestModule Cmdlet Get-Date Microsoft.PowerShell.Utility C:\PS> Microsoft.PowerShell.Utility\get-date Saturday, September 12, 2009 6:33:23 PM Description ----------- This example shows how to run commands that have been hidden by imported co mmands. The first command run the Get-Date cmdlet that comes with Windows PowerShel l. It returns a DateTime object with the current date. The second command imports the TestModule module. This module includes a fu nction named Get-Date that returns the Julian date. The third command runs the Get-Date command again. Because functions take p recedence over cmdlets, the Get-Date function from the TestModule module ra n, instead of the Get-Date cmdlet. The fourth command shows that there are two Get-Date commands in the sessio n, a function from the TestModule module and a cmdlet from the Microsoft.Po werShell.Utility snap-in. The fifth command runs the hidden cmdlet by qualifying the command name wit h the snap-in name. For more information about command precedence in Windows PowerShell, see ab out_command_precedence. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=141553 Get-Module New-Module Remove-Module Export-ModuleMember about_Modules Import-PSSession NAME Import-PSSession SYNOPSIS Imports commands from another session into the current session. SYNTAX Import-PSSession [-Session] <PSSession> [[-CommandName] <string[]>] [[-Form atTypeName] <string[]>] [-AllowClobber] [-ArgumentList <Object[]>] [-Comman dType {Alias | Function | Filter | Cmdlet | ExternalScript | Application | Script | All}] [-Module <string[]>] [-Prefix <string>] [<CommonParameters>] DESCRIPTION The Import-PSSession cmdlet imports commands (such as cmdlets, functions, a nd aliases) from a PSSession on a local or remote computer into the current session. You can import any command that Get-Command can find in the PSSes sion. Use an Import-PSSession command to import commands from a customized shell, such as a Microsoft Exchange Server shell, or from a session that includes Windows PowerShell modules and snap-ins or other elements that are not in the current session. To import commands, first use the New-PSSession cmdlet to create a PSSessio n. Then, use the Import-PSSession cmdlet to import the commands. By default , Import-PSSession imports all commands except for commands that have the s ame names as commands in the current session. To import all the commands, u se the AllowClobber parameter. You can use imported commands just as you would use any command in the sess ion. When you use an imported command, the imported part of the command run s implicitly in the session from which it was imported. However, the remote operations are handled entirely by Windows PowerShell. You need not even b e aware of them, except that you must keep the connection to the other sess ion (PSSession) open. If you close it, the imported commands are no longer available. Because imported commands might take longer to run than local commands, Imp ort-PSSession adds an AsJob parameter to every imported command. This param eter allows you to run the command as a Windows PowerShell background job. For more information, see about_Jobs. When you use Import-PSSession, Windows PowerShell adds the imported command s to a temporary module that exists only in your session and returns an obj ect that represents the module. To create a persistent module that you can use in future sessions, use the Export-PSSession cmdlet. The Import-PSSession cmdlet uses the implicit remoting feature of Windows P owerShell. When you import commands into the current session, they run impl icitly in the original session or in a similar session on the originating computer. PARAMETERS -AllowClobber [<SwitchParameter>] Imports the specified commands, even if they have the same names as com mands in the current session. If you import a command with the same name as a command in the current session, the imported command hides or replaces the original commands. For more information, see about_Command_Precedence. By default, Import-PSSession does not import commands that have the sam e name as commands in the current session. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -ArgumentList <Object[]> Imports the variant of the command that results from using the specifie d arguments (parameter values). For example, to import the variant of the Get-Item command in the certi ficate (Cert:) drive in the PSSession in $s, type "import-pssession -se ssion $s -command get-item -argumentlist cert:". Required? false Position? named Default value All command in the PSSession, except for c ommands with the same names as commands in the current session. Accept pipeline input? false Accept wildcard characters? false -CommandName <string[]> Imports only the commands with the specified names or name patterns. Wi ldcards are permitted. Use "CommandName" or its alias, "Name". By default, Import-PSSession imports all commands from the session, exc ept for commands that have the same names as commands in the current se ssion. This prevents imported commands from hiding or replacing command s in the session. To import all commands, even those that hide or repla ce other commands, use the AllowClobber parameter. If you use the CommandName parameter, the formatting files for the comm ands are not imported unless you use the FormatTypeName parameter. Simi larly, if you use the FormatTypeName parameter, no commands are importe d unless you use the CommandName parameter. Required? false Position? 3 Default value All commands in the PSSession, except for commands with the same names as commands in the current session. Accept pipeline input? false Accept wildcard characters? true -CommandType <CommandTypes> Imports only the specified types of command objects. The default value is Cmdlet. Use "CommandType" or its alias, "Type". Valid values are: -- Alias: The Windows PowerShell aliases in the remote session. -- All: The cmdlets and functions in the remote session. -- Application: All the files other than Windows-PowerShell files in th e paths that are listed in the Path environment variable ($env:path) in the remote session, including .txt, .exe, and .dll files. -- Cmdlet: The cmdlets in the remote session. "Cmdlet" is the default. -- ExternalScript: The .ps1 files in the paths listed in the Path envir onment variable ($env:path) in the remote session. -- Filter and Function: The Windows PowerShell functions in the remote session. -- Script: The script blocks in the remote session. Required? false Position? named Default value All command in the PSSession, except for c ommands with the same names as commands in the current session. Accept pipeline input? false Accept wildcard characters? false -FormatTypeName <string[]> Imports formatting instructions for the specified Microsoft .NET Framew ork types. Enter the type names. Wildcards are permitted. The value of this parameter must be the name of a type that is returned by a Get-FormatData command in the session from which the commands are being imported. To get all of the formatting data in the remote sessio n, type *. If the command does not include either the CommandName or FormatTypeNam e parameters, Import-PSSession imports formatting instructions for all .NET Framework types returned b y a Get-FormatData command in the remote session. If you use the FormatTypeName parameter, no commands are imported unles s you use the CommandName parameter. Similarly, if you use the CommandName parameter, the formatting files f or the commands are not imported unless you use the FormatTypeName para meter. Required? false Position? 4 Default value Types in the System.Management.Automation namespace Accept pipeline input? false Accept wildcard characters? true -Module <string[]> Imports only the commands in the specified Windows PowerShell snap-ins and modules. Enter the snap-in and module names. Wildcards are not perm itted. For more information, see about_PSSnapins and Import-Module. Required? false Position? named Default value All command in the PSSession, except for c ommands with the same names as commands in the current session. Accept pipeline input? false Accept wildcard characters? false -Prefix <string> Adds the specified prefix to the nouns in the names of imported command s. Use this parameter to avoid name conflicts that might occur when differ ent commands in the session have the same name. For example, if you specify the prefix "Remote" and then import a Get-D ate cmdlet, the cmdlet is known in the session as Get-RemoteDate and it is not confused with the original Get-Date cmdlet. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Session <PSSession> Specifies the PSSession from which the cmdlets are imported. Enter a va riable that contains a session object or a command that gets a session object, such as a New-PSSession or Get-PSSession command. You can speci fy only one session. This parameter is required. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS System.Management.Automation.PSModuleInfo Import-PSSession returns the same module object that New-Module and Get -Module return. However, the imported module is temporary and exists on ly in the current session. To create a permanent module on disk, use th e Export-PSSession cmdlet. NOTES Import-PSSession relies on the Windows PowerShell remoting infrastructu re. To use this cmdlet, the computer must be configured for WS-Manageme nt remoting. For more information, see about_Remote and about_Remote_Re quirements. You cannot use Import-PSSession to import variables or Windows PowerShe ll providers. When you import commands that have the same names as commands in the cu rrent session, the imported commands can hide aliases, functions, and c mdlets in the session and they can replace functions and variables in t he session. For more information, see about_Command_Precedence. Import-PSSession converts all commands into functions before it imports them. As a result, imported commands behave a bit differently than the y would if they retained their original command type. For example, if y ou import a cmdlet from a PSSession and then import a cmdlet with the s ame name from a module or snap-in, the cmdlet that is imported from the PSSession always runs by default because functions take precedence ove r cmdlets. Conversely, if you import an alias into a session that has a n alias with the same name, the original alias is always used, because aliases take precedence over functions. For more information, see about _Command_Precedence. Import-PSSession uses the Write-Progress cmdlet to display the progress of the command. You might see the progress bar while the command is ru nning. To find the commands to import, Import-PSSession uses the Invoke-Comman d cmdlet to run a Get-Command command in the PSSession. To get formatti ng data for the commands, it uses the Get-FormatData cmdlet. You might see error messages from Invoke-Command, Get-Command, and Get-FormatData when you run an Import-PSSession command. Also, Import-PSSession canno t import commands from a PSSession that does not include the Get-Comman d, Get-FormatData, Select-Object, and Get-Help cmdlets. Imported commands have the same limitations as other remote commands, i ncluding the inability to start a program with a user interface, such a s Notepad. Because Windows PowerShell profiles are not run in PSSessions, the comm ands that a profile adds to a session are not available to Import-PSSes sion. To import commands from a profile, use an Invoke-Command command to run the profile in the PSSession manually before importing commands. The temporary module that Import-PSSession creates might include a form atting file, even if the command does not import formatting data. If th e command does not import formatting data, any formatting files that ar e created will not contain formatting data. To use Import-PSSession, the execution policy in the current session ca nnot be Restricted or AllSigned, because the module that Import-PSSessi on creates contains unsigned script files that are prohibited by these policies. To use Import-PSSession without changing the execution policy for the local computer, use the Scope parameter of Set-ExecutionPolicy to set a less restrictive execution policy for a single process. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$s = new-pssession -computername Server01 C:\PS> import-pssession -session $s Description ----------- This command imports all commands from a PSSession on the Server01 computer into the current session, except for commands that have the same names as commands in the current session. Because this command does not use the CommandName parameter, it also import s all of the formatting data required for the imported commands. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$s = new-pssession https://ps.testlabs.com/powershell C:\PS> import-pssession -session $s -commandname *-test -formatTypeName * C:\PS> new-test -name test1 C:\PS> get-test test1 | run-test Description ----------- These commands import the commands with names that end in "-test" from a PS Session into the local session, and then they show how to use an imported c mdlet. The first command uses the New-PSSession cmdlet to create a PSSession. It s aves the PSSession in the $s variable. The second command uses the Import-PSSession cmdlet to import commands from the PSSession in $s into the current session. It uses the CommandName para meter to specify commands with the Test noun and the FormatTypeName paramet er to import the formatting data for the Test commands. The third and fourth commands use the imported commands in the current sess ion. Because imported commands are actually added to the current session, y ou use the local syntax to run them. You do not need to use the Invoke-Comm and cmdlet to run an imported command. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$s1 = new-pssession -computername s1 C:\PS> $s2 = new-pssession -computername s2 C:\PS> import-pssession -session s1 -type cmdlet -name New-Test, Get-Test - FormatTypeName * C:\PS> import-pssession -session s2 -type cmdlet -name Set-Test -FormatType Name * C:\PS> new-test Test1 | set-test -runtype full Description ----------- This example shows that you can use imported cmdlets just as you would use local cmdlets. These commands import the New-Test and Get-Test cmdlets from a PSSession on the Server01 computer and the Set-Test cmdlet from a PSSession on the Serv er02 computer. Even though the cmdlets were imported from different PSSessions, you can pi pe an object from one cmdlet to another without error. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$s = new-pssession -computername Server01 C:\PS> import-pssession -session $s -commandname *-test* -formattypename * C:\PS> $batch = new-test -name Batch -asjob C:\PS> receive-job $batch Description ----------- This example shows how to run an imported command as a background job. Because imported commands might take longer to run than local commands, Imp ort-PSSession adds an AsJob parameter to every imported command. The AsJob parameter lets you run the command as a background job. The first command creates a PSSession on the Server01 computer and saves th e PSSession object in the $s variable. The second command uses Import-PSSession to import the Test cmdlets from th e PSSession in $s into the current session. The third command uses the AsJob parameter of the imported New-Test cmdlet to run a New-Test command as a background job. The command saves the job ob ject that New-Test returns in the $batch variable. The fourth command uses the Receive-Job cmdlet to get the results of the jo b in the $batch variable. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$s = new-pssession -comp Server01 C:\PS> invoke-command -session $s {import-module TestManagement} C:\PS> import-pssession -session $s -module TestManagement Description ----------- This example shows how to import the cmdlets and functions from a Windows P owerShell module on a remote computer into the current session. The first command creates a PSSession on the Server01 computer and saves it in the $s variable. The second command uses the Invoke-Command cmdlet to run an Import-Module c ommand in the PSSession in $s. Typically, the module would be added to all sessions by an Import-Module co mmand in a Windows PowerShell profile, but profiles are not run in PSSessio ns. The third command uses the Module parameter of Import-PSSession to import t he cmdlets and functions in the module into the current session. -------------------------- EXAMPLE 6 -------------------------- C:\PS>import-pssession $s -CommandName Get-Date, SearchHelp -formatTypeNam e * -AllowClobber Name : tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1zunz.ttf Path : C:\Users\User01\AppData\Local\Temp\tmp_79468106-4e1d-4d 90-af97-1154f9317239_tcw1zunz.ttf\tmp_79468106-4e1d-4d90-af97-1154f9317239_ tcw1zunz.ttf.psm1 Description : Implicit remoting for http://server01.corp.fabrikam.com /wsman Guid : 79468106-4e1d-4d90-af97-1154f9317239 Version : 1.0 ModuleBase : C:\Users\User01\AppData\Local\Temp\tmp_79468106-4e1d-4d 90-af97-1154f9317239_tcw1zunz.ttf ModuleType : Script PrivateData : {ImplicitRemoting} AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {[Get-Date, Get-Date], [SearchHelp, SearchHelp]} ExportedVariables : {} NestedModules : {} Description ----------- This example shows that Import-PSSession creates a module in a temporary fi le on disk. It also shows that all commands are converted into functions be fore they are imported into the current session. The command uses the Import-PSSession cmdlet to import a Get-Date cmdlet an d a SearchHelp function into the current session. The Import-PSSession cmdlet returns a PSModuleInfo object that represents t he temporary module. The value of the Path property shows that Import-PSSes sion created a script module (.psm1) file in a temporary location. The Expo rtedFunctions property shows that the Get-Date cmdlet and the SearchHelp fu nction were both imported as functions. -------------------------- EXAMPLE 7 -------------------------- C:\PS>import-pssession $s -CommandName Get-Date -formatTypeName * -AllowClo bber C:\PS> get-command get-date CommandType Name Definition ----------- ---- ---------- Function Get-Date ... Cmdlet Get-Date Get-Date [[-Date] <DateTime>] [-Year <Int32>] [-Mo nth <Int32>] C:\PS> Get-Date 09074 C:\PS> (get-command -type cmdlet -name get-date).pssnapin.name Microsoft.PowerShell.Utility C:\PS> Microsoft.PowerShell.Utility\get-date Sunday, March 15, 2009 2:08:26 PM Description ----------- This example shows how to run a command that is hidden by an imported comma nd. The first command imports a Get-Date cmdlet from the PSSession in the $s va riable. Because the current session includes a Get-Date cmdlet, the AllowCl obber parameter is required in the command. The second command uses the Get-Command cmdlet to get the Get-Date commands in the current session. The output shows that the session includes the ori ginal Get-Date cmdlet and a Get-Date function. The Get-Date function runs t he imported Get-Date cmdlet in the PSSession in $s. The third command runs a Get-Date command. Because functions take precedenc e over cmdlets, Windows PowerShell runs the imported Get-Date function, whi ch returns a Julian date. The fourth and fifth commands show how to use a qualified name to run a com mand that is hidden by an imported command. The fourth command gets the name of the Windows PowerShell snap-in that add ed the original Get-Date cmdlet to the current session. The fifth command uses the snap-in-qualified name of the Get-Date cmdlet to run a Get-Date command. For more information about command precedence and hidden commands, see abou t_Command_Precedence. -------------------------- EXAMPLE 8 -------------------------- C:\PS>import-pssession -session $s -commandName *Item* -AllowClobber Description ----------- This command imports commands whose names include "Item" from the PSSession in $s. Because the command includes the CommandName parameter but not the FormatTypeData parameter, only the command is imported. Use this command when you are using Import-PSSession to run a command on a remote computer and you already have the formatting data for the command in the current session. -------------------------- EXAMPLE 9 -------------------------- C:\PS>$m = import-pssession -session $s -CommandName *bits* -formattypename *bits* C:\PS> get-command -module $m CommandType Name ----------- ---- Function Add-BitsFile Function Complete-BitsTransfer Function Get-BitsTransfer Function Remove-BitsTransfer Function Resume-BitsTransfer Function Set-BitsTransfer Function Start-BitsTransfer Function Suspend-BitsTransfer Description ----------- This command shows how to use the Module parameter of Get-Command to find o ut which commands were imported into the session by an Import-PSSession com mand. The first command uses the Import-PSSession cmdlet to import commands whose names include "bits" from the PSSession in the $s variable. The Import-PSS ession command returns a temporary module, and the command saves the module in the $m variable. The second command uses the Get-Command cmdlet to get the commands that are exported by the module in the $m variable. The Module parameter takes a string value, which is designed for the module name. However, when you submit a module object, Windows PowerShell uses th e ToString method on the module object, which returns the module name. The Get-Command command is the equivalent of "get-command $m.name". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135221 about_Command_Precedence New-PSSession Export-PSSession about_Jobs about_PSSessions ImportSystemModules ImportSystemModules Invoke-Command NAME Invoke-Command SYNOPSIS Runs commands on local and remote computers. SYNTAX Invoke-Command [-ScriptBlock] <scriptblock> [[-ComputerName] <string[]>] [- ApplicationName <string>] [-AsJob] [-Authentication {Default | Basic | Nego tiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-C ertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential PSCredential>] [-HideComputerName] [-JobName <string>] [-Port <int>] [-Sess ionOption <PSSessionOption>] [-ThrottleLimit <int>] [-UseSSL] [-ArgumentLis t <Object[]>] [-InputObject <psobject>] [<CommonParameters>] Invoke-Command [-FilePath] <string> [[-ComputerName] <string[]>] [-Applicat ionName <string>] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-Configura tionName <string>] [-Credential <PSCredential>] [-HideComputerName] [-JobNa me <string>] [-Port <int>] [-SessionOption <PSSessionOption>] [-ThrottleLim it <int>] [-UseSSL] [-ArgumentList <Object[]>] [-InputObject <psobject>] [ CommonParameters>] Invoke-Command [-FilePath] <string> [[-Session] <PSSession[]>] [-AsJob] [-H ideComputerName] [-JobName <string>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>] Invoke-Command [-FilePath] <string> [[-ConnectionURI] <Uri[]>] [-AllowRedir ection] [-AsJob] [-Authentication {Default | Basic | Negotiate | NegotiateW ithImplicitCredential | Credssp | Digest | Kerberos}] [-ConfigurationName string>] [-Credential <PSCredential>] [-HideComputerName] [-JobName <string >] [-SessionOption <PSSessionOption>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobject>] [<CommonParameters>] Invoke-Command [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-In putObject <psobject>] [<CommonParameters>] Invoke-Command [-ScriptBlock] <scriptblock> [[-Session] <PSSession[]>] [-As Job] [-HideComputerName] [-JobName <string>] [-ThrottleLimit <int>] [-Argum entList <Object[]>] [-InputObject <psobject>] [<CommonParameters>] Invoke-Command [-ScriptBlock] <scriptblock> [[-ConnectionURI] <Uri[]>] [-Al lowRedirection] [-AsJob] [-Authentication {Default | Basic | Negotiate | Ne gotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-Certificate Thumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredenti al>] [-HideComputerName] [-JobName <string>] [-SessionOption <PSSessionOpti on>] [-ThrottleLimit <int>] [-ArgumentList <Object[]>] [-InputObject <psobj ect>] [<CommonParameters>] DESCRIPTION The Invoke-Command cmdlet runs commands on a local or remote computer and r eturns all output from the commands, including errors. With a single Invoke -Command command, you can run commands on multiple computers. To run a single command on a remote computer, use the ComputerName paramete r. To run a series of related commands that share data, create a PSSession (a persistent connection) on the remote computer, and then use the Session parameter of Invoke-Command to run the command in the PSSession. You can also use Invoke-Command on a local computer to evaluate or run a st ring in a script block as a command. Windows PowerShell converts the script block to a command and runs the command immediately in the current scope, instead of just echoing the string at the command line. Before using Invoke-Command to run commands on a remote computer, read abou t_Remote. PARAMETERS -AllowRedirection [<SwitchParameter>] Allows redirection of this connection to an alternate URI. When you use the ConnectionURI parameter, the remote destination can re turn an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use the AllowRed irection parameter to allow it to redirect the connection. You can also limit the number of times that the connection is redirecte d by setting the MaximumConnectionRedirectionCount property of the $PSS essionOption preference variable, or the MaximumConnectionRedirectionCo unt property of the value of the SessionOption parameter. The default v alue is 5. For more information, see the description of the SessionOpti on parameter and the help topic for the New-PSSessionOption cmdlet. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ApplicationName <string> Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the Co nnectionURI parameter in the command. The default value is the value of the $PSSessionApplicationName prefere nce variable on the local computer. If this preference variable is not defined, the default value is WSMAN. This value is appropriate for most uses. For more information, see about_Preference_Variables. The WinRM service uses the application name to select a listener to ser vice the connection request. The value of this parameter should match t he value of the URLPrefix property of a listener on the remote computer . Required? false Position? named Default value WSMAN Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -ArgumentList <Object[]> Supplies the values of local variables in the command. The variables in the command are replaced by these values before the command is run on the remote computer. Enter the values in a comma-separated list. Values are associated with variables in the order that they are listed. The a lias for ArgumentList is "Args". The values in ArgumentList can be actual values, such as "1024", or the y can be references to local variables, such as "$max". To use local variables in a command, use the following command format: {param($<name1>[, $<name2>]...) <command-with-local-variables>} -Argume ntList <value | $local-variable> The "param" keyword lists the local variables that are used in the comm and. The ArgumentList parameter supplies the values of the variables, i n the order that they are listed. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -AsJob [<SwitchParameter>] Runs the command as a background job on a remote computer. Use this par ameter to run commands that take an extensive time to complete. When you use AsJob, the command returns an object that represents the j ob, and then displays the command prompt. You can continue to work in t he session while the job completes. To manage the job, use the Job cmd lets. To get the job results, use Receive-Job. The AsJob parameter is similar to using Invoke-Command to run a Start-J ob command remotely. However, with AsJob, the job is created on the loc al computer, even though the job runs on a remote computer, and the res ults of the remote job are automatically returned to the local computer . For more information about Windows PowerShell background jobs, see abou t_Jobs and about_Remote_Jobs. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationMechanism> Specifies the mechanism that is used to authenticate the user's credent ials. Valid values are Default, Basic, Credssp, Digest, Kerberos, Neg otiate, and NegotiateWithImplicitCredential. The default value is Defa ult. CredSSP authentication is available only in Windows Vista, Windows Serv er 2008, and later versions of Windows. For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in MSDN. CAUTION: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the r emote computer is compromised, the credentials that are passed to it ca n be used to control the network session. Required? false Position? named Default value Default Accept pipeline input? false Accept wildcard characters? false -CertificateThumbprint <string> Specifies the digital public key certificate (X509) of a user account t hat has permission to perform this action. Enter the certificate thumbp rint of the certificate. Certificates are used in client certificate-based authentication. They can only be mapped to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the Get-Item or Get-ChildItem comm ands in the Windows PowerShell Cert: drive. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Specifies the computers on which the command runs. The default is the l ocal computer. When you use the ComputerName parameter, Windows PowerShell creates a t emporary connection that is used only to run the specified command and is then closed. If you need a persistent connection, use the Session pa rameter. Type the NETBIOS name, IP address, or fully-qualified domain name of on e or more computers in a comma-separated list. To specify the local com puter, type the computer name, "localhost", or a dot (.). To use an IP address in the value of the ComputerName parameter, the co mmand must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote compute r must be included in the WinRM TrustedHosts list on the local computer . For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_ Troubleshooting. Note: On Windows Vista, and later versions of Windows, to include the local computer in the value of the ComputerName parameter, you must ope n Windows PowerShell with the "Run as administrator" option. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -ConfigurationName <string> Specifies the session configuration that is used for the new PSSession. Enter a configuration name or the fully qualified resource URI for a se ssion configuration. If you specify only the configuration name, the fo llowing schema URI is prepended: http://schemas.microsoft.com/powershe ll. The session configuration for a session is located on the remote comput er. If the specified session configuration does not exist on the remote computer, the command fails. The default value is the value of the $PSSessionConfigurationName prefe rence variable on the local computer. If this preference variable is no t set, the default is Microsoft.PowerShell. For more information, see a bout_preference_variables. Required? false Position? named Default value http://Schemas.Microsoft.com/PowerShell/Mi crosoft.PowerShell Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -ConnectionURI <Uri[]> Specifies a Uniform Resource Identifier (URI) that defines the connecti on endpoint. The URI must be fully qualified. The format of this string is: <Transport>://<ComputerName>:<Port>/ The default value is: http://localhost:80/WSMAN Valid values for the Transport segment of the URI are HTTP and HTTPS. I f you do not specify a ConnectionURI, you can use the UseSSL, ComputerN ame, Port, and ApplicationName parameters to specify the URI values. If the destination computer redirects the connection to a different URI , Windows PowerShell prevents the redirection unless you use the AllowR edirection parameter in the command. Required? false Position? 1 Default value http://localhost:80/wsman Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a var iable that contains a PSCredential object, such as one generated by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -FilePath <string> Runs the specified local script on one or more remote computers. Enter the path and file name of the script, or pipe a script path to Invoke-C ommand. The script must reside on the local computer or in a directory that the local computer can access. Use the ArgumentList parameter to s pecify the values of parameters in the script. When you use this parameter, Windows PowerShell converts the contents o f the specified script file to a script block, transmits the script blo ck to the remote computer, and runs it on the remote computer. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -HideComputerName [<SwitchParameter>] Omits the computer name of each object from the output display. By defa ult, the name of the computer that generated the object appears in the display. This parameter affects only the output display. It does not change the object. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies input to the command. Enter a variable that contains the obje cts or type a command or expression that gets the objects. When using InputObject, use the $input automatic variable in the value of the ScriptBlock parameter to represent the input objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -JobName <string> Specifies a friendly name for the background job. By default, jobs are named "Job<n>", where <n> is an ordinal number. This parameter is vali d only with the AsJob parameter. If you use the JobName parameter in a command, the command is run as a job, and Invoke-Command returns a job object, even if you do not includ e the AsJob parameter in the command. For more information about Windows PowerShell background jobs, see abou t_Jobs. Required? false Position? named Default value Job<n> Accept pipeline input? false Accept wildcard characters? false -Port <int> Specifies the network port on the remote computer used for this comman d. The default is port 80 (the HTTP port). Before using an alternate port, you must configure the WinRM listener o n the remote computer to listen at that port. To configure the listener , type the following two commands at the Windows PowerShell prompt: remove-item -path wsman:\Localhost\listener\listener* -recurse new-item -path wsman:\Localhost\listener -Transport http -Address * -po rt <port-number> Do not use the Port parameter unless you must. The Port set in the comm and applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all co mputers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ScriptBlock <scriptblock> Specifies the commands to run. Enclose the commands in curly braces ( { } ) to create a script block. This parameter is required. By default, any variables in the command are evaluated on the remote co mputer. To include local variables in the command, use the ArgumentList parameter. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Session <PSSession[]> Runs the command in the specified Windows PowerShell sessions (PSSessio ns). Enter a variable that contains the PSSessions or a command that cr eates or gets the PSSessions, such as a New-PSSession or Get-PSSession command. When you create a PSSession, Windows PowerShell establishes a persisten t connection to the remote computer. Use a PSSession to run a series of related commands that share data. To run a single command or a series of unrelated commands, use the ComputerName parameter. To create a PSSession, use the New-PSSession cmdlet. For more informati on, see about_PSSessions. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -SessionOption <PSSessionOption> Sets advanced options for the session. Enter a SessionOption object tha t you create by using the New-PSSessionOption cmdlet. The default values for the options are determined by the value of the $ PSSessionOption preference variable, if it is set. Otherwise, the sessi on uses the system defaults. For a description of the session options, including the default values, see the help topic for the New-PSSessionOption cmdlet. For information about the $PSSessionOption preference variable, see about_Preference_V ariables. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Specifies the maximum number of concurrent connections that can be esta blished to run this command. If you omit this parameter or enter a valu e of 0, the default value, 32, is used. The throttle limit applies only to the current command, not to the sess ion or to the computer. Required? false Position? named Default value 32 Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all Windows PowerShell content transmitted over the network. UseSSL is an additional protection that sends the data acr oss an HTTPS, instead of HTTP. If you use this parameter, but SSL is not available on the port used fo r the command, the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.ScriptBlock You can pipe a command in a script block to Invoke-Command. Use the $in put automatic variable to represent the input objects in the command. OUTPUTS System.Management.Automation.PSRemotingJob or the output of the invoked com mand When you use the AsJob parameter, Invoke-Command returns a job object. Otherwise, it returns the output of the invoked command (the value of t he ScriptBlock parameter). NOTES -- On Windows Vista, and later versions of Windows, to use the Computer Name parameter of Invoke-Command to run a command on the local computer , you must open Windows PowerShell with the "Run as administrator" opti on. -- When you run commands on multiple computers, Windows PowerShell conn ects to the computers in the order in which they appear in the list. Ho wever, the command output is displayed in the order that it is received from the remote computers, which might be different. -- Errors that result from the command that Invoke-Command runs are inc luded in the command results. Errors that would be terminating errors i n a local command are treated as non-terminating errors in a remote com mand. This strategy ensures that terminating errors on one computer do not terminate the command on all computers on which it is run. This pra ctice is used even when a remote command is run on a single computer. -- If the remote computer is not in a domain that the local computer tr usts, the computer might not be able to authenticate the user's credent ials. To add the remote computer to the list of "trusted hosts" in WS-M anagement, use the following command in the WSMAN provider, where <Remo te-Computer-Name> is the name of the remote computer: set-item -path wsman:\Localhost\Client\TrustedHosts -value <Remote-Comp uter-Name>. -------------------------- EXAMPLE 1 -------------------------- C:\PS>invoke-command -filepath c:\scripts\test.ps1 -computerName Server01 Disks: C:, D:, E: Status: Warning, Normal, Normal Description ----------- This command runs the Test.ps1 script on the Server01 computer. The command uses the FilePath parameter to specify a script that is located on the local computer. The script runs on the remote computer and the resu lts are returned to the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>invoke-command -computername server01 -credential domain01\user01 -sc riptblock {get-culture} Description ----------- This command runs a Get-Culture command on the Server01 remote computer. It uses the ComputerName parameter to specify the computer name and the Cre dential parameter to run the command in the security context of "Domain01\U ser01," a user with permission to run commands. It uses the ScriptBlock par ameter to specify the command to be run on the remote computer. In response, Windows PowerShell displays a dialog box that requests the pas sword and an authentication method for the User01 account. It then runs the command on the Server01 computer and returns the result. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$s = new-pssession -computername server02 -credential domain01\user01 C:\PS> invoke-command -session $s -scriptblock {get-culture} Description ----------- This example runs the same "Get-Culture" command in a session (a persistent connection) on the Server02 remote computer. Typically, you create a sessi on only when you are running a series of commands on the remote computer. The first command uses the New-PSSession cmdlet to create a session on the Server02 remote computer. Then, it saves the session in the $s variable. The second command uses the Invoke-Command cmdlet to run the Get-Culture co mmand on Server02. It uses the Session parameter to specify the session sa ved in the $s variable. In response, Windows PowerShell runs the command in the session on the Serv er02 computer. -------------------------- EXAMPLE 4 -------------------------- C:\PS>invoke-command -computername Server02 -scriptblock {$p = get-process powershell} C:\PS> invoke-command -computername Server02 -scriptblock {$p.virtualmemory size} C:\PS> C:\PS> $s = new-pssession -computername Server02 C:\PS> invoke-command -session $s -scriptblock {$p = get-process powershell } C:\PS> invoke-command -session $s -scriptblock {$p.virtualmemorysize} 17930240 Description ----------- This example compares the effects of using ComputerName and Session paramet ers of Invoke-Command. It shows how to use a session to run a series of com mands that share the same data. The first two commands use the ComputerName parameter of Invoke-Command to run commands on the Server02 remote computer. The first command uses the Ge t-Process command to get the PowerShell process on the remote computer and to save it in the $p variable. The second command gets the value of the Vir tualMemorySize property of the PowerShell process. The first command succeeds. But, the second command fails because when you use the ComputerName parameter, Windows PowerShell creates a connection jus t to run the command. Then, it closes the connection when the command is co mplete. The $p variable was created in one connection, but it does not exis t in the connection created for the second command. The problem is solved by creating a session (a persistent connection) on th e remote computer and by running both of the related commands in the same s ession. The third command uses the New-PSSession cmdlet to create a session on the Server02 computer. Then it saves the session in the $s variable. The fourth and fifth commands repeat the series of commands used in the first set, bu t in this case, the Invoke-Command command uses the Session parameter to ru n both of the commands in the same session. In this case, because both commands run in the same session, the commands s ucceed, and the $p value remains active in the $s session for later use. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$command = { get-eventlog -log "windows powershell" | where {$_.messa ge -like "*certificate*"} } C:\PS> invoke-command -computername S1, S2 -scriptblock $command Description ----------- This example shows how to enter a command that is saved in a local variable . When the entire command is saved in a local variable, you can specify the v ariable as the value of the ScriptBlock parameter. You do not have to use t he "param" keyword or the ArgumentList variable to submit the value of the local variable. The first command saves a Get-Eventlog command in the $command variable. Th e command is formatted as a script block. The second command uses the Invoke-Command cmdlet to run the command in $co mmand on the S1 and S2 remote computers. -------------------------- EXAMPLE 6 -------------------------- C:\PS>invoke-command -computername server01, server02, TST-0143, localhost -configurationname MySession.PowerShell -scriptblock {get-eventlog "windows powershell"} Description ----------- This example demonstrates how to use the Invoke-Command cmdlet to run a sin gle command on multiple computers. The command uses the ComputerName parameter to specify the computers. The c omputer names are presented in a comma-separated list. The list of computer s includes the "localhost" value, which represents the local computer. The command uses the ConfigurationName parameter to specify an alternate se ssion configuration for Windows PowerShell and the ScriptBlock parameter to specify the command. In this example, the command in the script block gets the events in the Win dows PowerShell event log on each remote computer. -------------------------- EXAMPLE 7 -------------------------- C:\PS>$version = invoke-command -computername (get-content machines.txt) -s criptblock {(get-host).version} Description ----------- This command gets the version of the Windows PowerShell host running on 200 remote computers. Because only one command is run, it is not necessary to create persistent c onnections (sessions) to each of the computers. Instead, the command uses t he ComputerName parameter to indicate the computers. The command uses the Invoke-Command cmdlet to run a Get-Host command. It us es dot notation to get the Version property of the Windows PowerShell host. To specify the computers, it uses the Get-Content cmdlet to get the content s of the Machine.txt file, a file of computer names. These commands run synchronously (one at a time). When the commands complet e, the output of the commands from all of the computers is saved in the $ve rsion variable. The output includes the name of the computer from which the data originated. -------------------------- EXAMPLE 8 -------------------------- C:\PS>$s = new-pssession -computername Server01, Server02 C:\PS> invoke-command -session $s -scriptblock {get-eventlog system} -AsJob Id Name State HasMoreData Location Command --- ---- ----- ----- ----------- -------- ------- 1 Job1 Running True Server01,Server02 get-eventlog syste m C:\PS> $j = Get-Job C:\PS> $j | format-list -property * HasMoreData : True StatusMessage : Location : Server01,Server02 Command : get-eventlog system JobStateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : e124bb59-8cb2-498b-a0d2-2e07d4e030ca Id : 1 Name : Job1 ChildJobs : {Job2, Job3} Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} StateChanged : C:\PS> $results = $j | Receive-Job Description ----------- These commands run a background job on two remote computers. Because the In voke-Command command uses the AsJob parameter, the commands run on the remo te computers, but the job actually resides on the local computer and the re sults are transmitted to the local computer. The first command uses the New-PSSession cmdlet to create sessions on the S erver01 and Server02 remote computers. The second command uses the Invoke-Command cmdlet to run a background job i n each of the sessions. The command uses the AsJob parameter to run the com mand as a background job. This command returns a job object that contains t wo child job objects, one for each of the jobs run on the two remote comput ers. The third command uses a Get-Job command to save the job object in the $j v ariable. The fourth command uses a pipeline operator (|) to send the value of the $j variable to the Format-List cmdlet, which displays all properties of the j ob object in a list. The fifth command gets the results of the jobs. It pipes the job object in $j to the Receive-Job cmdlet and stores the results in the $results variabl e. -------------------------- EXAMPLE 9 -------------------------- C:\PS>$MWFO-LOg = Microsoft-Windows-Forwarding/Operational C:\PS> invoke-command -computername server01 -scriptblock {param($log, $num ) get-eventlog -logname $log -newest $num} -ArgumentList $MWFO-log, 10 Description ----------- This example shows how to include the values of local variables in a comman d run on a remote computer. The first command saves the name of the Microsoft-Windows-Forwarding/Operat ional event log in the $MWFO-Log variable. The second command uses the Invoke-Command cmdlet to run a Get-EventLog com mand on the Server01 remote computer that gets the 10 newest events from th e Microsoft-Windows-Forwarding/Operational event log on Server01. This command uses the "param" keyword to create two variables, $log and $nu m, that are used as placeholders in the Get-EventLog command. These placeho lders have arbitrary names that do not need to match the names of the local variables that supply their values. The values of the ArgumentList parameter demonstrate the two different ways to specify values in the argument list. The value of the $log placeholder is the $MFWO-Log variable, which is defined in the first command. The value of the $num variable is 10. Before the command is sent to the remote computer, the variables are replac ed with the specified values. -------------------------- EXAMPLE 10 -------------------------- C:\PS>invoke-command -computername S1, S2 -scriptblock {get-process powersh ell} PSComputerName Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName -------------- ------- ------ ----- ----- ----- ------ -- ----------- S1 575 15 45100 40988 200 4.68 13 92 powershell S2 777 14 35100 30988 150 3.68 67 powershell C:\PS> invoke-command -computername S1, S2 -scriptblock {get-process powers hell} -HideComputerName Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 575 15 45100 40988 200 4.68 1392 powershell 777 14 35100 30988 150 3.68 67 powershell Description ----------- This example shows the effect of using the HideComputerName parameter of In voke-Command. The first two commands use the Invoke-Command cmdlet to run a Get-Process c ommand for the PowerShell process. The output of the first command includes the PsComputerName property, which contains the name of the computer on wh ich the command ran. The output of the second command, which uses the HideC omputerName parameter, does not include the PsComputerName column. Using the HideComputerName parameter does not change the object. You can st ill use the Format cmdlets to display the PsComputerName property of any of the affected objects. -------------------------- EXAMPLE 11 -------------------------- C:\PS>invoke-command -comp (get-content servers.txt) -filepath c:\scripts\s ample.ps1 -argumentlist Process, Service Description ----------- This example uses the Invoke-Command cmdlet to run the Sample.ps1 script on all of the computers listed in the Servers.txt file. The command uses the FilePath parameter to specify the script file. This command allows you to r un the script on the remote computers, even if the script file is not acces sible to the remote computers. When you submit the command, the content of the Sample.ps1 file is copied i nto a script block and the script block is run on each of the remote comput ers. This procedure is equivalent to using the ScriptBlock parameter to sub mit the contents of the script. -------------------------- EXAMPLE 12 -------------------------- C:\PS>$LiveCred = Get-Credential C:\PS> Invoke-Command -ConfigurationName Microsoft.Exchange ` -ConnectionUri https://ps.exchangelabs.com/powershell ` -Credential $LiveCred -Authentication Basic ` -scriptblock {Invoke-Command {Set-Mailbox dan -DisplayName "Dan Pa rk"} Description ----------- This example shows how to run a command on a remote computer that is identi fied by a URI (Internet address). This particular example runs a Set-Mailbo x command on a remote Exchange server. The backtick (`) in the command is t he Windows PowerShell continuation character. The first command uses the Get-Credential cmdlet to store Windows Live ID c redentials in the $LiveCred variab the credentials dialog box appears, ente r Windows Live ID credentials. The second command uses the Invoke-Command cmdlet to run a Set-Mailbox comm and. The command uses the ConfigurationName parameter to specify that the c ommand should run in a session that uses the Microsoft.Exchange session con figuration. The ConnectionURI parameter specifies the URL of the Exchange s erver endpoint. The credential parameter specifies tle. Whenhe Windows Live credentials sto red in the $LiveCred variable. The AuthenticationMechanism parameter specif ies the use of basic authentication. The ScriptBlock parameter specifies a script block that contains the command. -------------------------- EXAMPLE 13 -------------------------- C:\PS>$max = New-PSSessionOption -MaximumRedirection 1 C:\PS> Invoke-Command -ConnectionUri https://ps.exchangelabs.com/powershell ` -scriptblock {Invoke-Command {Get-Mailbox dan} ` -AllowRedirection -SessionOption $max Description ----------- This command shows how to use the AllowRedirection and SessionOption parame ters to manage URI redirection in a remote command. The first command uses the New-PSSessionOption cmdlet to create a PSSession Opption object that it saves in the $max variable. The command uses the Max imumRedirection parameter to set the MaximumConnectionRedirectionCount prop erty of the PSSessionOption object to 1. The second command uses the Invoke-Command cmdlet to run a Get-Mailbox comm and on a remote server running Microsoft Exchange Server. The command uses the AllowRedirection parameter to provide explicit permission to redirect t he connection to an alternate endpoint. It also uses the SessionOption para meter to specify the session object in the $max variable. As a result, if the remote computer specified by the ConnectionURI paramete r returns a redirection message, Windows PowerShell will redirect the conne ction, but if the new destination returns another redirection message, the redirection count value of 1 is exceeded, and Invoke-Command returns a non- terminating error. -------------------------- EXAMPLE 14 -------------------------- C:\PS>$so = New-PSSessionOption -SkipCACheck PS C:\> invoke-command $s { get-hotfix } -SessionOption $so -credential ser ver01\user01 Description ----------- This example shows how to create and use a SessionOption parameter. The first command uses the New-PSSessionOption cmdlet to create a session o ption. It saves the resulting SessionOption object in the $so parameter. The second command uses the Invoke-Command cmdlet to run a Get-Hotfix comma nd remotely. The value of the SessionOption parameter is the SessionOption object in the $so variable. -------------------------- EXAMPLE 15 -------------------------- C:\PS>enable-wsmanCredSSP -delegate server02 C:\PS> connect-wsman Server02 C:\PS> set-item wsman:\server02*\service\auth\credSSP -value $true C:\PS> $s = new-pssession server02 C:\PS> invoke-command -session $s -script {get-item \\Net03\Scripts\LogFile s.ps1} -authentication credssp -credential domain01\admin01 Description ----------- This example shows how to access a network share from within a remote sessi on. The command requires that CredSSP delegation be enabled in the client setti ngs on the local computer and in the service settings on the remote compute r. To run the commands in this example, you must be a member of the Adminis trators group on the local computer and the remote computer. The first command uses the Enable-WSManCredSSP cmdlet to enable CredSSP del egation from the Server01 local computer to the Server02 remote computer. T his configures the CredSSP client setting on the local computer. The second command uses the Connect-WSman cmdlet to connect to the Server02 computer. This action adds a node for the Server02 computer to the WSMan: drive on the local computer, allowing you to view and change the WS-Managem ent settings on the Server02 computer. The third command uses the Set-Item cmdlet to change the value of the CredS SP item in the Service node of the Server02 computer to True. This action e nables CredSSP in the service settings on the remote computer. The fourth command uses the New-PSSession cmdlet to create a PSSession on t he Server02 computer. It saves the PSSession in the $s variable. The fifth command uses the Invoke-Command cmdlet to run a Get-Item command in the session in $s that gets a script from the Net03\Scripts network shar e. The command uses the Credential parameter and it uses the Authentication parameter with a value of CredSSP. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135225 about_Remote about_PSSessions New-PSSession Get-PSSession Remove-PSSession Enter-PSSession Exit-PSSession WS-Management Provider Invoke-Expression NAME Invoke-Expression SYNOPSIS Runs commands or expressions on the local computer. SYNTAX Invoke-Expression [-Command] <string> [<CommonParameters>] DESCRIPTION The Invoke-Expression cmdlet evaluates or runs a specified string as a comm and and returns the results of the expression or command. Without Invoke-Ex pression, a string submitted at the command line would be returned (echoed) unchanged. PARAMETERS -Command <string> Specifies the command or expression to run. Type the command or express ion or enter a variable that contains the command or expression. The Co mmand parameter is required. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String or PSObject You can pipe an object that represents the command to Invoke-Expression . Use the $input automatic variable to represent the input objects in t he command. OUTPUTS PSObject Returns the output that is generated by the invoked command (the value of the Command parameter). NOTES -- An expression is a statement that can be evaluated and produces a re sult, such as a Windows PowerShell command. -- Take reasonable precautions when using the Invoke-Expression cmdlet in scripts. When using Invoke-Expression to run a command that the user enters, verify that the command is safe to run before running it. In g eneral, it is best to design your script with predefined input options, rather than allowing freeform input. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$command = "Get-Process" C:\PS> $command Get-Process C:\PS> invoke-expression $command Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 296 4 1572 1956 20 0.53 1348 AdtAgent 270 6 1328 800 34 0.06 2396 alg 67 2 620 484 20 0.22 716 ati2evxx 1060 15 12904 11840 74 11.48 892 CcmExec 1400 33 25280 37544 223 38.44 2564 communicator ... Description ----------- This example demonstrates the use of Invoke-Expression to evaluate an expre ssion. Without Invoke-Expression, the expression is printed, but not evalua ted. The first command assigns a value of "Get-Process" (a string) to the $comma nd variable. The second command shows the effect of typing the variable name at the comm and line. Windows PowerShell echoes the string. The third command uses Invoke-Expression to evaluate the string. -------------------------- EXAMPLE 2 -------------------------- C:\PS>invoke-expression -command "C:\ps-test\testscript.ps1" C:\PS> "C:\ps-test\testscript.ps1" | invoke-expression Description ----------- These commands use Invoke-Expression to run a script, TestScript.ps1, on th e local computer. The two commands are equivalent. The first uses the Comma nd parameter to specify the command to run. The second uses a pipeline oper ator (|) to send the command string to Invoke-Expression. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$cmd = 'get-process | where {$_.cpu -gt 1000}' C:\PS> iex $command Description ----------- This example runs a command string that is saved in the $cmd variable. The command string is enclosed in single quotation marks because it include s a variable, $_, which represents the current object. If it were enclosed in double quotation marks, the $_ variable would be replaced by its value b efore it was saved in the $command string. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$cmdlet_name = "get-eventlog" C:\PS> $example_number = 1 C:\PS> $example_code = (get-help $cmdlet_name).examples.example[($example_n umber-1)].code C:\PS> invoke-expression $example_code Description ----------- This command retrieves and runs the first example in the Get-EventLog cmdle t help topic. To run an example of a different cmdlet, change the value of the $cmdlet_na me variable to the name of the cmdlet. And, change the $example_number vari able to the example number you want to run. The command will fail if the ex ample number is not valid. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113343 Invoke-Command Invoke-History NAME Invoke-History SYNOPSIS Runs commands from the session history. SYNTAX Invoke-History [[-Id] <string>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Invoke-History cmdlet runs commands from the session history. You can p ass objects representing the commands from Get-History to Invoke-History, o r you can identify commands in the current history by using their ID number . To find the identification number of a command, use Get-History. PARAMETERS -Id <string> Identifies a command in the history. You can type the ID number of the command or the first few characters of the command. If you type characters, Invoke-History matches the most recent commands first. If you omit this parameter, Invoke-History runs the last (most recent) command. The parameter name ("id") is optional. To find the ID number of a command, use Get-History. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None Invoke-History does not generate any output, but output might be genera ted by the commands that Invoke-History runs. NOTES The session history is a list of the commands entered during the sessio n along with the ID. The session history represents the order of execut ion, the status, and the start and end times of the command. As you ent er each command, Windows PowerShell adds it to the history so that you can reuse it. For more information about the session history, see abou t_History. You can also refer to Invoke-History by its built-in aliases, "r" and " ihy". For more information, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>invoke-history Description ----------- This command runs the last (most recent) command in the session history. Yo u can abbreviate this command as "r" (think "repeat" or "rerun"), the alias for Invoke-History. -------------------------- EXAMPLE 2 -------------------------- C:\PS>invoke-history -id 132 Description ----------- This command runs the command in the session history with ID 132. Because t he name of the Id parameter is optional, you can abbreviate this command as "Invoke-History 132", "ihy 132", or "r 132". -------------------------- EXAMPLE 3 -------------------------- C:\PS>invoke-history get-pr Description ----------- This command runs the most recent Get-Process command in the session histor y. When you type characters for the Id parameter, Invoke-History runs the f irst command that it finds that matches the pattern, beginning with the mos t recent commands. This command uses the ID parameter, but it omits the opt ional parameter name. -------------------------- EXAMPLE 4 -------------------------- C:\PS>invoke-history (16..24), 27 Description ----------- This command runs commands 16 through 24 and 27. You can list multiple IDs and ID ranges separated by commas. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-history -id 255 -count 7 | invoke-history Description ----------- This command runs the 7 commands in the history that end with command 255 ( typically 249 through 255). It uses the Get-History cmdlet to retrieve the commands. The pipeline operator (|) passes the commands to Invoke-History, which executes them. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113344 about_History Get-History Add-History Clear-History Invoke-Item NAME Invoke-Item SYNOPSIS Performs the default action on the specified item. SYNTAX Invoke-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclud e <string[]>] [-Filter <string>] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] Invoke-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <stri ng[]>] [-Filter <string>] [-Include <string[]>] [-Confirm] [-WhatIf] [-UseT ransaction] [<CommonParameters>] DESCRIPTION The Invoke-Item cmdlet performs the default action on the specified item. F or example, it runs an executable file or opens a document file in the appl ication associated with the document file type. The default action depends on the type of item and is determined by the Windows PowerShell provider th at provides access to the data. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Performs the default action only on the specified items. The value of t his parameter qualifies the Path parameter. Enter a path element or pat tern, such as "*.txt". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the item. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Sing le quotation marks tell Windows PowerShell not to interpret any charact ers as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the path to the selected item. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Invoke-Item. OUTPUTS None The command does not generate any output. However, output might be gene rated by the item that it invokes. NOTES The Invoke-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-P sSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>invoke-item C:\Test\aliasApr04.doc Description ----------- This command opens the file aliasApr04.doc in Microsoft Office Word. In thi s case, opening in Word is the default action for .doc files. -------------------------- EXAMPLE 2 -------------------------- C:\PS>invoke-item "C:\Documents and Settings\Lister\My Documents\*.xls" Description ----------- This command opens all of the Microsoft Office Excel spreadsheets in the C: \Documents and Settings\Lister\My Documents folder. Each spreadsheet is ope ned in a new instance of Excel. In this case, opening in Excel is the defau lt action for .xls files. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113345 about_Providers Clear-Item Get-Item Move-Item Set-Item New-Item Remove-Item Rename-Item Copy-Item Invoke-WmiMethod NAME Invoke-WmiMethod SYNOPSIS Calls Windows Management Instrumentation (WMI) methods. SYNTAX Invoke-WmiMethod [-Class] <string> [[-ArgumentList] <Object[]>] [-Authentic ation {Default | None | Connect | Call | Packet | PacketIntegrity | PacketP rivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Cre dential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | A nonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespa ce <string>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [- WhatIf] [<CommonParameters>] Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Co mputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-Thrott leLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] Invoke-WmiMethod -InputObject <ManagementObject> [-ArgumentList <Object[]>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<Co mmonParameters>] Invoke-WmiMethod -Path <string> [-ArgumentList <Object[]>] [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivac y | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credenti al <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonym ous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <s tring>] [-Name] <string> [-AsJob] [-ThrottleLimit <int>] [-Confirm] [-WhatI f] [<CommonParameters>] Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Co mputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-Thrott leLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] Invoke-WmiMethod [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Co mputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-Name] <string> [-AsJob] [-Thrott leLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Invoke-WmiMethod cmdlet calls WMI methods. PARAMETERS -ArgumentList <Object[]> Specifies the parameters to pass to the called method. The value of thi s parameter must be an array of objects and they must appear in the ord er required by the called method. Important: A second value of $null is required, otherwise the command w ill generate an error, such as "Unable to cast object of type 'System.B yte' to type 'System.Array'.". An example using an array of objects ($binSD) followed by a null value ($null) follows: PS C:\> $acl = get-acl test.txt PS C:\> $binSD = $acl.GetSecurityDescriptorBinaryForm() PS C:\> invoke-wmimethod -class Win32_SecurityDescriptorHelper -Name Bi narySDToSDDL -argumentlist $binSD, $null Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -AsJob [<SwitchParameter>] Runs the command as a background job. Use this parameter to run command s that take a long time to finish. When you use the AsJob parameter, the command returns an object that re presents the background job and then displays the command prompt. You c an continue to work in the session while the job finishes. If Invoke-Wm iMethod is used against a remote computer, the job is created on the lo cal computer, and the results from remote computers are automatically r eturned to the local computer. To manage the job, use the cmdlets that contain the Job noun (the Job cmdlets). To get the job results, use the Receive-Job cmdlet. Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must star t Windows PowerShell by using the "Run as administrator" option in Wind ows Vista and later versions of Windows. For more information, see abou t_Remote_Requirements. For more information about Windows PowerShell background jobs, see abou t_Jobs and about_Remote_Jobs. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationLevel> Specifies the authentication level to be used with the WMI connection. Valid values are: -1: Unchanged 0: Default 1: None (No authentication in performed.) 2: Connect (Authentication is performed only when the client establishe s a relationship with the application.) 3: Call (Authentication is performed only at the beginning of each call when the application receives the request.) 4: Packet (Authentication is performed on all the data that is received from the client.) 5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.) 6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.) Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authority <string> Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to ntlmdomain:<DomainName>, where <DomainName> id entifies a valid NTLM domain name. To use Kerberos, specify kerberos:<D omainName\ServerName>. You cannot include the authority setting when yo u connect to the local computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Class <string> Specifies the WMI class that contains a static method to call. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an Internet Protocol (IP) address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local c omputer is the default. When the remote computer is in a different dom ain from the user, a fully qualified domain name is required. You can a lso set the value of this parameter by piping the value to the paramete r. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or User@Contoso.com. Or, enter a PSCredential object, su ch as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -EnableAllPrivileges [<SwitchParameter>] Enables all the privileges of the current user before the command makes the WMI call. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Impersonation <ImpersonationLevel> Specifies the impersonation level to use. Valid values are: 0: Default (Reads the local registry for the default impersonation leve l, which is usually set to "3: Impersonate".) 1: Anonymous (Hides the credentials of the caller.) 2: Identify (Allows objects to query the credentials of the caller.) 3: Impersonate (Allows objects to use the credentials of the caller.) 4: Delegate (Allows objects to permit other objects to use the credenti als of the caller.) Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ManagementObject> Specifies a ManagementObject object to use as input. When this paramete r is used, all other parameters except the Flag and Argument parameters are ignored. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Locale <string> Specifies the preferred locale for WMI objects. Specify the value of th e Locale parameter as an array in the MS_<LCID> format in the preferred order. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies the name of the method to be invoked. This parameter is manda tory and cannot be null or empty. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Namespace <string> When used with the Class parameter, this parameter specifies the WMI re pository namespace where the referenced WMI class or object is located. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the WMI object path of a WMI class, or specifies the WMI obje ct path of an instance of a WMI class. The class or the instance that y ou specify must contain the method that is specified in the Name parame ter. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Allows the user to specify a throttling value for the number of WMI ope rations that can be executed simultaneously. This parameter is used tog ether with the AsJob parameter. The throttle limit applies only to the current command, not to the session or to the computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>invoke-wmimethod -path win32_process -name create -argumentlist notep ad.exe __GENUS : 2 __CLASS : __PARAMETERS __SUPERCLASS : __DYNASTY : __PARAMETERS __RELPATH : __PROPERTY_COUNT : 2 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : ProcessId : 4844 ReturnValue : 0 Description ----------- This command starts an instance of Notepad by calling the Create method of the Win32_Process class. Note: The ReturnValue property is populated with a 0, and the ProcessId pro perty is populated with an integer (the next process ID number) if the comm and is completed. -------------------------- EXAMPLE 2 -------------------------- C:\PS>invoke-wmimethod -path "CIM_DataFile.Name='C:\scripts\test.txt'" -Nam e Rename -ArgumentList "C:\scripts\test_bu.txt" __GENUS : 2 __CLASS : __PARAMETERS __SUPERCLASS : __DYNASTY : __PARAMETERS __RELPATH : __PROPERTY_COUNT : 1 __DERIVATION : {} __SERVER : __NAMESPACE : __PATH : ReturnValue : 0 Description ----------- This command renames a file. It uses the Path parameter to reference an ins tance of the CIM_DataFile class. Then, it applies the Rename method to that particular instance. Note: The ReturnValue property is populated with a 0 if the command is comp leted. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113346 Get-WmiObject Remove-WmiObject Set-WmiInstance Get-WSManInstance Invoke-WSManAction New-WSManInstance Remove-WSManInstance Invoke-WSManAction NAME Invoke-WSManAction SYNOPSIS Invokes an action on the object that is specified by the Resource URI and b y the selectors. SYNTAX Invoke-WSManAction [-ApplicationName <string>] [-ComputerName <string>] [-C redential <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCred ential>] [-Credential <PSCredential>] [-Credential <PSCredential>] [-Creden tial <PSCredential>] [-Credential <PSCredential>] [-Credential <PSCredentia l>] [-Credential <PSCredential>] [-Port <int>] [-Port <int>] [-Port [-Port <int>] [-Port <int>] [-Port <int>] [-Port t <int>] [-UseSSL] [-ResourceURI] <Uri> [-Action] <string> [-Authentication <AuthenticationMechanism>] [-FilePath <File>] [-OptionSet <hashtable>] [-S electorSet <hashtable>] [-SessionOption <hashtable>] [-ValueSet <hashtable> ] [<CommonParameters>] Invoke-WSManAction [-ConnectionURI <Uri>] [-ResourceURI] <Uri> [-Action] <s tring> [-Authentication <AuthenticationMechanism>] [-FilePath <File>] [-Opt ionSet <hashtable>] [-SelectorSet <hashtable>] [-SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>] DESCRIPTION The Invoke-WSManAction runs an action on the object that is specified by RE SOURCE_URI, where parameters are specified by key value pairs. This cmdlet uses the WSMan connection/transport layer to run the action. PARAMETERS -Action <string> Indicates the method to run on the management object specified by the R esourceURI and selectors. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -ApplicationName <string> Specifies the application name in the connection. The default value of the ApplicationName parameter is WSMAN. The complete identifier for the remote endpoint is in the following format: <transport>://<server>:<port>/ For example: http://server01:8080/WSMAN Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is desi gned to be used when numerous computers establish remote connections to one computer running Windows PowerShell. In this case, IIS hosts Web S ervices for Management (WS-Management) for efficiency. Required? false Position? named Default value wsman Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationMechanism> Specifies the authentication mechanism to be used at the server. Possib le values are: - Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - Default : Use the authentication method implemented by the WS-Managem ent protocol. This is the default. - Digest: Digest is a challenge-response scheme that uses a server-spec ified data string for the challenge. - Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates. - Negotiate: Negotiate is a challenge-response scheme that negotiates w ith the server or proxy to determine the scheme to use for authenticati on. For example, this parameter value allows negotiation to determine w hether the Kerberos protocol or NTLM is used. - CredSSP: Use Credential Security Service Provider (CredSSP) authentic ation, which allows the user to delegate credentials. This option is de signed for commands that run on one remote computer but collect data fr om or run additional commands on other remote computers. Caution: CredSSP delegates the user's credentials from the local comput er to a remote computer. This practice increases the security risk of t he remote operation. If the remote computer is compromised, when creden tials are passed to it, the credentials can be used to control the netw ork session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name must be used. You can pipe a v alue for this parameter to the cmdlet. Required? false Position? named Default value localhost Accept pipeline input? false Accept wildcard characters? false -ConnectionURI <Uri> Specifies the connection endpoint. The format of this string is: <Transport>://<Server>:<Port>/ The following string is a properly formatted value for this parameter: http://Server01:8080/WSMAN The URI must be fully qualified. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or User@Domain.com. Or, enter a PSCredential object, suc h as one returned by the Get-Credential cmdlet. When you type a user na me, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -FilePath <File> Specifies the path of a file that is used to update a management resour ce. You specify the management resource by using the ResourceURI parame ter and the SelectorSet parameter. For example, the following command u ses the FilePath parameter: invoke-wsmanaction -action stopservice -resourceuri wmicimv2/Win32_Serv ice -SelectorSet @{Name="spooler"} -FilePath:c:\input.xml -authenticati on default This command calls the StopService method on the Spooler service by usi ng input from a file. The file, Input.xml, contains the following conte nt: <p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1 /wmi/root/cimv2/Win32_Service"/> Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -OptionSet <hashtable> Passes a set of switches to a service to modify or refine the nature o f the request. These are similar to switches used in command-line shell s because they are service specific. Any number of options can be spec ified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: -OptionSet @{a=1;b=2;c=3} Required? false Position? named Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Port <int> Specifies the port to use when the client connects to the WinRM service . When the transport is HTTP, the default port is 80. When the transpor t is HTTPS, the default port is 443. When you use HTTPS as the transpor t, the value of the ComputerName parameter must match the server's cert ificate common name (CN). However, if the SkipCNCheck parameter is spec ified as part of the SessionOption parameter, then the certificate comm on name of the server does not have to match the host name of the serve r. The SkipCNCheck parameter should be used only for trusted machines. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ResourceURI <Uri> Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, suc h as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Log icalDisk http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSenso r Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -SelectorSet <hashtable> Specifies a set of value pairs that are used to select particular manag ement resource instances. The SelectorSet parameter is used when more t han one instance of the resource exists. The value of the SelectorSet p arameter must be a hash table. The following example shows how to enter a value for this parameter: -SelectorSet @{Name="WinRM";ID="yyy"} Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SessionOption <hashtable> Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOpt ion cmdlet. For more information about the options that are available, see New-WSManSessionOption. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Specifies that the Secure Sockets Layer (SSL) protocol should be used t o establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is tran smitted over the network. The UseSSL parameter lets you specify the add itional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this paramete r, the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ValueSet <hashtable> Specifies a hash table that helps modify a management resource. You spe cify the management resource by using the ResourceURI parameter and the SelectorSet parameter. The value of the ValueSet parameter must be a h ash table. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>invoke-wsmanaction -action startservice -resourceuri wmicimv2/win32_s ervice -selectorset @{name="spooler"} -authentication default xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win3 2_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common lang : en-US ReturnValue : 0 Description ----------- This command calls the StartService method of the Win32_Service WMI class i nstance that corresponds to the Spooler service. The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started. -------------------------- EXAMPLE 2 -------------------------- C:\PS>invoke-wsmanaction -action stopservice -resourceuri wmicimv2/Win32_Se rvice -SelectorSet @{Name="spooler"} -FilePath:input.xml -authentication de fault xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win3 2_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common lang : en-US ReturnValue : 0 Description ----------- This command calls the StopService method on the Spooler service by using i nput from a file. The file, Input.xml, contains the following content: <p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wm i/root/cimv2/Win32_Service"/> The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started. -------------------------- EXAMPLE 3 -------------------------- C:\PS>invoke-wsmanaction -action create -resourceuri wmicimv2/win32_process -valueset @{commandline="notepad.exe";currentdirectory="C:\"} xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win3 2_Process cim : http://schemas.dmtf.org/wbem/wscim/1/common lang : en-US ProcessId : 6356 ReturnValue : 0 Description ----------- This command calls the Create method of the Win32_Process class. It passes the method two parameter values, Notepad.exe and "C:\". As a result, a new process is created to run Notepad, and the current directory of the new pro cess is set to "C:\". -------------------------- EXAMPLE 4 -------------------------- C:\PS>invoke-wsmanaction -action startservice -resourceuri wmicimv2/win32_s ervice -selectorset @{name="spooler"} -computername server01 -authenticati on default xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win3 2_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common lang : en-US ReturnValue : 0 Description ----------- This command calls the StartService method of the Win32_Service WMI class i nstance that corresponds to the Spooler service. Because the ComputerName p arameter is specified, the command runs against the remote server01 compute r. The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141446 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan Invoke-WmiMethod Join-Path NAME Join-Path SYNOPSIS Combines a path and a child path into a single path. The provider supplies the path delimiters. SYNTAX Join-Path [-Path] <string[]> [-ChildPath] <string> [-Credential <PSCredenti al>] [-Resolve] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Join-Path cmdlet combines a path and child-path into a single path. The provider supplies the path delimiters. PARAMETERS -ChildPath <string> Specifies the elements to append to the value of Path. Wildcards are pe rmitted. The ChildPath parameter is required, although the parameter na me ("ChildPath") is optional. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PS Credential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the main path (or paths) to which the child-path is appended. Wildcards are permitted. The value of Path determines which provider joins the paths and adds th e path delimiters. The Path parameter is required, although the paramet er name ("Path") is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Resolve [<SwitchParameter>] Displays the items that are referenced by the joined path. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Join-Path. OUTPUTS System.String Join-Path returns a string that contains the resulting path. NOTES The cmdlets that contain the Path noun (the Path cmdlets) manipulate pa th names and return the names in a concise format that all Windows Powe rShell providers can interpret. They are designed for use in programs a nd scripts where you want to display all or part of a path name in a pa rticular format. Use them like you would use Dirname, Normpath, Realpat h, Join, or other path manipulators. You can use the path cmdlets with several providers, including the File System, Registry, and Certificate providers. The Join-Path cmdlet is designed to work with the data exposed by any p rovider. To list the providers available in your session, type "Get-PSP rovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>join-path -path c:\win* -childpath System* Description ----------- This command uses Join-Path to combine the "c:\Win*" path with the "System* " child path. The Windows PowerShell file system provider, FileSystem joins the path and adds the "\" delimiter. -------------------------- EXAMPLE 2 -------------------------- C:\PS>join-path c:\win* System* -resolve Description ----------- This command displays the files and folders that are referenced by joining the "c:\Win*" path and the "System*" child path. It displays the same files and folders as Get-ChildItem, but it displays the fully qualified path to each item. In this command, the Path and ChildPath optional parameter names are omitted. -------------------------- EXAMPLE 3 -------------------------- C:\PS>PS HKLM:\> join-path System *ControlSet* -resolve Description ----------- This command displays the registry keys in the HKLM\System registry subkey that include "ControlSet". This example shows how to use Join-Path with the Windows PowerShell registry provider. -------------------------- EXAMPLE 4 -------------------------- C:\PS>join-path -path C:, D:, E:, F: -childpath New Description ----------- This command uses Join-Path to combine multiple path roots with a child pat h. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-psdrive -psprovider filesystem | foreach {$_.root} | join-path -c hildpath Subdir Description ----------- This command combines the roots of each Windows PowerShell file system driv e in the console with the Subdir child path. The command uses the Get-PSDrive cmdlet to get the Windows PowerShell drive s supported by the FileSystem provider. The ForEach statement selects only the Root property of the PSDriveInfo objects and combines it with the speci fied child path. The output shows that the Windows PowerShell drives on the computer include d a drive mapped to the C:\Program Files directory. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113347 about_Providers Test-Path Split-Path Resolve-Path Convert-Path Limit-EventLog NAME Limit-EventLog SYNOPSIS Sets the event log properties that limit the size of the event log and the age of its entries. SYNTAX Limit-EventLog [-LogName] <string[]> [-ComputerName <string[]>] [-MaximumSi ze <Int64>] [-OverFlowAction {OverwriteAsNeeded | OverwriteOlder | DoNotOve rwrite}] [-RetentionDays <int>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Limit-EventLog cmdlet sets the maximum size of a classic event log, how long each event must be retained, and what happens when the log reaches it s maximum size. You can use it to limit the event logs on local or remote c omputers. The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinE vent. PARAMETERS -ComputerName <string[]> Specifies a remote computer. The default is the local computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qu alified domain name of a remote computer. To specify the local computer , type the computer name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Limit-EventLog even if your computer is not configured to run remote commands. Required? false Position? named Default value Local computer Accept pipeline input? false Accept wildcard characters? false -LogName <string[]> Specifies the event logs. Enter the log name (the value of the Log prop erty; not the LogDisplayName) of one or more event logs , separated by commas. Wildcard characters are not permitted. This parameter is requi red. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -MaximumSize <Int64> Specifies the maximum size of the event logs in bytes. Enter a value be tween 64 kilobytes (KB) and 4 gigabytes (GB). The value must be divisib le by 64 KB (65536). This parameter specifies the value of the MaximumKilobytes property of the System.Diagnostics.EventLog object that represents a classic event log. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -OverFlowAction <OverflowAction> Specifies what happens when the event log reaches its maximum size. Valid values are: -- DoNotOverwrite: Existing entries are retained and new entries are d iscarded. -- OverwriteAsNeeded: Each new entry overwrites the oldest entry. -- OverwriteOlder: New events overwrite events older than the value sp ecified by the MinimumRetentionDays property. If there are no events ol der than specified by the MinimumRetentionDays property value, new even ts are discarded. This parameter specifies the value of the OverflowAction property of th e System.Diagnostics.EventLog object that represents a classic event lo g. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -RetentionDays <int> Specifies the minimum number of days that an event must remain in the e vent log. This parameter specifies the value of the MinimumRetentionDays property of the System.Diagnostics.EventLog object that represents a classic ev ent log. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None None OUTPUTS None None NOTES To use Limit-EventLog on Windows Vista and later versions of Windows, o pen Windows PowerShell with the "Run as administrator" option. Limit-EventLog changes the properties of the System.Diagnostics.EventLo g object that represents a classic event log. To see the current settin gs of the event log properties, type "get-eventlog -list". -------------------------- EXAMPLE 1 -------------------------- C:\PS>limit-eventLog -logname "Windows PowerShell" -MaximumSize 20KB Description ----------- This command increases the maximum size of the Windows PowerShell event log on the local computer to 20480 kilobytes (KB) (20 KB). -------------------------- EXAMPLE 2 -------------------------- C:\PS>limit-eventlog -logname Security -comp Server01, Server02 -retentionD ays 7 Description ----------- This command ensures that events in the Security log on the Server01 and Se rver02 computers are retained for at least 7 days. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$logs = get-eventlog -list | foreach {$_.log} C:\PS> limit-eventlog -overflowaction OverwriteOlder -logname $logs C:\PS> get-eventlog -list Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 15,168 0 OverwriteOlder 3,412 Application 512 0 OverwriteOlder 0 DFS Replication 512 0 OverwriteOlder 17 DxStudio 10,240 7 OverwriteOlder 0 HardwareEvents 512 0 OverwriteOlder 0 Internet Explorer 512 0 OverwriteOlder 0 Key Management Service 16,384 0 OverwriteOlder 4 ODiag 16,384 0 OverwriteOlder 389 OSession Security 15,168 0 OverwriteOlder 19,360 System 15,360 0 OverwriteOlder 15,828 Windows PowerShell Description ----------- These commands change the overflow action of all event logs on the local co mputer to "OverwriteOlder". The first command gets the log names of all of the logs on the local comput er. The second command sets the overflow action. The third command displays the results. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135227 Clear-EventLog Get-EventLog Limit-EventLog New-EventLog Remove-EventLog Show-EventLog Write-EventLog Get-WinEvent Measure-Command NAME Measure-Command SYNOPSIS Measures the time it takes to run script blocks and cmdlets. SYNTAX Measure-Command [-Expression] <scriptblock> [-InputObject <psobject>] [<Com monParameters>] DESCRIPTION The Measure-Command cmdlet runs a script block or cmdlet internally, times the execution of the operation, and returns the execution time. PARAMETERS -Expression <scriptblock> Specifies the expression that is being timed. Enclose the expression in curly braces ({}). The parameter name ("Expression") is optional. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies objects representing the expressions to be measured. Enter a variable that contains the objects or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe an object to Measure-Command. OUTPUTS System.TimeSpan Measure-Command returns a time span object that represents the result. NOTES For more information, type "Get-Help Measure-Command -detailed". For te chnical information, type "Get-Help Measure-Command -full". When specifying multiple values for a parameter, use commas to separat e the values. For example, "<parameter-name> <value1>, <value2>". -------------------------- EXAMPLE 1 -------------------------- C:\PS>Measure-Command { get-eventlog "windows powershell" } Description ----------- This command measures the time it takes to run a "get-eventlog" command tha t gets the events in the Windows PowerShell event log. -------------------------- EXAMPLE 2 -------------------------- C:\PS>measure-command {get-childitem c:\windows -include *.txt -recurse} Days : 0 Hours : 0 Minutes : 0 Seconds : 8 Milliseconds : 618 Ticks : 86182763 TotalDays : 9.9748568287037E-05 TotalHours : 0.00239396563888889 TotalMinutes : 0.143637938333333 TotalSeconds : 8.6182763 TotalMilliseconds : 8618.2763 C:\PS>measure-command {get-childitem c:\windows -filter "*.txt" -recurse} Days : 0 Hours : 0 Minutes : 0 Seconds : 1 Milliseconds : 140 Ticks : 11409189 TotalDays : 1.32050798611111E-05 TotalHours : 0.000316921916666667 TotalMinutes : 0.019015315 TotalSeconds : 1.1409189 TotalMilliseconds : 1140.9189 Description ----------- These commands show the value of using a provider-specific filter in Window s PowerShell commands. The first command measures the time it takes to proc ess a recursive Get-ChildItem command that uses the Include parameter. The second command measures the time it takes to process a recursive Get-ChildI tem command that uses the provider-specific Filter parameter. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113348 Trace-Command Invoke-Command Measure-Object NAME Measure-Object SYNOPSIS Calculates the numeric properties of objects, and the characters, words, an d lines in string objects, such as files of text. SYNTAX Measure-Object [-Average] [-Maximum] [-Minimum] [-Sum] [[-Property] <string []>] [-InputObject <psobject>] [<CommonParameters>] Measure-Object [-Character] [-IgnoreWhiteSpace] [-Line] [-Word] [[-Property ] <string[]>] [-InputObject <psobject>] [<CommonParameters>] DESCRIPTION The Measure-Object cmdlet calculates the property values of certain types o f object. Measure-Object performs three types of measurements, depending on the parameters in the command. The Measure-Object cmdlet performs calculations on the property values of o bjects. It can count objects and calculate the minimum, maximum, sum, and average of the numeric values. For text objects, it can count and calculate the number of lines, words, and characters. PARAMETERS -Average [<SwitchParameter>] Displays the average value of the specified properties. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Character [<SwitchParameter>] Counts the number of characters in the input object. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -IgnoreWhiteSpace [<SwitchParameter>] Ignores white space in word counts and character counts. By default, wh ite space is not ignored. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be measured. Enter a variable that contains th e objects, or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Line [<SwitchParameter>] Counts the number of lines in the input object. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Maximum [<SwitchParameter>] Displays the maximum value of the specified properties. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Minimum [<SwitchParameter>] Displays the minimum value of the specified properties. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Property <string[]> Specifies one or more numeric properties to measure. The default is the Count (Length) property of the object. Required? false Position? 1 Default value Count Accept pipeline input? false Accept wildcard characters? false -Sum [<SwitchParameter>] Displays the sum of the values of the specified properties. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Word [<SwitchParameter>] Counts the number of words in the input object. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe objects to Measure-Object. OUTPUTS GenericMeasureInfo or TextMeasureInfoObject NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-childitem | measure-object Description ----------- This command counts the files and folders in the current directory. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-childitem | measure-object -property length -minimum -maximum -av erage Description ----------- This command displays the minimum, maximum, and sum of the sizes of all fil es in the current directory, and the average size of a file in the director y. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-content C:\test.txt | measure-object -character -line -word Description ----------- This command displays the number of characters, words, and lines in the Tex t.txt file. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-process | measure-object -property workingset -minimum -maximum - average Description ----------- This command displays the minimum, maximum, and average sizes of the workin g sets of the processes on the computer. -------------------------- EXAMPLE 5 -------------------------- C:\PS>import-csv d:\test\serviceyrs.csv | measure-object -property years -m inimum -maximum -average Description ----------- This command calculates the average years of service of the employees of a company. The ServiceYrs.csv file is a CSV file that contains the employee number and years of service of each employee. The first row in the table is a header row of "EmpNo, Years". When you use Import-Csv to import the file, the result is a PSCustomObject with note properties of EmpNo and Years. You can use Measure-Object to calc ulate the values of these properties, just like any other property of an ob ject. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-childitem | measure-object -property psiscontainer -max -sum -min -average Count : 126 Average : 0.0634920634920635 Sum : 8 Maximum : 1 Minimum : 0 Property : PSIsContainer Description ----------- This example demonstrates the Measure-Object can measure Boolean values. In this case, it uses the PSIsContainer Boolean property to measure the incid ence of folders (vs. files) in the current directory. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113349 Compare-Object ForEach-Object Group-Object New-Object Select-Object Sort-Object Tee-Object Where-Object mkdir NAME New-Item SYNOPSIS Creates a new item. SYNTAX New-Item [-Path] <string[]> [-Credential <PSCredential>] [-Force] [-ItemTyp e <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTransaction] [<Comm onParameters>] New-Item -Name <string> [[-Path] <string[]>] [-Credential <PSCredential>] [ -Force] [-ItemType <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTr ansaction] [<CommonParameters>] DESCRIPTION The New-Item cmdlet creates a new item and sets its value. The types of ite ms that can be created depend upon the location of the item. For example, i n the file system, New-Item is used to create files and folders. In the reg istry, New-Item creates registry keys and entries. New-Item can also set the value of the items that it creates. For example, when creating a new file, New-Item can add initial content to the file. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to create an item that writes over an existing read-o nly item. Implementation varies from provider to provider. For more inf ormation, see about_Providers. Even using the Force parameter, the cmdl et cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ItemType <string> Specifies the provider-specified type of the new item. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies the name of the new item. You can use this parameter to speci fy the name of the new item, or include the name in the value of the Pa th parameter. Required? true Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the path to the location of the new item. Wildcards are permi tted. You can specify the name of the new item in the Name parameter, or incl ude it in the Path parameter. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Value <Object> Specifies the value of the new item. You can also pipe a value to New-I tem. Required? false Position? named Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe a value for the new item to the New-Item cmdlet. OUTPUTS System.Object New-Item returns the item that it creates. NOTES The New-Item cmdlet is designed to work with the data exposed by any pr ovider. To list the providers available in your session, type "Get-PsPr ovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-item -path . -name testfile1.txt -type "file" -value "This is a t ext string." Description ----------- This command creates a text file named testfile1.txt in the current directo ry. The dot (.) in the value of the Path parameter indicates the current di rectory. The quoted text that follows the Value parameter is added to the f ile as content. -------------------------- EXAMPLE 2 -------------------------- C:\PS>new-item -path c:\ -name logfiles -type directory Description ----------- This command creates a directory named Logfiles in the C: drive. The Type p arameter specifies that the new item is a directory, not a file or other fi le system object. -------------------------- EXAMPLE 3 -------------------------- C:\PS>new-item -path $profile -type file -force Description ----------- This command creates a Windows PowerShell profile in the path that is speci fied by the $profile variable. You can use profiles to customize Windows PowerShell. $Profile is an automa tic (built-in) variable that stores the path and file name of the CurrentUs er/CurrentHost profile. By default, the profile does not exist, even though Windows PowerShell stores a path and file name for it. In this command, the $profile variable represents the path to the file. The Type parameter (or InfoType) specifies that the command creates a file. Th e Force parameter lets you create a file in the profile path, even when the directories in the path do not exist (Windows PowerShell creates them). After you use this command to create a profile, you can enter aliases, func tions, and scripts in the profile to customize your shell. For more information, see about_Automatic_Variables and about_Profiles. -------------------------- EXAMPLE 4 -------------------------- C:\PS>new-item -type directory -path c:\ps-test\scripts Description ----------- This command creates a new Scripts directory in the C:\PS-Test directory. The name of the new directory item, Scripts, is included in the value of th e Path parameter, instead of being specified in the value of the Name param eter. As indicated by the syntax, either command form is valid. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113353 about_Providers Get-Item Set-Item Remove-Item Clear-Item Invoke-Item Rename-Item Move-Item Copy-Item more more [[-paths] <String[]>] Move-Item NAME Move-Item SYNOPSIS Moves an item from one location to another. SYNTAX Move-Item [-LiteralPath] <string[]> [[-Destination] <string>] [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonPar ameters>] Move-Item [-Path] <string[]> [[-Destination] <string>] [-Credential <PSCred ential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <strin g[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters >] DESCRIPTION The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider. For example, it can move a file or subdirec tory from one directory to another or move a registry subkey from one key t o another. When you move an item, it is added to the new location and delet ed from its original location. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Destination <string> Specifies the path to the location where the items are being moved. The default is the current directory. Wildcards are permitted, but the res ult must specify a single location. To rename the item being moved, specify a new name in the value of the Destination parameter. Required? false Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to move an item that writes over an existing read-onl y item. Implementation varies from provider to provider. For more infor mation, see about_Providers. Even using the Force parameter, the cmdlet cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Moves only the specified items. The value of this parameter qualifies t he Path parameter. Enter a path element or pattern, such as "*.txt". Wi ldcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies the path to the current location of the items. Unlike Path, t he value of LiteralPath is used exactly as it is typed. No characters a re interpreted as wildcards. If the path includes escape characters, en close it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Passes an object representing the item to the pipeline. By default, thi s cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the current location of the items. The default is the current directory. Wildcards are permitted. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Move-Item. OUTPUTS None or an object representing the moved item. When you use the Passthru parameter, Move-Item generates an object repr esenting the moved item. Otherwise, this cmdlet does not generate any o utput. NOTES Move-Item will move files between drives that are supported by the same provider, but it will move directories only within the same drive. Because a Move-Item command moves the properties, contents, and child i tems of an item, all moves are recursive by default. You can also refer to Move-Item by its built-in aliases, "move", "mv", and "mi". For more information, see about_Aliases. The Move-Item cmdlet is designed to work with the data exposed by any p rovider. To list the providers available in your session, type "Get-PsP rovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>move-item -path C:\test.txt -destination E:\Temp\tst.txt Description ----------- This command moves the Test.txt file from the C: drive to the E:\Temp direc tory and renames it from "test.txt" to "tst.txt". -------------------------- EXAMPLE 2 -------------------------- C:\PS>move-item -path C:\Temp -destination C:\Logs Description ----------- This command moves the C:\Temp directory and its contents to the C:\Logs di rectory. The Temp directory, and all of its subdirectories and files, then appear in the Logs directory. -------------------------- EXAMPLE 3 -------------------------- C:\PS>move-item -path .\*.txt -destination C:\Logs Description ----------- This command moves all of the text files (*.txt) in the current directory ( represented by a dot (.)) to the C:\Logs directory. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-childitem -path . -recurse -include *.txt | move-item -destinatio n C:\TextFiles Description ----------- This command moves all of the text files from the current directory and all subdirectories, recursively, to the C:\TextFiles directory. The command uses the Get-ChildItem cmdlet to get all of the child items in the current directory (represented by the dot [.]) and its subdirectories t hat have a *.txt file name extension. It uses the Recurse parameter to make the retrieval recursive and the Include parameter to limit the retrieval t o *.txt files. The pipeline operator (|) sends the results of this command to Move-Item, w hich moves the text files to the TextFiles directory. If files being moved to C:\Textfiles have the same name, Move-Item displays an error and continues, but it moves only one file with each name to C:\Te xtfiles. The other files remain in their original directories. If the Textfiles directory (or any other element of the destination path) d oes not exist, the command fails. The missing directory is not created for you, even if you use the Force parameter. Move-Item moves the first item to a file called "Textfiles" and then displays an error explaining that the f ile already exists. Also, by default, Get-ChildItem does not move hidden files. To move hidden files, use the Force parameter with Get-ChildItem. -------------------------- EXAMPLE 5 -------------------------- C:\PS>move-item hklm:\software\mycompany\* hklm:\software\mynewcompany Description ----------- This command moves the registry keys and values within the MyCompany regist ry key in HKLM\Software to the MyNewCompany key. The wildcard character (*) indicates that the contents of the MyCompany key should be moved, not the key itself. In this command, the optional Path and Destination parameter na mes are omitted. -------------------------- EXAMPLE 6 -------------------------- C:\PS>move-item -literalpath 'Logs[Sept`06]' -destination 'Logs[2006]' Description ----------- This command moves the Logs[Sept`06] directory (and its contents) into the Logs[2006] directory. The LiteralPath parameter is used instead of Path, because the original dir ectory name includes left bracket and right bracket characters ("[" and "]" ). The path is also enclosed in single quotation marks (' '), so that the b acktick symbol (`) is not misinterpreted. The Destination parameter does not require a literal path, because the Dest ination variable also must be enclosed in single quotation marks, because i t includes brackets that can be misinterpreted. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113350 about_Providers Clear-Item Get-Item Invoke-Item Set-Item New-Item Remove-Item Rename-Item Copy-Item Move-ItemProperty NAME Move-ItemProperty SYNOPSIS Moves a property from one location to another. SYNTAX Move-ItemProperty [-LiteralPath] <string[]> [-Destination] <string> [-Name] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter ring>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-Us eTransaction] [<CommonParameters>] Move-ItemProperty [-Path] <string[]> [-Destination] <string> [-Name] <strin g[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransa ction] [<CommonParameters>] DESCRIPTION The Move-ItemProperty cmdlet moves a property of an item from one item to a nother item. For example, it can move a registry entry from one registry ke y to another registry key. When you move an item property, it is added to the new location and deleted from its original location. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Destination <string> Specifies the path to the destination location. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to move properties to or from items that cannot other wise be accessed by the user. Implementation varies from provider to pr ovider. For more information, see about_Providers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Moves only the specified items. The value of this parameter qualifies t he Path parameter. Enter a path element or pattern, such as "*.txt". Wi ldcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies the path to the current location of the property. Unlike Path , the value of LiteralPath is used exactly as it is typed. No character s are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Wind ows PowerShell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Specifies the name of the property to be moved. Required? true Position? 3 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Passes an object representing the item property. By default, this cmdle t does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the current location of the property. Wildcards a re permitted. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Move-ItemProperty. OUTPUTS None or System.Management.Automation.PSCustomObject When you use the PassThru parameter, Move-ItemProperty generates a PSCu stomObject representing the moved item property. Otherwise, this cmdlet does not generate any output. NOTES The names of the Path, Destination, and Name parameters are optional. I f you omit the parameter names, the unnamed parameter values must appea r in this order: Path, Destination, Name. If you include the parameter names, the parameters can appear in any order. You can also refer to Move-ItemProperty by its built-in alias, "mp". Fo r more information, see about_Aliases. The Move-ItemProperty cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>move-itemproperty HKLM:\Software\MyCompany\MyApp -Name ` Version -Destination HKLM:\Software\MyCompany\NewApp Description ----------- This command moves the "Version" registry value, and its data, from the MyA pp subkey to the NewApp subkey of the HKLM\Software\MyCompany registry key. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113351 about_Providers Clear-ItemProperty New-ItemProperty Copy-ItemProperty Rename-ItemProperty Get-ItemProperty Set-ItemProperty Remove-ItemProperty New-Alias NAME New-Alias SYNOPSIS Creates a new alias. SYNTAX New-Alias [-Name] <string> [-Value] <string> [-Description <string>] [-Forc e] [-Option {None | ReadOnly | Constant | Private | AllScope}] [-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The New-Alias cmdlet creates a new alias in the current Windows PowerShell session. Aliases created by using New-Alias are not saved after you exit th e session or close Windows PowerShell. You can use the Export-Alias cmdlet to save your alias information to a file. You can later use Import-Alias to retrieve that saved alias information. PARAMETERS -Description <string> Specifies a description of the alias. You can type any string. If the d escription includes spaces, enclose it in quotation marks. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] If set, act like set-alias if the alias named already exists. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies the new alias. You can use any alphanumeric characters in an alias, but the first character cannot be a number. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Option <ScopedItemOptions> Sets one or more optional properties of the alias. Valid values are: -- None: Sets no options. (default) -- ReadOnly: The alias cannot be changed unless you use the Force param eter. -- Constant: The alias cannot be changed, even by using the Force param eter. -- Private: The alias is available only within the scope specified by t he Scope parameter. It is invisible in all other scopes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the new alias. By default, this cmdlet d oes not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Scope <string> Specifies the scope of the new alias. Valid values are "Global", "Local ", or "Script", or a number relative to the current scope (0 through th e number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Value <string> Specifies the name of the cmdlet or command element that is being alias ed. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None or System.Management.Automation.AliasInfo When you use the Passthru parameter, New-Alias generates a System.Manag ement.Automation.AliasInfo object representing the new alias. Otherwise , this cmdlet does not generate any output. NOTES To create a new alias, use Set-Alias or New-Alias. To change an alias, use Set-Alias. To delete an alias, use Remove-Item. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-alias list get-childitem Description ----------- This command creates an alias named "list" to represent the Get-ChildItem c mdlet. -------------------------- EXAMPLE 2 -------------------------- C:\PS>new-alias -name w -value get-wmiobject -description "quick wmi alias" -option ReadOnly C:\PS> get-alias -name w | format-list * Description ----------- This command creates an alias named "w" to represent the Get-WMIObject cmdl et. It creates a description, "quick wmi alias", for the alias and makes it read only. The last line of the command uses Get-Alias to get the new alia s and pipes it to Format-List to display all of the information about it. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113352 Set-Alias Get-Alias Export-Alias Import-Alias New-Event NAME New-Event SYNOPSIS Creates a new event. SYNTAX New-Event [-SourceIdentifier] <string> [[-Sender] <psobject>] [[-EventArgum ents] <PSObject[]>] [[-MessageData] <psobject>] [<CommonParameters>] DESCRIPTION The New-Event cmdlet creates a new custom event. You can use custom events to notify users about state changes in your progr am and any change that your program can detect, including hardware or syste m conditions, application status, disk status, network status, or the compl etion of a background job. Custom events are automatically added to the event queue in your session wh enever they are raised; you do not need to subscribe to them. However, if y ou want to forward an event to the local session or specify an action to re spond to the event, use the Register-EngineEvent cmdlet to subscribe to the custom event. When you subscribe to a custom event, the event subscriber is added to your session. If you cancel the event subscription by using the Unregister-Even t cmdlet, the event subscriber and custom event are deleted from the sessio n. If you do not subscribe to the custom event, to delete the event, you mu st change the program conditions or close the Windows PowerShell session. PARAMETERS -EventArguments <PSObject[]> Specifies an object that contains options for the event. Required? false Position? 3 Default value None Accept pipeline input? false Accept wildcard characters? false -MessageData <psobject> Specifies additional data associated with the event. The value of this parameter appears in the MessageData property of the event object. Required? false Position? 4 Default value None Accept pipeline input? false Accept wildcard characters? false -Sender <psobject> Specifies the object that raises the event. The default is the Windows PowerShell engine. Required? false Position? 2 Default value None Accept pipeline input? false Accept wildcard characters? false -SourceIdentifier <string> Specifies a name for the new event. This parameter is required, and it must be unique in the session. The value of this parameter appears in the SourceIdentifier property of the events. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.PSEventArgs NOTES The new custom event, the event subscription, and the event queue exist only in the current session. If you close the current session, the eve nt queue is discarded and the event subscription is canceled. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-event -sourceidentifier Timer -sender windows.timer -messagedata "Test" Description ----------- This command creates a new event in the Windows PowerShell event queue. It uses a Windows.Timer object to send the event. -------------------------- EXAMPLE 2 -------------------------- C:\PS>function Enable-ProcessCreationEvent { $query = New-Object System.Management.WqlEventQuery "__InstanceCreationE vent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'" $processWatcher = New-Object System.Management.ManagementEventWatcher $q uery $identifier = "WMI.ProcessCreated" Register-ObjectEvent $processWatcher "EventArrived" -SupportEvent $ident ifier -Action { [void] (New-Event -sourceID "PowerShell.ProcessCreated" -Sender $arg s[0] -EventArguments $args[1].SourceEventArgs.NewEvent.TargetInstance) } } Description ----------- This sample function uses the New-Event cmdlet to raise an event in respons e to another event. The command uses the Register-ObjectEvent cmdlet to sub scribe to the Windows Management Instrumentation (WMI) event that is raised when a new process is created. The command uses the Action parameter of th e cmdlet to call the New-Event cmdlet, which creates the new event. Because the events that New-Event raises are automatically added to the Win dows PowerShell event queue, you do not need to register for that event. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135234 Register-ObjectEvent Register-EngineEvent Register-WmiEvent Unregister-Event Get-Event Remove-Event Wait-Event New-EventLog NAME New-EventLog SYNOPSIS Creates a new event log and a new event source on a local or remote compute r. SYNTAX New-EventLog [-LogName] <string> [-Source] <string[]> [[-ComputerName] <str ing[]>] [-CategoryResourceFile <string>] [-MessageResourceFile <string>] [- ParameterResourceFile <string>] [<CommonParameters>] DESCRIPTION This cmdlet creates a new classic event log on a local or remote computer. It can also register an event source that writes to the new log or to an ex isting log. The cmdlets that contain the EventLog noun (the Event log cmdlets) work onl y on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-Win Event. PARAMETERS -CategoryResourceFile <string> Specifies the path to the file that contains category strings for the s ource events. This file is also known as the Category Message File. The file must be present on the computer on which the event log is bein g created. This parameter does not create or move files. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Creates the new event logs on the specified computers. The default is t he local computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qu alified domain name of a remote computer. To specify the local computer , type the computer name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Get-EventLog even if your computer is n ot configured to run remote commands. Required? false Position? 3 Default value . Accept pipeline input? false Accept wildcard characters? false -LogName <string> Specifies the name of the event log. If the log does not exist, New-EventLog creates the log and uses this v alue for the Log and LogDisplayName properties of the new event log. If the log exists, New-EventLog registers a new source for the event log. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -MessageResourceFile <string> Specifies the path to the file that contains message formatting strings for the source events. This file is also known as the Event Message Fi le. The file must be present on the computer on which the event log is bein g created. This parameter does not create or move files. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ParameterResourceFile <string> Specifies the path to the file that contains strings used for parameter substitutions in event descriptions. This file is also known as the Pa rameter Message File. The file must be present on the computer on which the event log is bein g created. This parameter does not create or move files. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Source <string[]> Specifies the names of the event log sources, such as application progr ams that write to the event log. This parameter is required. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Diagnostics.EventLogEntry NOTES To use New-EventLog on Windows Vista and later versions of Windows, ope n Windows PowerShell with the "Run as administrator" option. To create an event source in Windows Vista, Windows XP Professional, or Windows Server 2003, you must be a member of the Administrators group on the computer. When you create a new event log and a new event source, the system regi sters the new source for the new log, but the log is not created until the first entry is written to it. The operating system stores event logs as files. When you create a new event log, the associated file is stored in the %SystemRoot%\System32\C onfig directory on the specified computer. The file name is the first e ight characters of the Log property with an .evt file name extension. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-eventlog -source TestApp -logname TestLog -MessageResourceFile C: \Test\TestApp.dll Description ----------- This command creates the TestLog event log on the local computer and regist ers a new source for it. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$file = "C:\Program Files\TestApps\NewTestApp.dll" C:\PS> new-eventlog -computername Server01 -source NewTestApp -logname Appl ication -MessageResourceFile $file -CategoryResourceFile $file Description ----------- This command adds a new event source, NewTestApp, to the Application log on the Server01 remote computer. The command requires that the NewTestApp.dll file is located on the Server0 1 computer. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135235 Clear-EventLog Get-EventLog Limit-EventLog New-EventLog Remove-EventLog Show-EventLog Write-EventLog Get-WinEvent New-Item NAME New-Item SYNOPSIS Creates a new item. SYNTAX New-Item [-Path] <string[]> [-Credential <PSCredential>] [-Force] [-ItemTyp e <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTransaction] [<Comm onParameters>] New-Item -Name <string> [[-Path] <string[]>] [-Credential <PSCredential>] [ -Force] [-ItemType <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTr ansaction] [<CommonParameters>] DESCRIPTION The New-Item cmdlet creates a new item and sets its value. The types of ite ms that can be created depend upon the location of the item. For example, i n the file system, New-Item is used to create files and folders. In the reg istry, New-Item creates registry keys and entries. New-Item can also set the value of the items that it creates. For example, when creating a new file, New-Item can add initial content to the file. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to create an item that writes over an existing read-o nly item. Implementation varies from provider to provider. For more inf ormation, see about_Providers. Even using the Force parameter, the cmdl et cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ItemType <string> Specifies the provider-specified type of the new item. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies the name of the new item. You can use this parameter to speci fy the name of the new item, or include the name in the value of the Pa th parameter. Required? true Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the path to the location of the new item. Wildcards are permi tted. You can specify the name of the new item in the Name parameter, or incl ude it in the Path parameter. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Value <Object> Specifies the value of the new item. You can also pipe a value to New-I tem. Required? false Position? named Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe a value for the new item to the New-Item cmdlet. OUTPUTS System.Object New-Item returns the item that it creates. NOTES The New-Item cmdlet is designed to work with the data exposed by any pr ovider. To list the providers available in your session, type "Get-PsPr ovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-item -path . -name testfile1.txt -type "file" -value "This is a t ext string." Description ----------- This command creates a text file named testfile1.txt in the current directo ry. The dot (.) in the value of the Path parameter indicates the current di rectory. The quoted text that follows the Value parameter is added to the f ile as content. -------------------------- EXAMPLE 2 -------------------------- C:\PS>new-item -path c:\ -name logfiles -type directory Description ----------- This command creates a directory named Logfiles in the C: drive. The Type p arameter specifies that the new item is a directory, not a file or other fi le system object. -------------------------- EXAMPLE 3 -------------------------- C:\PS>new-item -path $profile -type file -force Description ----------- This command creates a Windows PowerShell profile in the path that is speci fied by the $profile variable. You can use profiles to customize Windows PowerShell. $Profile is an automa tic (built-in) variable that stores the path and file name of the CurrentUs er/CurrentHost profile. By default, the profile does not exist, even though Windows PowerShell stores a path and file name for it. In this command, the $profile variable represents the path to the file. The Type parameter (or InfoType) specifies that the command creates a file. Th e Force parameter lets you create a file in the profile path, even when the directories in the path do not exist (Windows PowerShell creates them). After you use this command to create a profile, you can enter aliases, func tions, and scripts in the profile to customize your shell. For more information, see about_Automatic_Variables and about_Profiles. -------------------------- EXAMPLE 4 -------------------------- C:\PS>new-item -type directory -path c:\ps-test\scripts Description ----------- This command creates a new Scripts directory in the C:\PS-Test directory. The name of the new directory item, Scripts, is included in the value of th e Path parameter, instead of being specified in the value of the Name param eter. As indicated by the syntax, either command form is valid. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113353 about_Providers Get-Item Set-Item Remove-Item Clear-Item Invoke-Item Rename-Item Move-Item Copy-Item New-ItemProperty NAME New-ItemProperty SYNOPSIS Creates a new property for an item and sets its value. For example, you can use New-ItemProperty to create and change registry values and data, which are properties of a registry key. SYNTAX New-ItemProperty [-LiteralPath] <string[]> [-Name] <string> [-Credential <P SCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include string[]>] [-PropertyType <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] New-ItemProperty [-Path] <string[]> [-Name] <string> [-Credential <PSCreden tial>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[ ]>] [-PropertyType <string>] [-Value <Object>] [-Confirm] [-WhatIf] [-UseTr ansaction] [<CommonParameters>] DESCRIPTION The New-ItemProperty cmdlet creates a new property for a specified item and sets its value. Typically, this cmdlet is used to create new registry valu es, because registry values are properties of a registry key item. This cmdlet does not add properties to an object. To add a property to an i nstance of an object, use the Add-Member cmdlet. To add a property to all o bjects of a particular type, edit the Types.ps1xml file. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcards, depends on th e provider. Filters are more efficient than other parameters, because t he provider applies them when retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to create a property on an object that cannot otherwi se be accessed by the user. Implementation varies from provider to prov ider. For more information, see about_Providers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation ma rks. Single quotation marks tell Windows PowerShell not to interpret an y characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies a name for the new property. If the property is a registry en try, this parameter specifies the name of the entry. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the path to the item. This parameter identifies the item to w hich the new property will be added. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -PropertyType <string> Specifies the type of property that will be added. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Value <Object> Specifies the property value. If the property is a registry entry, this parameter specifies the value of the entry. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to New-ItemProperty. OUTPUTS System.Management.Automation.PSCustomObject New-ItemProperty returns a custom object that contains the new property . NOTES The New-ItemProperty cmdlet is designed to work with the data exposed b y any provider. To list the providers available in your session, type " Get-PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-itemproperty -path HKLM:\Software\MyCompany -name NoOfEmployees - value 822 C:\PS> get-itemproperty hklm:\software\mycompany PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\soft ware\mycompany PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\soft ware PSChildName : mycompany PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry NoOfLocations : 2 NoOfEmployees : 822 Description ----------- This command adds a new registry entry, NoOfEmployees, to the MyCompany key of the HKLM:\Software hive. The first command uses the Path parameter to specify the path to the MyComp any registry key. It uses the Name parameter to specify a name for the entr y and the Value parameter to specify its value. The second command uses the Get-ItemProperty cmdlet to see the new registry entry. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-item -path HKLM:\Software\MyCompany | new-Itemproperty -name NoOf Locations -value 3 Description ----------- This command adds a new registry entry to a registry key. To specify the ke y, it uses a pipeline operator (|) to send an object representing the key t o the New-ItemProperty cmdlet. The first part of the command uses the Get-Item cmdlet to get the MyCompany registry key. The pipeline operator (|) sends the results of the command t o the New-ItemProperty cmdlet, which adds the new registry entry, NoOfLocat ions, and its value, 3, to the MyCompany key. This command works because the parameter-binding feature of Windows PowerSh ell associates the path of the RegistryKey object that Get-Item returns wit h the LiteralPath parameter of New-ItemProperty. For more information, see about_Pipelines. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113354 about_Providers Clear-ItemProperty Copy-ItemProperty Move-ItemProperty Rename-ItemProperty Get-ItemProperty Set-ItemProperty Remove-ItemProperty New-Module NAME New-Module SYNOPSIS Creates a new dynamic module that exists only in memory. SYNTAX New-Module [-Name] <string> [-ScriptBlock] <scriptblock> [-ArgumentList <Ob ject[]>] [-AsCustomObject] [-Cmdlet <string[]>] [-Function <string[]>] [-Re turnResult] [<CommonParameters>] New-Module [-ScriptBlock] <scriptblock> [-ArgumentList <Object[]>] [-AsCust omObject] [-Cmdlet <string[]>] [-Function <string[]>] [-ReturnResult] [<Com monParameters>] DESCRIPTION The New-Module cmdlet creates a dynamic module from a script block. The mem bers of the dynamic module, such as functions and variables, are immediatel y available in the session and remain available until you close the session . Like static modules, by default, the cmdlets and functions in a dynamic mod ule are exported and the variables and aliases are not. However, you can us e the Export-ModuleMember cmdlet and the parameters of New-Module to overri de the defaults. Dynamic modules exist only in memory, not on disk. Like all modules, the m embers of dynamic modules run in a private module scope that is a child of the global scope. Get-Module cannot get a dynamic module, but Get-Command c an get the exported members. To make a dynamic module available to Get-Module, pipe a New-Module command to Import-Module, or pipe the module object that New-Module returns to Imp ort-Module. This action adds the dynamic module to the Get-Module list, but it does not save the module to disk or make it persistent. PARAMETERS -ArgumentList <Object[]> Specifies arguments (parameter values) that are passed to the script bl ock. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -AsCustomObject [<SwitchParameter>] Returns a custom object with members that represent the module members. When you use the AsCustomObject parameter, New-Module creates the dynam ic module, imports the module members into the current session, and the n returns a PSCustomObject object instead of a PSModuleInfo object. You can save the custom object in a variable and use dot notation to invok e the members. If the module has multiple members with the same name, such as a functi on and a variable that are both named "A," only one member with each na me is accessible from the custom object. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Cmdlet <string[]> Exports only the specified cmdlets from the module into the current ses sion. Enter a comma-separated list of cmdlets. Wildcard characters are permitted. By default, all cmdlets in the module are exported. You cannot define cmdlets in a script block, but a dynamic module can i nclude cmdlets if it imports the cmdlets from a binary module. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? true -Function <string[]> Exports only the specified functions from the module into the current s ession. Enter a comma-separated list of functions. Wildcard characters are permitted. By default, all functions defined in a module are export ed. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? true -Name <string> Specifies a name for the new module. You can also pipe a module name to New-Module. The default value is an autogenerated name that begins with "__DynamicM odule_" and is followed by a GUID that specifies the path to the dynami c module. Required? true Position? 1 Default value "__DynamicModule_" + GUID Accept pipeline input? true (ByValue) Accept wildcard characters? false -ReturnResult [<SwitchParameter>] Runs the script block and returns the script block results instead of r eturning a module object. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -ScriptBlock <scriptblock> Specifies the contents of the dynamic module. Enclose the contents in b races ( { } ) to create a script block. This parameter is required. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a module name string to New-Module. OUTPUTS System.Management.Automation.PSModuleInfo, System.Management.Automation.PSC ustomObject, or None By default, New-Module generates a PSModuleInfo object. If you use the AsCustomObject parameter, it generates a PSCustomObject object. If you use the ReturnResult parameter, it returns the result of evaluating the script block in the dynamic module. NOTES You can also refer to New-Module by its alias, "nmo". For more informat ion, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-module -scriptblock {function Hello {"Hello"}} Name : __DynamicModule_2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5 Path : 2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5 Description : Guid : 00000000-0000-0000-0000-000000000000 Version : 0.0 ModuleBase : ModuleType : Script PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {[Hello, Hello]} ExportedVariables : {} NestedModules : {} Description ----------- This command creates a new dynamic module with a function called "Hello". T he command returns a module object that represents the new dynamic module. -------------------------- EXAMPLE 2 -------------------------- C:\PS>new-module -scriptblock {function Hello {"Hello"}} Name : __DynamicModule_2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5 Path : 2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5 Description : Guid : 00000000-0000-0000-0000-000000000000 Version : 0.0 ModuleBase : ModuleType : Script PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {[Hello, Hello]} ExportedVariables : {} NestedModules : {} C:\PS> get-module C:\PS> C:\PS> get-command Hello CommandType Name Definition ----------- ---- ---------- Function Hello "Hello" Description ----------- This example demonstrates that dynamic modules are not returned by the Get- Module cmdlet, but the members that they export are returned by the Get-Com mand cmdlet. -------------------------- EXAMPLE 3 -------------------------- C:\PS>New-Module -scriptblock {$SayHelloHelp="Type 'SayHello', a space, and a name."; function SayHello ($name) { "Hello, $name" }; Export-ModuleMembe r -function SayHello -Variable SayHelloHelp} C:\PS> $SayHelloHelp Type 'SayHello', a space, and a name. C:\PS> SayHello Jeffrey Hello, Jeffrey Description ----------- This command uses the Export-ModuleMember cmdlet to export a variable into the current session. Without the Export-ModuleMember command, only the func tion is exported. The output shows that both the variable and the function were exported into the session. -------------------------- EXAMPLE 4 -------------------------- C:\PS>new-module -scriptblock {function Hello {"Hello"}} -name GreetingMod ule | import-module C:\PS> get-module Name : GreetingModule Path : d54dfdac-4531-4db2-9dec-0b4b9c57a1e5 Description : Guid : 00000000-0000-0000-0000-000000000000 Version : 0.0 ModuleBase : ModuleType : Script PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {[Hello, Hello]} ExportedVariables : {} NestedModules : {} C:\PS> get-command hello CommandType Name Definition ----------- ---- ---------- Function Hello "Hello" Description ----------- This command demonstrates that you can make a dynamic module available to t he Get-Module cmdlet by piping the dynamic module to the Import-Module cmdl et. The first command uses a pipeline operator (|) to send the module object th at New-Module generates to the Import-Module cmdlet. The command uses the N ame parameter of New-Module to assign a friendly name to the module. Becaus e Import-Module does not return any objects by default, there is no output from this command. The second command uses the Get-Module cmdlet to get the modules in the ses sion. The result shows that Get-Module can get the new dynamic module. The third command uses the Get-Command cmdlet to get the Hello function tha t the dynamic module exports. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$m = new-module -scriptblock {function Hello ($name) {"Hello, $name"} ; function Goodbye ($name) {"Goodbye, $name"}} -AsCustomObject C:\PS> $m C:\PS> $m | get-member TypeName: System.Management.Automation.PSCustomObject Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Goodbye ScriptMethod System.Object Goodbye(); Hello ScriptMethod System.Object Hello(); PS C:\ps-test> $m.goodbye("Jane") Goodbye, Jane PS C:\ps-test> $m.hello("Manoj") Hello, Manoj PS C:\ps-test> goodbye Jane Goodbye, Jane PS C:\ps-test> hello Manoj Hello, Manoj Description ----------- This example shows how to use the AsCustomObject parameter of New-Module to generate a custom object with script methods that represent the exported f unctions. The first command uses the New-Module cmdlet to generate a dynamic module w ith two functions, Hello and Goodbye. The command uses the AsCustomObject p arameter to generate a custom object instead of the PSModuleInfo object tha t New-Module generates by default. The command saves the custom object in t he $m variable. The second command attempts to display the value of the $m variable. No con tent appears. The third command uses a pipeline operator (|) to send the custom object to the Get-Member cmdlet, which displays the properties and methods of the cu stom object. The output shows that the object has script methods that repre sent the Hello and Goodbye functions. The fourth and fifth commands use the script method format to call the Hell o and Goodbye functions. The sixth and seventh commands call the functions by specifying the functio n name and parameter value. -------------------------- EXAMPLE 6 -------------------------- C:\PS>new-module -scriptblock {function SayHello {"Hello, World"}; SayHell o} -returnResult Hello, World Description ----------- This command uses the ReturnResult parameter to request the results of runn ing the script block instead of requesting a module object. The script block in the new module defines the SayHello function and then c alls the function. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=141554 Get-Module Import-Module Remove-Module Export-ModuleMember about_Modules New-ModuleManifest NAME New-ModuleManifest SYNOPSIS Creates a new module manifest. SYNTAX New-ModuleManifest [-Path] <string> -Author <string> -CompanyName <string> -Copyright <string> -Description <string> -FileList <string[]> -FormatsToPr ocess <string[]> -ModuleToProcess <string> -NestedModules <string[]> -Requi redAssemblies <string[]> -TypesToProcess <string[]> [-AliasesToExport <stri ng[]>] [-ClrVersion <Version>] [-CmdletsToExport <string[]>] [-DotNetFramew orkVersion <Version>] [-FunctionsToExport <string[]>] [-Guid <Guid>] [-Modu leList <Object[]>] [-ModuleVersion <Version>] [-PassThru] [-PowerShellHostN ame <string>] [-PowerShellHostVersion <Version>] [-PowerShellVersion <Versi on>] [-PrivateData <Object>] [-ProcessorArchitecture {None | MSIL | X86 | I A64 | Amd64}] [-RequiredModules <Object[]>] [-ScriptsToProcess <string[]>] [-VariablesToExport <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The New-ModuleManifest cmdlet creates a new module manifest (.psd1) file, p opulates its values, and saves the manifest file in the specified path. Module authors can use this cmdlet to create a manifest for their module. A module manifest is a .psd1 file that contains a hash table. The keys and v alues in the hash table describe the contents and attributes of the module, define the prerequisites, and determine how the components are processed. Manifests are not required for a module. New-ModuleManifest creates a manifest that includes all of the commonly use d manifest keys, so you can use the default output as a manifest template. To add or change values, or to add module keys that this cmdlet does not ad d, open the resulting file in a text editor. Each parameter of this cmdlet (except for Path and PassThru) creates a modu le manifest key and its value. In a module manifest, only the ModuleVersion key is required. However, several other parameters of this cmdlet are mand atory. As a result, you can type a "New-ModuleManifest" command without par ameters and the cmdlet will prompt you for values for other commonly used k eys. To leave the value empty, press ENTER. For a complete description of the format, effects, and requirements of a mo dule manifest, see "How to Write a Module Manifest" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143613 . PARAMETERS -AliasesToExport <string[]> Specifies the aliases that the module exports. Wildcards are permitted. You can use this parameter to restrict the aliases that are exported by the module. It can remove aliases from the list of exported aliases, b ut it cannot add aliases to the list. If you omit this parameter, New-ModuleManifest creates an AliasesToExpo rt key with a value of * (all), meaning that all aliases that are expor ted by the module are exported by the manifest. Required? false Position? named Default value * (all) Accept pipeline input? false Accept wildcard characters? true -Author <string> Specifies the module author. This parameter is required by the cmdlet, but the Author key is not req uired in the manifest. If you omit this parameter and do not enter a va lue when prompted, New-ModuleManifest creates an Author key with the na me of the current user. Required? true Position? named Default value Name of the current user Accept pipeline input? false Accept wildcard characters? false -ClrVersion <Version> Specifies the version of the Common Language Runtime (CLR) of the Micro soft .NET Framework that the module requires. If you omit this parameter, New-ModuleManifest creates a CLRVersion key with an empty string value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -CmdletsToExport <string[]> Specifies the cmdlets that the module exports. Wildcards are permitted. You can use this parameter to restrict the cmdlets that are exported by the module. It can remove cmdlets from the list of exported cmdlets, b ut it cannot add cmdlets to the list. If you omit this parameter, New-ModuleManifest creates a CmdletsToExpor t key with a value of * (all), meaning that all cmdlets that are export ed by the module are exported by the manifest. Required? false Position? named Default value * (all) Accept pipeline input? false Accept wildcard characters? true -CompanyName <string> Identifies the company or vendor who created the module. This parameter is required by the cmdlet, but the CompanyName key is no t required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a CompanyName key wi th a value of "Unknown". Required? true Position? named Default value "Unknown" Accept pipeline input? false Accept wildcard characters? false -Copyright <string> Specifies a copyright statement for the module. This parameter is required by the cmdlet, but the Copyright key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a Copyright key with a value of "(c) <year> <username>. All rights reserved." where <year> i s the current year and <username> is the value of the Author key (if on e is specified) or the name of the current user. Required? true Position? named Default value (c) <year> <username>. All rights reserved . Accept pipeline input? false Accept wildcard characters? false -Description <string> Describes the contents of the module. This parameter is required by the cmdlet, but the Description key is no t required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a Description key wi th an empty string value. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -DotNetFrameworkVersion <Version> Specifies the version of the Microsoft .NET Framework that the module r equires. If you omit this parameter, New-ModuleManifest creates a DotNetFrameWor kVersion key with an empty string value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -FileList <string[]> Specifies all items that are included in the module. This key is designed to act as a module inventory. These files are not automatically exported with the module. This parameter is required by the cmdlet, but the FileList key is not r equired in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a FileList key with an empty array value. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -FormatsToProcess <string[]> Specifies the formatting files (.ps1xml) that run when the module is im ported. When you import a module, Windows PowerShell runs the Update-FormatData cmdlet with the specified files. Because formatting files are not scop ed, they affect all session states in the session. This parameter is required by the cmdlet, but the FormatsToProcess key is not required in the manifest. If you omit this parameter and do not enter a value when prompted, New-ModuleManifest creates a FormatsToProc ess key with an empty array value. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -FunctionsToExport <string[]> Specifies the functions that the module exports. Wildcards are permitte d. You can use this parameter to restrict the functions that are exported by the module. It can remove functions from the list of exported aliase s, but it cannot add functions to the list. If you omit this parameter, New-ModuleManifest creates an FunctionsToEx port key with a value of * (all), meaning that all functions that are e xported by the module are exported by the manifest. Required? false Position? named Default value * (all) Accept pipeline input? false Accept wildcard characters? true -Guid <Guid> Specifies a unique identifier for the module. The GUID can be used to d istinguish among modules with the same name. If you omit this parameter, New-ModuleManifest creates a GUID key in th e manifest and generates a GUID for the value. To create a new GUID in Windows PowerShell, type "[guid]::NewGuid()". Required? false Position? named Default value A GUID generated for the module Accept pipeline input? false Accept wildcard characters? false -ModuleList <Object[]> Lists all modules that are packaged with this module. Enter each module name as a string or enter a hash table with ModuleNam e and GUID keys. The hash table can also have an optional ModuleVersion key. This key is designed to act as a module inventory. These modules are no t automatically processed. If you omit this parameter, New-ModuleManifest creates a ModuleList key in the manifest with an empty array value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -ModuleToProcess <string> Specifies the primary or "root" file of the module. When the module is imported, the members that are exported from the root module file are i mported into the caller's session state. Enter the file name of one scr ipt module (.psm1) or binary module (.dll). If a module has a manifest file and no root file has been designated in the ModuleToProcess key, the manifest becomes the primary file for the module, and the module becomes a "manifest module" (ModuleType = Manif est). To export members from .psm1 or .dll files in a module that has a manif est, the names of those files must be specified in the values of the Mo duleToProcess or NestedModules keys in the manifest. Otherwise, their m embers are not exported. This parameter is required by the cmdlet, but the ModuleToProcess key i s not required in the manifest. If you omit this parameter and do not e nter a value when prompted, New-ModuleManifest creates a ModuleToProces s key with an empty string value. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -ModuleVersion <Version> Specifies the version of the module. This parameter is not required by the cmdlet, but a ModuleVersion key i s required in the manifest. If you omit this parameter, New-ModuleManif est creates a ModuleVersion key with a value of "1.0". Required? false Position? named Default value 1.0 Accept pipeline input? false Accept wildcard characters? false -NestedModules <string[]> Specifies script modules (.psm1) and binary modules (.dll) that are imp orted into the module's session state. The files in the NestedModules k ey run in the order in which they are listed in the value. Typically, nested modules contain commands that the root module needs f or its internal processing. By default, the commands in nested modules are exported from the module's session state into the caller's session state, but the root module can restrict the commands that it exports (f or example, by using an Export-Module command). Nested modules in the module session state are available to the root mo dule, but they are not returned by a Get-Module command in the caller's session state. Scripts (.ps1) that are listed in the NestedModules key are run in the module's session state, not in the caller's session state. To run a scr ipt in the caller's session state, list the script file name in the val ue of the ScriptsToProcess key in the manifest. This parameter is required by the cmdlet, but the NestedModules key is not required in the manifest. If you omit this parameter and do not ent er a value when prompted, New-ModuleManifest creates a NestedModules ke y with an empty array value. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Writes the resulting module manifest to the console, in addition to cre ating a .psd1 file. By default, this cmdlet does not generate any outpu t. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the path and file name of the new module manifest. Enter a pa th and file name with a .psd1 file name extension, such as "$pshome\Mod ules\MyModule\MyModule.psd1". This parameter is required. If you specify the path to an existing file, New-ModuleManifest replace s the file without warning unless the file has the read-only attribute. The manifest should be located in the module's directory, and the manif est file name should be the same as the module directory name, but with a .psd1 file name extension. Note: You cannot use variables, such as $pshome or $home, in response t o a prompt for a Path parameter value. To use a variable, include the Path parameter in the command. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -PowerShellHostName <string> Specifies the name of the Windows PowerShell host program that the modu le requires. Enter the name of the host program, such as "Windows Power Shell ISE Host" or "ConsoleHost". Wildcards are not permitted. To find the name of a host program, in the program, type "$host.name". If you omit this parameter, New-ModuleManifest creates a PowerShellHost Name key with an empty string value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -PowerShellHostVersion <Version> Specifies the minimum version of the Windows PowerShell host program th at works with the module. Enter a version number, such as 1.1. If you omit this parameter, New-ModuleManifest creates a PowerShellHost Name key with an empty string value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -PowerShellVersion <Version> Specifies the minimum version of Windows PowerShell that will work with this module. Enter 1.0 or 2.0. Requirements for versions greater than 2.0 are not enforced. If you omit this parameter, New-ModuleManifest creates a PowerShellVers ion key with an empty string value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -PrivateData <Object> Specifies data that is passed to the module when it is imported. If you omit this parameter, New-ModuleManifest creates a PrivateData ke y with an empty string value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -ProcessorArchitecture <ProcessorArchitecture> Specifies the processor architecture that the module requires. Valid va lues are x86, AMD64, IA64, and None (unknown or unspecified). If you omit this parameter, New-ModuleManifest creates a ProcessorArchi tecture key with an empty string value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -RequiredAssemblies <string[]> Specifies the assembly (.dll) files that the module requires. Windows P owerShell loads the specified assemblies before updating types or forma ts, importing nested modules, or importing the module file that is spec ified in the value of the ModuleToProcess key. Use this parameter to list all the assemblies that the module requires, including assemblies that must be loaded to update any formatting or t ype files that are listed in the FormatsToProcess or TypesToProcess key s, even if those assemblies are also listed as binary modules in the Ne stedModules key. This parameter is required by the cmdlet, but the RequiredAssemblies ke y is not required in the manifest. If you omit this parameter and do no t enter a value when prompted, New-ModuleManifest creates a RequiredAss emblies key with an empty array value. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -RequiredModules <Object[]> Specifies modules that must be in the global session state. If the req uired modules are not in the global session state, attempts to import t his module will fail. Enter each module name as a string or enter a hash table with the Modul eName and GUID keys. The hash table can also have an optional ModuleVer sion key. For more information, see the examples. Windows PowerShell does not import required modules automatically. It v erifies only that the required modules are present. However, modules ca n include scripts (.ps1) that import the required modules into the glob al session state. If you omit this parameter, New-ModuleManifest creates a RequiredModule s key with an empty array value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -ScriptsToProcess <string[]> Specifies script (.ps1) files that run in the caller's session state wh en the module is imported. You can use these scripts to prepare an envi ronment, just as you might use a login script. To specify scripts that run in the module's session state, use the Nest edModules key. If you omit this parameter, New-ModuleManifest creates a ScriptsToProce ss key with an empty array value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -TypesToProcess <string[]> Specifies the type files (.ps1xml) that run when the module is imported . When you import the module, Windows PowerShell runs the Update-TypeData cmdlet with the specified files. Because type files are not scoped, th ey affect all session states in the session. This parameter is required by the cmdlet, but the TypesToProcess key is not required in the manifest. If you omit this parameter and do not en ter a value when prompted, New-ModuleManifest creates a TypesToProcess key with an empty array value. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -VariablesToExport <string[]> Specifies the variables that the module exports. Wildcards are permitte d. You can use this parameter to restrict the variables that are exported by the module. It can remove variables from the list of exported variab les, but it cannot add variables to the list. If you omit this parameter, New-ModuleManifest creates a VariablesToExp ort key with a value of * (all), meaning that all variables that are ex ported by the module are exported by the manifest. Required? false Position? named Default value * (all) Accept pipeline input? false Accept wildcard characters? true -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None or System.String By default, New-ModuleManifest does not generate any output. However, i f you use the PassThru parameter, it generates a System.String object r epresenting the module manifest.. NOTES Module manifests are usually optional. However, a module manifest is re quired to export an assembly that is installed in the global assembly c ache. To add or change files in the $pshome\Modules directory (%Windir%\Syste m32\WindowsPowerShell\v1.0\Modules), start Windows PowerShell with the "Run as administrator" option. A "session" is an instance of the Windows PowerShell execution environm ent. A session can have one or more session state. By default, a sessio n has only a global session state, but each imported module has its own session state. Session states allow the commands in a module to run wi thout affecting the global session state. The "caller's session state" is the session state into which a module i s imported. Typically, it refers to the global session state, but when a module imports nested modules, the "caller" is the module and the "ca ller's session state" is the module's session state. -------------------------- EXAMPLE 1 -------------------------- C:\PS>New-ModuleManifest Path: C:\Users\User01\Documents\WindowsPowerShell\Modules\Test-Module\Test- Module.psd1 NestedModules[0]: BackgroundModule.psm1 Author: Jinghao Liu CompanyName: Fabrikam, Inc. Copyright: Copyright ¸ 2009 Liu Jinghao. All rights reserved. ModuleToProcess: TestModule.psm1 Description: Cmdlets to find common errors in scripts. TypesToProcess[0]: TestTypes.ps1xml FormatsToProcess[0]: TestFormat.ps1xml RequiredAssemblies[0]: Test.dll FileList[0]: Test-Module.psd1 FileList[1]: Test-Module.psm1 FileList[2]: BackgroundModule.psm1 FileList[3]: TestTypes.ps1xml FileList[4]: TestFormat.ps1xml FileList[5]: Test.dll FileList[6]: TestIcon.ico Description ----------- This command creates a new module manifest. The cmdlet prompts you for the parameters that it requires, including the Path parameter, and creates a ma nifest file in the specified location. The output of this command shows sample responses to the prompts. To use de fault values, press ENTER. The actual prompt, and its handling of quoted and non-quoted phrases, depen ds on the host program in which Windows PowerShell is running. -------------------------- EXAMPLE 2 -------------------------- C:\PS>New-ModuleManifest -PowerShellVersion 1.0 -AliasesToExport JKBC, DRC, TAC Description ----------- This command creates a new module manifest. The command includes parameters that the cmdlet does not require (or prompt for). You can include other ma nifest key values at the prompt. -------------------------- EXAMPLE 3 -------------------------- C:\PS>New-ModuleManifest -RequiredModules FileTransfer,@{ModuleName="Backgr oundModule";GUID="486569a2-2784-48bf-af15-70ba837a64d0";ModuleVersion="3.5" } Description ----------- This example shows how to use the string and hash table formats of the Requ iredModules parameter value. Strings and hash tables can be used in the sam e command. This command commands creates a module manifest for a module that requires the FileTransfer module and a (fictitious) module named "BackgroundModule". The command uses a string format to specify the name of the FileTransfer mo dule and the hash table format to specify the name, a GUID, and a version o f the BackgroundModule. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=141555 Import-Module Get-Module New-Module Remove-Module Export-ModuleMember Test-ModuleManifest about_Modules New-Object NAME New-Object SYNOPSIS Creates an instance of a Microsoft .NET Framework or COM object. SYNTAX New-Object -ComObject <string> [-Strict] [-Property <hashtable>] [<CommonPa rameters>] New-Object [-TypeName] <string> [[-ArgumentList] <Object[]>] [-Property <ha shtable>] [<CommonParameters>] DESCRIPTION The New-Object cmdlet creates an instance of a .NET Framework or COM object . You can specify either the type of a .NET Framework class or a ProgID of a COM object. By default, you type the fully qualified name of a .NET Framewo rk class and the cmdlet returns a reference to an instance of that class. T o create an instance of a COM object, use the ComObject parameter and speci fy the ProgID of the object as its value. PARAMETERS -ArgumentList <Object[]> Specifies a list of arguments to pass to the constructor of the .NET Fr amework class. Separate elements in the list by using commas (,). The a lias for ArgumentList is Args. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -ComObject <string> Specifies the programmatic identifier (ProgID) of the COM object. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Property <hashtable> Sets property values and invokes methods of the new object. Enter a hash table in which the keys are the names of properties or met hods and the values are property values or method arguments. New-Object creates the object and sets each property value and invokes each metho d in the order that they appear in the hash table. If the new object is derived from the PSObject class, and you specify a property that does not exist on the object, New-Object adds the specif ied property to the object as a NoteProperty. If the object is not a PS Object, the command generates a non-terminating error. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Strict [<SwitchParameter>] Specifies that an error should be raised if the COM object that you att empt to create uses an interop assembly. This enables you to distinguis h actual COM objects from .NET Framework objects with COM-callable wrap pers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -TypeName <string> Specifies the fully qualified name of the .NET Framework class. You can not specify both the TypeName parameter and the ComObject parameter. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS Object New-Object returns the object that is created. NOTES New-Object provides the most commonly-used functionality of the VBScrip t CreateObject function. A statement like Set objShell = CreateObject(" Shell.Application") in VBScript can be translated to $objShell = new-ob ject -comobject "Shell.Application" in Windows PowerShell. New-Object expands upon the functionality available in the Windows Scri pt Host environment by making it easy to work with .NET Framework objec ts from the command line and within scripts. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-object -typename System.Version -argumentlist "1.2.3.4" Major Minor Build Revision ----- ----- ----- -------- 1 2 3 4 Description ----------- This command creates a System.Version object using the string "1.2.3.4" as the constructor. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$ie = new-object -comobject InternetExplorer.Application -property @{ navigate2="www.microsoft.com"; visible = $true} Description ----------- This command creates an instance of the COM object that represents the Inte rnet Explorer application. It uses the Property parameter to call the Navig ate2 method and to set the Visible property of the object to $true to make the application visible. This command is the equivalent of the following: $ie = new-object -comobject InternetExplorer.Application $ie.navigate2("www.microsoft.com") $ie.visible = $true -------------------------- EXAMPLE 3 -------------------------- C:\PS>$a=new-object -comobject Word.Application -strict -property @{visible =$true} New-Object : The object written to the pipeline is an instance of the type "Microsoft.Office.Interop.Word.ApplicationClass" from the component's prima ry interop assembly. If this type exposes different members than the IDispa tch members, scripts written to work with this object might not work if the primary interop assembly is not installed. At line:1 char:14 + $a=New-Object < -COM Word.Application -Strict; $a.visible=$true Description ----------- This command demonstrates that specifying the Strict parameter causes the N ew-Object cmdlet to generate a non-terminating error when the COM object th at is created uses an interop assembly. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$objshell = new-object -comobject "Shell.Application" C:\PS> $objshell | get-member C:\PS> $objshell.ToggleDesktop() Description ----------- The command uses the ComObject parameter to create a COM object with the "S hell.Application" ProgID. It stores the resulting object in the $objShell v ariable. The second command pipes the $objShell variable to the Get-Member cmdlet, w hich displays the properties and methods of the COM object. The third command calls the ToggleDesktop method of the object to minimize the open windows on your desktop. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113355 Compare-Object Select-Object Sort-Object ForEach-Object Group-Object Measure-Object Tee-Object Where-Object New-PSDrive NAME New-PSDrive SYNOPSIS Creates a Windows PowerShell drive in the current session. SYNTAX New-PSDrive [-Name] <string> [-PSProvider] <string> [-Root] <string> [-Cred ential <PSCredential>] [-Description <string>] [-Scope <string>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The New-PSDrive cmdlet creates a Windows PowerShell drive that is "mapped" to or associated with a location in a data store, such as a network drive, a directory on the local computer, or a registry key. You can use the Windows PowerShell drives that you create to access data in the associated data store, just like you would do with any mapped drive. Y ou can change locations into the drive (using "set-location", "cd", or "chd ir") and access the contents of the drive (using "get-item", "get-childitem ", or "dir"). However, the Windows PowerShell drives are known only to Windows PowerShell . You cannot access them by using Windows Explorer, Windows Management Inst rumentation (WMI), Component Object Model (COM), or the Microsoft .NET Fram ework, or by using tools such as Net Use. Windows PowerShell drives exist only in the current Windows PowerShell ses sion. To make the drive persistent, you can export the session to which you have added the drive, or you can save a New-PSDrive command in your Window s PowerShell profile. To delete a drive that was created by New-PSDrive, use the Remove-PSDrive c mdlet. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PS Credential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Description <string> Specifies a brief text description of the drive. Type any string. To see the descriptions of all of the Windows PowerShell drives on your system, type "get-psdrive | format name, description". To see the desc ription of a particular Windows PowerShell drives, type "(get-psdrive DriveName>).description". Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies a name for the new drive. You can use any valid string for th e name. You are not limited to drive letters. Windows PowerShell drives names are case-sensitive. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PSProvider <string> Specifies the Windows PowerShell provider that supports drives of this type. For example, if the Windows PowerShell drives is associated with a net work share or file system directory, the Windows PowerShell provider is "FileSystem". If the Windows PowerShell drive is associated with a reg istry key, the provider is "Registry". To see a list of the providers in your Windows PowerShell session, type "get-psprovider". Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Root <string> Specifies the data store location that the Windows PowerShell drive is mapped to. For example, specify a network share (such as \\Server01\Public), a loc al directory (such as C:\Program Files), or a registry key (such as HKL M:\Software\Microsoft). Required? true Position? 3 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Scope <string> Specifies a scope for the drive. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the num ber of scopes, where 0 is the current scope and 1 is its parent). "Loca l" is the default. For more information, see about_Scopes. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.PSDriveInfo NOTES The New-PSDrive cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "get-p sprovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-psdrive -name P -psprovider FileSystem -root \\Server01\Public Name Provider Root ---- -------- ---- P FileSystem \\Server01\Public Description ----------- This command creates a Windows PowerShell drive that functions like a mappe d network drive in Windows. The command creates a Windows PowerShell drive named P: that is mapped to the \\Server01\Public network share. It uses the Name parameter to specify a name for the drive, the PSProvider parameter to specify the Windows PowerShell FileSystem provider, and the Ro ot parameter to specify the network share. When the command completes, the contents of the \\Server01\Public share app ear in the P: drive. To see them, type: "dir p:". -------------------------- EXAMPLE 2 -------------------------- C:\PS>new-psdrive -name MyDocs -psprovider FileSystem -root "C:\Documents a nd Settings\User01\My Documents" -Description "Maps to my My Documents fold er." Name Provider Root ---- -------- ---- MyDocs FileSystem C:\Documents and Settings\User01\My Documents Description ----------- This command creates a Windows PowerShell drive that provides quick access to a local directory. It creates a drive named MyDocs: that is mapped to th e "C:\Documents and Settings\User01\My Documents" directory on the local comp uter. It uses the Name parameter to specify a name for the drive, the PSProvider parameter to specify the Windows PowerShell FileSystem provider, the Root p arameter to specify the path to the My Documents folder, and the Descriptio n parameter to create a description of the drive. When the command completes, the contents of the My Documents folder appear in the MyDocs: drive. To see them, type: "dir mydocs:". -------------------------- EXAMPLE 3 -------------------------- C:\PS>new-psdrive -name MyCompany -psprovider Registry -root HKLM:\Software \MyCompany Name Provider Root ---- -------- ---- MyCompany Registry HKEY_LOCAL_MACHINE\Software\MyCo... Description ----------- This command creates a Windows PowerShell drive that provides quick access to a frequently checked registry key. It creates a drive named MyCompany th at is mapped to the HKLM\Software\MyCompany registry key. It uses the Name parameter to specify a name for the drive, the PSProvider parameter to specify the Windows PowerShell Registry provider, and the Root parameter to specify the registry key. When the command completes, the contents of the MyCompany key appear in the MyCompany: drive. To see them, type: "dir MyCompany:". -------------------------- EXAMPLE 4 -------------------------- C:\PS>new-psdrive -name PsDrive -psprovider FileSystem -root \\Server01\Pub lic C:\PS> $drive = new-object -com wscript.network C:\PS> $drive.MapNetworkDrive("X:", "\\Server01\Public") C PS:\> get-psdrive public, x Name Provider Root ---- -------- ---- PsDrive FileSystem \\Server01\public X FileSystem X:\ C:\PS>get-psdrive psdrive, x | get-member TypeName: System.Management.Automation.PSDriveInfo Name MemberType Definition ---- ---------- ---------- CompareTo Method System.Int32 CompareTo(PSDriveInfo drive), Equals Method System.Boolean Equals(Object obj), GetHashCode Method System.Int32 GetHashCode() ... C:\PS> net use Status Local Remote Network --------------------------------------------------------------------------- X: \\server01\public Microsoft Windows Network C:\PS> get-wmiobject win32_logicaldisk | ft deviceid deviceid -------- C: D: X: C:\PS> get-wmiobject win32_networkconnection LocalName RemoteName ConnectionState Status --------- ---------- --------------- ------ X: \\products\public Disconnected Unavailable Description ----------- This example shows the difference between a Windows drive that is mapped to a network share and a Windows PowerShell drive that is mapped to the same network share. The first command uses the New-PSDrive cmdlet to create a Windows PowerShel l drive called PSDrive: that is mapped to the \\Server01\Public network sha re. The second set of commands uses the New-Object cmdlet to create a Wscript.N etwork COM object and then use its MapNetworkDrive method to map the \\Serv er01\Public network share to the X: drive on the local computer. Now, you can examine the two drives. Using a Get-PSDrive drive command, the drives appear to be the same, although the network share name appears only in the root of the PSDrive: drive. Sending the drive objects to Get-Member shows that they have the same objec t type, System.Management.Automation.PSDriveInfo. However, a "net use" command, a Get-WmiObject command to the Win32_LogicalD isk class, and a Get-WmiObject command to the Win32_NetworkConnection class find only the X: drive that was created by using the Wscript.Network objec t. That is because Windows PowerShell drives are known only to Windows Powe rShell. If you close the Windows PowerShell session and then open a new one, the PS Drive: drive is gone, and the X: drive persists. Therefore, when deciding which method to use to map network drives, conside r how you will use the drive, whether it needs to be persistant, and whethe r the drive needs to be visible to other Windows features. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113357 about_Providers Get-PSDrive Remove-PSDrive New-PSSession NAME New-PSSession SYNOPSIS Creates a persistent connection to a local or remote computer. SYNTAX New-PSSession [[-ComputerName] <string[]>] [-ApplicationName <string>] [-Au thentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>] [-Config urationName <string>] [-Credential <PSCredential>] [-Name <string[]>] [-Por t <int>] [-SessionOption <PSSessionOption>] [-UseSSL] [-ThrottleLimit <int> ] [<CommonParameters>] New-PSSession [[-Session] <PSSession[]>] [-Name <string[]>] [-ThrottleLimit <int>] [<CommonParameters>] New-PSSession [-ConnectionURI] <Uri[]> [-AllowRedirection] [-Authentication {Default | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-CertificateThumbprint <string>] [-ConfigurationName <string>] [-Credential <PSCredential>] [-Name <string[]>] [-SessionOption PSSessionOption>] [-ThrottleLimit <int>] [<CommonParameters>] DESCRIPTION The New-PSSession cmdlet creates a Windows PowerShell session (PSSession) o n a local or remote computer. When you create a PSSession, Windows PowerSh ell establishes a persistent connection to the remote computer. Use a PSSession to run multiple commands that share data, such as a functio n or the value of a variable. To run commands in a PSSession, use the Invok e-Command cmdlet. To use the PSSession to interact directly with a remote c omputer, use the Enter-PSSession cmdlet. For more information, see about_PS Sessions. You can run commands on a remote computer without creating a PSSession by u sing the ComputerName parameters of Enter-PSSession or Invoke-Command. When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used for the interactive session or for a single comman d and is then closed. PARAMETERS -AllowRedirection [<SwitchParameter>] Allows redirection of this connection to an alternate Uniform Resource Identifier (URI). When you use the ConnectionURI parameter, the remote destination can re turn an instruction to redirect to a different URI. By default, Windows PowerShell does not redirect connections, but you can use the AllowRed irection parameter to allow it to redirect the connection. You can also limit the number of times that the connection is redirecte d by setting the MaximumConnectionRedirectionCount property of the $PSS essionOption preference variable, or the MaximumConnectionRedirectionCo unt property of the value of the SessionOption parameter. The default value is 5. For more information, see the description of th e SessionOption parameter, and see New-PSSessionOption. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ApplicationName <string> Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the Co nnectionURI parameter in the command. The default value is the value of the $PSSessionApplicationName prefere nce variable on the local computer. If this preference variable is not defined, the default value is "WSMAN". This value is appropriate for mo st uses. For more information, see about_Preference_Variables. The WinRM service uses the application name to select a listener to ser vice the connection request. The value of this parameter should match t he value of the URLPrefix property of a listener on the remote computer . Required? false Position? named Default value WSMAN Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Authentication <AuthenticationMechanism> Specifies the mechanism that is used to authenticate the user's credent ials. Valid values are "Default", "Basic", "Credssp", "Digest", "Kerb eros", "Negotiate", and "NegotiateWithImplicitCredential". The default value is "Default". CredSSP authentication is available only in Windows Vista, Windows Serv er 2008, and later versions of Windows. For more information about the values of this parameter, see the descri ption of the System.Management.Automation.Runspaces.AuthenticationMecha nism enumeration in the MSDN (Microsoft Developer Network) library at h ttp://go.microsoft.com/fwlink/?LinkID=144382. Caution: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the r emote computer is compromised, the credentials that are passed to it ca n be used to control the network session. Required? false Position? named Default value Default Accept pipeline input? false Accept wildcard characters? false -CertificateThumbprint <string> Specifies the digital public key certificate (X509) of a user account t hat has permission to perform this action. Enter the certificate thumbp rint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the Get-Item or Get-ChildItem comm and in the Windows PowerShell Cert: drive. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Creates a persistent connection (PSSession) to the specified computer. If you enter multiple computer names, New-PSSession creates multiple PS Sessions, one for each computer. The default is the local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more remote computers. To specify the local computer, type th e computer name, "localhost", or a dot (.). When the computer is in a d ifferent domain than the user, the fully qualified domain name is requi red. You can also pipe a computer name (in quotes) to New-PSSession. To use an IP address in the value of the ComputerName parameter, the co mmand must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote compute r must be included in the WinRM TrustedHosts list on the local computer . For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_ Troubleshooting. Note: In Windows Vista and later versions of Windows, to include the l ocal computer in the value of the ComputerName parameter, you must star t Windows PowerShell with the "Run as administrator" option. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -ConfigurationName <string> Specifies the session configuration that is used for the new PSSession. Enter a configuration name or the fully qualified resource Uniform Reso urce Identifier (URI) for a session configuration. If you specify only the configuration name, the following schema URI is prepended: http:// schemas.microsoft.com/powershell. The session configuration for a session is located on the remote comput er. If the specified session configuration does not exist on the remote computer, the command fails. The default value is the value of the $PSSessionConfigurationName prefe rence variable on the local computer. If this preference variable is no t set, the default is Microsoft.PowerShell. For more information, see a bout_Preference_Variables. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -ConnectionURI <Uri[]> Specifies a Uniform Resource Identifier (URI) that defines the connecti on endpoint. The URI must be fully qualified. The format of this string is as follows: <Transport>://<ComputerName>:<Port>/ The default value is as follows: http://localhost:80/WSMAN Valid values for the Transport segment of the URI are HTTP and HTTPS. I f you do not specify a ConnectionURI, you can use the UseSSL, ComputerN ame, Port, and ApplicationName parameters to specify the URI values. If the destination computer redirects the connection to a different URI , Windows PowerShell prevents the redirection unless you use the AllowR edirection parameter in the command. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Domain. com", or enter a PSCredential object, such as one returned by the Get-C redential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Specifies a friendly name for the PSSession. You can use the name to refer to the PSSession when using other cmdlets , such as Get-PSSession and Enter-PSSession. The name is not required t o be unique to the computer or the current session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Port <int> Specifies the network port on the remote computer that is used for thi s command. The default is port 80 (the HTTP port). Before using an alternate port, you must configure the WinRM listener o n the remote computer to listen at that port. Use the following command s to configure the listener: 1. winrm delete winrm/config/listener?Address=*+Transport=HTTP 2. winrm create winrm/config/listener?Address=*+Transport=HTTP @{Port=& quot;<port-number>"} Do not use the Port parameter unless you must. The port setting in the command applies to all computers and sessions in which the command runs . An alternate port setting might prevent the command from running on a ll computers. Required? false Position? named Default value 80 Accept pipeline input? false Accept wildcard characters? false -Session <PSSession[]> Uses the specified PSSession as a model for the new PSSession. This par ameter creates new PSSessions with the same properties as the specified PSSessions. Enter a variable that contains the PSSessions or a command that creates or gets the PSSessions, such as a New-PSSession or Get-PSSession comma nd. The resulting PSSessions have the same computer name, application name, connection URI, port, configuration name, throttle limit, and Secure S ockets Layer (SSL) value as the originals, but they have a different di splay name, ID, and instance ID (GUID). Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -SessionOption <PSSessionOption> Sets advanced options for the session. Enter a SessionOption object th at you create by using the New-PSSessionOption cmdlet. The default values for the options are determined by the value of the $ PSSessionOption preference variable, if it is set. Otherwise, the sessi on uses the system defaults. For a description of the session options, including the default values, see New-PSSessionOption. For information about the $PSSessionOption pr eference variable, see about_Preference_Variables. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Specifies the maximum number of concurrent connections that can be esta blished to run this command. If you omit this parameter or enter a valu e of 0 (zero), the default value, 32, is used. The throttle limit applies only to the current command, not to the sess ion or to the computer. Required? false Position? named Default value 32 Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all Windows PowerShell content transmitted over the network. UseSSL is an additional protection that sends the data acr oss an HTTPS connection instead of an HTTP connection. If you use this parameter, but SSL is not available on the port used fo r the command, the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String, System.URI, System.Management.Automation.Runspaces.PSSession You can pipe a ComputerName (string), ConnectionURI (URI), or Session ( PSSession) object to New-PSSession. OUTPUTS System.Management.Automation.Runspaces.PSSession NOTES This cmdlet uses the Windows PowerShell remoting infrastructure. To use this cmdlet, the local computer and any remote computers must be confi gured for Windows PowerShell remoting. For more information, see about_ Remote_Requirements. In Windows Vista and later versions of Windows, to create a PSSession o n the local computer, you must start Windows PowerShell with the "Run a s administrator" option. When you are finished with the PSSession, use the Remove-PSSession cmdl et to delete the PSSession and release its resources. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$s = new-pssession Description ----------- This command creates a new PSSession on the local computer and saves the PS Session in the $s variable. You can now use this PSSession to run commands on the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$Server01 = new-pssession -ComputerName Server01 Description ----------- This command creates a new PSSession on the Server01 computer and saves it in the $Server01 variable. When creating multiple PSSessions, assign them to variables with useful nam es. This will help you manage the PSSessions in subsequent commands. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$s1, $s2, $s3 = new-session -computername server1,server2,server3 Description ----------- This command creates three new PSSessions, one on each of the computers spe cified by the ComputerName parameter. The command uses the assignment operator (=) to assign the new PSSessions t o an array of variables: $s1, $s2, $s3. It assigns the Server01 PSSession t o $s1, the Server02 PSSession to $s2, and the Server03 PSSession to $s3. When you assign multiple objects to an array of variables, Windows PowerShe ll assigns each object to a variable in the array respectively. If there ar e more objects than variables, all remaining objects are assigned to the la st variable. If there are more variables than objects, the remaining variab les are empty (null). -------------------------- EXAMPLE 4 -------------------------- C:\PS>new-pssession -computername Server01 -port 8081 -useSSL -Configuratio nName E12 Description ----------- This command creates a new PSSession on the Server01 computer that connects to server port 8081 and uses the SSL protocol. The new PSSession uses an a lternate session configuration called "E12". Before setting the port, you must configure the WinRM listener on the remot e computer to listen on port 8081. For more information, see the descriptio n of the Port parameter. -------------------------- EXAMPLE 5 -------------------------- C:\PS>new-pssession -session $s -credential domain01\user01 Description ----------- This command creates a new PSSession with the same properties as an existin g PSSession. You can use this command format when the resources of an exist ing PSSession are exhausted and a new PSSession is needed to offload some o f the demand. The command uses the Session parameter of New-PSSession to specify the PSSe ssion saved in the $s variable. It uses the credentials of the Domain1\Admi n01 user to complete the command. -------------------------- EXAMPLE 6 -------------------------- C:\PS>$global:s = new-pssession -computername server1.domain44.corpnet.fabr ikam.com -credential domain01\admin01 Description ----------- This example shows how to create a PSSession with a global scope on a compu ter in a different domain. By default, PSSessions created at the command line are created with local s cope and PSSessions created in a script have script scope. To create a PSSession with global scope, create a new PSSession and then st ore the PSSession in a variable that is cast to a global scope. In this cas e, the $s variable is cast to a global scope. The command uses the ComputerName parameter to specify the remote computer. Because the computer is in a different domain than the user account, the f ull name of the computer is specified along with the credentials of the use r. -------------------------- EXAMPLE 7 -------------------------- C:\PS>$rs = get-content c:\test\servers.txt | new-PSsession -throttleLimit 50 Description ----------- This command creates a PSSession on each of the 200 computers listed in the Servers.txt file and it stores the resulting PSSession in the $rs variable . The PSSessions have a throttle limit of 50. You can use this command format when the names of computers are stored in a database, spreadsheet, text file, or other text-convertible format. -------------------------- EXAMPLE 8 -------------------------- C:\PS>$s = new-PSSession -URI http://Server01:91/NewSession -credential dom ain01\user01 Description ----------- This command creates a PSSession on the Server01 computer and stores it in the $s variable. It uses the URI parameter to specify the transport protoco l, the remote computer, the port, and an alternate session configuration. I t also uses the Credential parameter to specify a user account with permiss ion to create a session on the remote computer. -------------------------- EXAMPLE 9 -------------------------- C:\PS>$s = new-PSSession -computername (import-csv servers.csv) -credential domain01\admin01 -throttlelimit 16 C:\PS> invoke-command -session $s -scriptblock {get-process powershell} -As Job Description ----------- These commands create a set of PSSessions and then run a background job in each of the PSSessions. The first command creates a new PSSession on each of the computers listed i n the Servers.csv file. It uses the New-PSSession cmdlet to create the PSSe ssion. The value of the ComputerName parameter is a command that uses the I mport-Csv cmdlet to import the Servers.csv file and read its contents. The command uses the Credential parameter to create the PSSessions with the permission of a domain administrator, and it uses the ThrottleLimit parame ter to limit the command to 16 concurrent connections. The command saves th e PSSessions in the $s variable. The second command uses the AsJob parameter of Invoke-Command to start a ba ckground job that runs a "Get-Process PowerShell" command in each of the PS Sessions in $s. For more information about background jobs, see about_Jobs and about_Remote _Jobs. -------------------------- EXAMPLE 10 -------------------------- C:\PS>new-PSSession -ConnectionURI https://management.exchangelabs.com/Mana gement Description ----------- This command creates a new PSSession that connects to a computer that is sp ecified by a URI instead of a computer name. -------------------------- EXAMPLE 11 -------------------------- C:\PS>$so = New-WSManSessionOption -SkipCACheck PS C:\> new-pssession -ConnectionUri https://management.exchangelabs.com/Ma nagement -SessionOption $so -credential server01\admin01 Description ----------- This example shows how to create and use a SessionOption parameter. The first command uses the New-WSManSessionOption cmdlet to create a sessio n option. It saves the resulting SessionOption object in the $so parameter. The second command uses the option in a new session. The command uses the N ew-PSSession cmdlet to create a new session. The value of the SessionOption parameter is the SessionOption object in the $so variable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135237 about_PSSessions about_Remote Get-PSSession Remove-PSSession Enter-PSSession Exit-PSSession Invoke-Command New-PSSessionOption NAME New-PSSessionOption SYNOPSIS Creates an object that contains advanced options for a PSSession. SYNTAX New-PSSessionOption [-ApplicationArguments <PSPrimitiveDictionary>] [-Cance lTimeOut <int>] [-Culture <CultureInfo>] [-IdleTimeOut <int>] [-MaximumRece ivedDataSizePerCommand <int>] [-MaximumReceivedObjectSize <int>] [-MaximumR edirection <int>] [-NoCompression] [-NoEncryption] [-NoMachineProfile] [-Op enTimeOut <int>] [-OperationTimeOut <int>] [-ProxyAccessType {None | IEConf ig | WinHttpConfig | AutoDetect | NoProxyServer}] [-ProxyAuthentication {De fault | Basic | Negotiate | NegotiateWithImplicitCredential | Credssp | Dig est | Kerberos}] [-ProxyCredential <PSCredential>] [-SkipCACheck] [-SkipCNC heck] [-SkipRevocationCheck] [-UICulture <CultureInfo>] [-UseUTF16] [<Commo nParameters>] DESCRIPTION The New-PSSessionOption cmdlet creates an object that contains advanced opt ions for a PSSession. You can use the object as the value of the SessionOpt ion parameter of cmdlets that create a PSSession, such as New-PSSession, En ter-PSSession, and Invoke-Command. Without parameters, New-PSSessionOption generates an object that contains t he default values for all of the options. Because all of the properties can be edited, you can use the resulting object as a template, and create stan dard option objects for your enterprise. PARAMETERS -ApplicationArguments <PSPrimitiveDictionary> Specifies a hash table that is sent directly to the session configurati on without interpretation. This hash table is available to the session configuration as a property of the PSSenderInfo class. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -CancelTimeOut <int> Determines how long Windows PowerShell waits for a cancel operation (CT RL + C) to complete before terminating it. Enter a value in millisecon ds. The default value is 60000 (one minute). A value of 0 (zero) means no t imeout; the command continues indefinitely. Required? false Position? named Default value 60000 Accept pipeline input? false Accept wildcard characters? false -Culture <CultureInfo> Specifies the culture to use for the PSSession. Enter a culture name in <languagecode2>-<country/regioncode2> format, such as "ja-jP", a vari able that contains a CultureInfo object, or a command that gets a Cultu reInfo object, such as "get-culture". The default value is $null, and the culture that is set in the operatin g system when the PSSession is created is used in the PSSession. Required? false Position? named Default value Current culture Accept pipeline input? false Accept wildcard characters? false -IdleTimeOut <int> Determines how long the PSSession stays open if the remote computer doe s not receive any communication from the local computer, including the heartbeat signal. When the interval expires, the PSSession closes. Enter a value in milliseconds. The default value is 240000 (4 minutes). The minimum value is 60000 (1 minute). If both the local and remote computers specify an idle timeout value, t he PSSession uses the shorter timeout value. The local computer can set an idle timeout value by using this parameter or by setting an idle ti meout in the $PSSessionOption preference variable. The remote computer can specify an idle timeout value in the WS-Management configuration (W SMAN:\localhost\shell\idletimeout). Required? false Position? named Default value 240000 Accept pipeline input? false Accept wildcard characters? false -MaximumReceivedDataSizePerCommand <int> Specifies the maximum number of bytes that the local computer can recei ve from the remote computer in a single command. Enter a value in bytes . By default, there is no data size limit. This option is designed to protect the resources on the client computer . Required? false Position? named Default value No limit Accept pipeline input? false Accept wildcard characters? false -MaximumReceivedObjectSize <int> Specifies the maximum size of an object that the local computer can rec eive from the remote computer. Enter a value in bytes. By default, ther e is no data size limit. This option is designed to protect the resources on the client computer . Required? false Position? named Default value No limit Accept pipeline input? false Accept wildcard characters? false -MaximumRedirection <int> Determines how many times Windows PowerShell redirects a connection to an alternate Uniform Resource Identifier (URI) before the connection fa ils. The default value is 5. A value of 0 (zero) prevents all redirecti on. This option is used in the PSSession only when the AllowRedirection par ameter is used in the command that creates the PSSession. Required? false Position? named Default value 5 Accept pipeline input? false Accept wildcard characters? false -NoCompression [<SwitchParameter>] Turns off packet compression in the PSSession. Compression uses more pr ocessor cycles, but it makes transmission faster. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -NoEncryption [<SwitchParameter>] Turns off data encryption. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -NoMachineProfile [<SwitchParameter>] Prevents loading the user's Windows user profile. As a result, the PSSe ssion might be created faster, but user-specific registry settings, ite ms such as environment variables, and certificates are not available in the PSSession. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -OpenTimeOut <int> Determines how long the client computer waits for the session connectio n to be established. When the interval expires, the command to establis h the connection fails. Enter a value in milliseconds. The default value is 180000 (3 minutes). A value of 0 (zero) means no t ime-out; the command continues indefinitely. Required? false Position? named Default value 180000 Accept pipeline input? false Accept wildcard characters? false -OperationTimeOut <int> Determines the maximum time that any operation in the PSSession can run . When the interval expires, the operation fails. Enter a value in mill iseconds. The default value is 180000 (3 minutes). A value of 0 (zero) means no t ime-out; the operation continues indefinitely. Required? false Position? named Default value 180000 Accept pipeline input? false Accept wildcard characters? false -ProxyAccessType <ProxyAccessType> Determines which mechanism is used to resolve the host name. Valid valu es are IEConfig, WinHttpConfig, AutoDetect, NoProxyServer and None. The default value is None. For information about the values of this parameter, see the description of the System.Management.Automation.Remoting.ProxyAccessType enumerati on in the MSDN (Microsoft Developer Network) Library at http://go.micro soft.com/fwlink/?LinkId=144756. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -ProxyAuthentication <AuthenticationMechanism> Specifies the authentication method that is used for proxy resolution. Valid values are Basic, Digest, and Negotiate. The default value is Neg otiate. For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in the MSDN library at http://go.microsoft.com/fwlink/?Link ID=144382. Required? false Position? named Default value Negotiate Accept pipeline input? false Accept wildcard characters? false -ProxyCredential <PSCredential> Specifies the credentials to use for proxy authentication. Enter a vari able that contains a PSCredential object or a command that gets a PSCre dential object, such as Get-Credential. If this option is not set, no c redentials are specified. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -SkipCACheck [<SwitchParameter>] Specifies that when connecting over HTTPS, the client does not validate that the server certificate is signed by a trusted certificate authori ty (CA). Use this option only when the remote computer is trusted by using anoth er mechanism, such as when the remote computer is part of a network tha t is physically secure and isolated, or the remote computer is listed a s a trusted host in a WinRM configuration. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -SkipCNCheck [<SwitchParameter>] Specifies that the certificate common name (CN) of the server does not need to match the hostname of the server. This option is used only in r emote operations that use the HTTPS protocol. Use this option only for trusted computers. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -SkipRevocationCheck [<SwitchParameter>] Does not validate the revocation status of the server certificate. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -UICulture <CultureInfo> Specifies the UI culture to use for the PSSession. Enter a culture name in <languagecode2>-<country/regioncode2> format, s uch as "ja-jP", a variable that contains a CultureInfo object, or a co mmand that gets a CultureInfo object, such as Get-Culture. The default value is $null, and the UI culture that is set in the opera ting system when the PSSession is created is used in the PSSession. Required? false Position? named Default value Current UI culture Accept pipeline input? false Accept wildcard characters? false -UseUTF16 [<SwitchParameter>] Encode the request in UTF16 format rather than UTF8 format. Required? false Position? named Default value False (UTF8 encoding) Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.Automation.Remoting.PSSessionOption NOTES If the SessionOption parameter is not used in a command to create a PSS ession, the session options are determined by the property values of th e $PSSessionOption preference variable, if it is set. For more informat ion about the $PSSessionOption variable, see about_Preference_Variables . -------------------------- EXAMPLE 1 -------------------------- C:\PS>New-PSSessionOption MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False ProxyAccessType : IEConfig ProxyAuthentication : Negotiate ProxyCredential : SkipCACheck : False SkipCNCheck : False SkipRevocationCheck : False OperationTimeout : 00:03:00 NoEncryption : False UseUTF16 : False Culture : UICulture : MaximumReceivedDataSizePerCommand : MaximumReceivedObjectSize : ApplicationArguments : OpenTimeout : 00:03:00 CancelTimeout : 00:01:00 IdleTimeout : 00:04:00 Description ----------- This command creates a session option object with all of the default values . -------------------------- EXAMPLE 2 -------------------------- C:\PS>$pso = new-pssessionoption -Culture "fr-fr" -MaximumReceivedObjectSiz e 10MB C:\PS> new-pssession -computerName Server01 -SessionOption $pso Description ----------- This example shows how to use a session option object to configure a sessio n. The first command creates a new session option object and saves it in the v alue of the $pso variable. The second command uses the New-PSSession cmdlet to create a PSSession on t he Server01 remote computer. The command uses the session option object in the value of the $pso variable as the value of the SessionOption parameter of the command. -------------------------- EXAMPLE 3 -------------------------- C:\PS>enter-pssession -computername Server01 -sessionOption (new-pssessiono ption -noEncryption -noCompression) Description ----------- This command uses the Enter-PSSession cmdlet to start an interactive sessio n with the Server01 computer. The value of the SessionOption parameter is a New-PSSessionOption command with the NoEncryption and NoCompression switch parameters. The New-PSSessionOption command is enclosed in parentheses to make sure tha t it runs before the Enter-PSSession command. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$a = new-pssessionoption MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False ProxyAccessType : IEConfig ProxyAuthentication : Negotiate ProxyCredential : SkipCACheck : False SkipCNCheck : False SkipRevocationCheck : False OperationTimeout : 00:03:00 NoEncryption : False UseUTF16 : False Culture : UICulture : MaximumReceivedDataSizePerCommand : MaximumReceivedObjectSize : ApplicationArguments : OpenTimeout : 00:03:00 CancelTimeout : 00:01:00 IdleTimeout : 00:04:00 C:\PS> $a.UICulture = (get-UICulture) C:\PS> $a.OpenTimeout = (new-timespan -minutes 4) C:\PS> $a.MaximumConnectionRedirectionCount = 1 C:\PS> $a MaximumConnectionRedirectionCount : 1 NoCompression : False NoMachineProfile : False ProxyAccessType : IEConfig ProxyAuthentication : Negotiate ProxyCredential : SkipCACheck : False SkipCNCheck : False SkipRevocationCheck : False OperationTimeout : 00:03:00 NoEncryption : False UseUTF16 : False Culture : UICulture : en-US MaximumReceivedDataSizePerCommand : MaximumReceivedObjectSize : ApplicationArguments : OpenTimeout : 00:04:00 CancelTimeout : 00:01:00 IdleTimeout : 00:04:00 Description ----------- This example demonstrates that you can edit the session option object. All properties have read/write values. Use this method to create a standard session object for your enterprise, an d then create customized versions of it for particular uses. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$PSSessionOption = New-PSSessionOption -OpenTimeOut 120000 Description ----------- This command creates a $PSSessionOption preference variable. When the $PSSessionOption preference variable exists in the session, it est ablishes default values for options in the PSSessions that are created by u sing the New-PSSession, Enter-PSSession, and Invoke-Command cmdlets. To make the $PSSessionOption variable available in all sessions, add it to your Windows PowerShell session and to your Windows PowerShell profile. For more information about the $PSSessionOption variable, see about_Prefere nce_Variables. For more information about profiles, see about_Profiles. -------------------------- EXAMPLE 6 -------------------------- C:\PS>$skipCN = new-pssessionoption -SkipCNCheck C:\PS> new-pssession -computername 171.09.21.207 -UseSSL -credential domain 01\user01 -sessionOption $skipCN Description ----------- This example shows how to use a SessionOption object to fulfill the require ments for a remote session configuration. The first command uses the New-PSSessionOption cmdlet to create a session o ption object with the SkipCNCheck property. The command saves the resulting session object in the $skipCN variable. The second command uses the New-PSSession cmdlet to create a new PSSession on a remote computer. The $skipCN check variable is used in the value of th e SessionOption parameter. Because the computer is identified by its IP address, the value of the Comp uterName parameter does not match any of the common names in the certificat e used for Secure Sockets Layer (SSL). As a result, the SkipCNCheck option is required. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144305 Enter-PSSession New-PSSession Invoke-Command New-Service NAME New-Service SYNOPSIS Creates a new Windows service. SYNTAX New-Service [-Name] <string> [-BinaryPathName] <string> [-Credential <PSCre dential>] [-DependsOn <string[]>] [-Description <string>] [-DisplayName <st ring>] [-StartupType {Automatic | Manual | Disabled}] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The New-Service cmdlet creates a new entry for a Windows service in the reg istry and in the service database. A new service requires an executable fil e that executes during the service. The parameters of this cmdlet let you set the display name, description, st artup type, and dependencies of the service. PARAMETERS -BinaryPathName <string> Specifies the path to the executable file for the service. This paramet er is required. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Ty pe a user name, such as "User01" or "Domain01\User01". Or, enter a PSCr edential object, such as one from the Get-Credential cmdlet. If you typ e a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DependsOn <string[]> Specifies the names of other services upon which the new service depend s. To enter multiple service names, use a comma to separate the names. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Description <string> Specifies a description of the service. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DisplayName <string> Specifies a display name for the service. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies the name of the service. This parameter is required. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -StartupType <ServiceStartMode> Sets the startup type of the service. "Automatic" is the default. Valid values are: -- Manual: The service is started only manually, by a user (using the Service Control Manager) or by an application. -- Automatic: The service is to be started (or was started) by the op erating system, at system start-up. If an automatically started service depends on a manually started service, the manually started service is also started automatically at system startup. -- Disabled: The service is disabled and cannot be started by a user or application. Required? false Position? named Default value Automatic Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.ServiceProcess.ServiceController New-Service returns an object that represents the new service. NOTES To run this cmdlet on Windows Vista and later versions of Windows, star t Windows PowerShell with the "Run as administrator" option. -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-service -name TestService -binaryPathName "C:\WINDOWS\System32\sv chost.exe -k netsvcs" Description ----------- This command creates a new service named "TestService". -------------------------- EXAMPLE 2 -------------------------- C:\PS>new-service -name TestService -path "C:\WINDOWS\System32\svchost.exe -k netsvcs" -dependson NetLogon -displayName "Test Service" -StartupType Ma nual -Description "This is a test service." Description ----------- This command creates a new service named "TestService". It uses the paramet ers of the New-Service cmdlet to specify a description, startup type, and d isplay name for the new service. To specify the BinaryPathName parameter, the command uses the Path paramete r alias. You can also use "-bpn". -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-wmiobject win32_service -filter "name='testservice'" ExitCode : 0 Name : testservice ProcessId : 0 StartMode : Auto State : Stopped Status : OK Description ----------- This command uses the Get-WmiObject cmdlet to get the Win32_Service object for the new service. This object includes the start mode and the service de scription. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113359 Get-Service Start-Service Stop-Service Restart-Service Resume-Service Set-Service Suspend-Service New-TimeSpan NAME New-TimeSpan SYNOPSIS Creates a TimeSpan object. SYNTAX New-TimeSpan [[-Start] <DateTime>] [[-End] <DateTime>] [<CommonParameters>] New-TimeSpan [-Days <int>] [-Hours <int>] [-Minutes <int>] [-Seconds [<CommonParameters>] DESCRIPTION The New-TimeSpan cmdlet creates a TimeSpan object that represents a time. i nterval You can use a TimeSpan object to add or subtract time from DateTime objects. Without parameters, a "New-Timespan" command returns a timespan object that represents a time interval of zero. PARAMETERS -Days <int> Indicates the days in the time span. The default is 0. Required? false Position? named Default value 0 Accept pipeline input? false Accept wildcard characters? false -End <DateTime> Indicates the end of a time span. The default is the current date and t ime. Required? false Position? 2 Default value Current date and time Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Hours <int> Indicates the hours in the time span. The default is zero. Required? false Position? named Default value 0 Accept pipeline input? false Accept wildcard characters? false -Minutes <int> Indicates the minutes in the time span. The default is 0. Required? false Position? named Default value 0 Accept pipeline input? false Accept wildcard characters? false -Seconds <int> Indicates the length of the time span in seconds. The default is 0. Required? false Position? named Default value 0 Accept pipeline input? false Accept wildcard characters? false -Start <DateTime> Indicates the start of a time span. Enter a string that represents the date and time, such as "3/15/09" or a DateTime object, such as one from a Get-Date command. The default is the current date and time. Required? false Position? 1 Default value Current date and time Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.DateTime You can pipe a DateTime object that represents that start time to New-T imeSpan. OUTPUTS System.Timespan New-TimeSpan returns an object that represents the time span. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$timespan = new-timespan -hour 1 -minute 25 Description ----------- This command creates a TimeSpan object with a duration of 1 hour and 25 min utes and stores it in a variable named $timespan. It displays a representat ion of the TimeSpan object. -------------------------- EXAMPLE 2 -------------------------- C:\PS>new-timespan -end (get-date -year 2010 -month 1 -day 1) Description ----------- This example creates a new TimeSpan object that represents the interval bet ween the time that the command is run and January 1, 2010. This command does not require the Start parameter, because the default valu e of the Start parameter is the current date and time. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$90days = new-timespan -days 90 C:\PS> (get-date) + $90days Description ----------- These commands return the date that is 90 days after the current date. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113360 Set-Date Get-Date New-Variable NAME New-Variable SYNOPSIS Creates a new variable. SYNTAX New-Variable [-Name] <string> [[-Value] <Object>] [-Description <string>] [ -Force] [-Option {None | ReadOnly | Constant | Private | AllScope}] [-PassT hru] [-Scope <string>] [-Visibility {Public | Private}] [-Confirm] [-WhatIf ] [<CommonParameters>] DESCRIPTION The New-Variable cmdlet creates a new variable in Windows PowerShell. You c an assign a value to the variable while creating it or assign or change the value after it is created. You can use the parameters of New-Variable to set the properties of the var iable (such as those that create read-only or constant variables), set the scope of a variable, and determine whether variables are public or private. Typically, you create a new variable by typing the variable name and its va lue, such as "$var = 3", but you can use the New-Variable cmdlet to use its parameters. PARAMETERS -Description <string> Specifies a description of the variable. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows you to create a new variable with the same name as an existing r ead-only variable. By default, you can overwrite a variable unless the variable has an opt ion value of ReadOnly or Constant. For more information, see the Option parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies a name for the new variable. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Option <ScopedItemOptions> Sets the value of the Options property of the new variable. Valid values are: -- None: Sets no options. ("None" is the default.) -- ReadOnly: The value of the variable cannot be changed except by usin g the Force parameter. You can use Remove-Variable to delete the variab le. -- Constant: The variable cannot be deleted, and its properties cannot be changed. "Constant" is available only when you are creating an alias . You cannot change the option of an existing variable to "Constant". -- Private: The variable is available only within the scope specified b y the Scope parameter. It is inherited by child scopes. (This value is not related to the "Private" value of the Visibility parameter.) -- AllScope: The variable is copied to any new scopes that are created. To see the Options property of the variables, type "get-variable| forma t-table -property name, options -autosize". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the new variable. By default, this cmdle t does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Scope <string> Determines the scope of the new variable. Valid values are "Global", "L ocal", or "Script", or a number relative to the current scope (0 throug h the number of scopes, where 0 is the current scope and 1 is its paren t). "Local" is the default. For more information, see about_Scopes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Value <Object> Specifies the initial value of the variable. Required? false Position? 2 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Visibility <SessionStateEntryVisibility> Determines whether the variable is visible outside of the session in wh ich it was created. This parameter is designed for use in scripts and commands that will be delivered to other users. Valid values are: -- Public: The variable is visible. ("Public" is the default.) -- Private: The variable is not visible. When a variable is private, it does not appear in lists of variables, s uch as those returned by Get-Variable, or in displays of the Variable: drive. Commands to read or change the value of a private variable retur n an error. However, the user can run commands that use a private varia ble if the commands were written in the session in which the variable w as defined. Required? false Position? named Default value Public Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe a value to New-Variable. OUTPUTS None or System.Management.Automation.PSVariable When you use the PassThru parameter, New-Variable generates a System.Ma nagement.Automation.PSVariable object representing the new variable. Ot herwise, this cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>new-variable days Description ----------- This command creates a new variable named "days". It has no value immediate ly following the command. -------------------------- EXAMPLE 2 -------------------------- C:\PS>new-variable zipcode -value 98033 Description ----------- This command creates a variable named "zipcode" and assigns it the value "9 8033". -------------------------- EXAMPLE 3 -------------------------- C:\PS>new-variable -name max -value 256 -option readonly new-variable -name max -value 1024 new-variable -name max -value 1024 -force C:\PS> new-variable -name max -value 256 -option readonly C:\PS> new-variable -name max -value 1024 New-Variable : A variable with name 'max' already exists. At line:1 char:13 + new-variable < -name max -value 1024 C:\PS> new-variable -name max -value 1024 -force Description ----------- This example shows how to use the ReadOnly option of New-Variable to protec t a variable from being overwritten. The first command creates a new variable named Max and sets its value to "2 56". It uses the Option parameter with a value of ReadOnly. The second command tries to create a second variable with the same name. Th is command returns an error, because the read-only option is set on the var iable. The third command uses the Force parameter to override the read-only protec tion on the variable. In this case, the command to create a new variable wi th the same name succeeds. -------------------------- EXAMPLE 4 -------------------------- C:\PS>new-variable -name counter -visibility private #Effect of private variable in a module. C:\PS> get-variable c* Name Value ---- ----- Culture en-US ConsoleFileName ConfirmPreference High CommandLineParameters {} C:\PS> $counter "Cannot access the variable '$counter' because it is a private variable" C:\PS> Get-Counter Name Value ---- ----- Counter1 3.1415 ... Description ----------- This command demonstrates the behavior of a private variable in a module. T he module contains the Get-Counter cmdlet, which has a private variable nam ed "Counter". The command uses the Visibility parameter with a value of "Pr ivate" to create the variable. The sample output shows the behavior of a private variable. The user who ha s loaded the module cannot view or change the value of the Counter variable , but the Counter variable can be read and changed by the commands in the m odule. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113361 Get-Variable Set-Variable Remove-Variable Clear-Variable New-WebServiceProxy NAME New-WebServiceProxy SYNOPSIS Creates a Web service proxy object that lets you use and manage the Web ser vice in Windows PowerShell. SYNTAX New-WebServiceProxy [-URI] <Uri> [[-Class] <string>] [[-Namespace] <string> ] [<CommonParameters>] New-WebServiceProxy [-URI] <Uri> [[-Class] <string>] [[-Namespace] <string> ] [-Credential <PSCredential>] [<CommonParameters>] New-WebServiceProxy [-URI] <Uri> [[-Class] <string>] [[-Namespace] <string> ] [-UseDefaultCredential] [<CommonParameters>] DESCRIPTION The New-WebServiceProxy cmdlet lets you use a Web service in Windows PowerS hell. The cmdlet connects to a Web service and creates a Web service proxy object in Windows PowerShell. You can use the proxy object to manage the We b service. A Web service is an XML-based program that exchanges data over a network, p articularly over the Internet. The Microsoft .NET Framework provides Web se rvice proxy objects that represent the Web service as a .NET Framework obje ct. PARAMETERS -Class <string> Specifies a name for the proxy class that the cmdlet creates for the We b service. The value of this parameter is used with the Namespace param eter to provide a fully qualified name for the class. The default value is generated from the URI. Required? false Position? 2 Default value Generated from the URI Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. This is an alternative to using the UseD efaultCredential parameter. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PS Credential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Namespace <string> Specifies a namespace for the new class. The value of this parameter is used with the value of the Class paramet er to generate a fully qualified name for the class. The default value is Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes plus a type that is generated from the URI. You can set the value of the Namespace parameter so that you can access multiple Web services with the same name. Required? false Position? 3 Default value Microsoft.PowerShell.Commands.NewWebservic eProxy.AutogeneratedTypes Accept pipeline input? false Accept wildcard characters? false -URI <Uri> Specifies the URI of the Web service. Enter a URI or the path and file name of a file that contains a service description. The URI must refer to an .asmx page or to a page that returns a service description. To return a service description of a Web service that was created by using ASP.NET, append "?WSDL" to the URL of the Web service (for example, http://www.contoso.com/MyWebService.asmx?WSDL). Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -UseDefaultCredential [<SwitchParameter>] Sets the UseDefaultCredential parameter in the resulting proxy object t o True. This is an alternative to using the Credential parameter. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not take input from the pipeline. OUTPUTS A Web service proxy object The namespace and class of the object are determined by the parameters of the command. The default is generated from the input Uniform Resourc e Identifier (URI). NOTES New-WebServiceProxy uses the System.Net.WebClient class to load the spe cified Web service. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$zip = New-WebServiceProxy -uri http://www.webservicex.net/uszip.asmx ?WSDL Description ----------- This command uses the New-WebServiceProxy command to create a .NET Framewor k proxy of the US Zip Web service in Windows PowerShell. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$URI = "http://www.webservicex.net/uszip.asmx?WSDL" C:\PS> $zip = New-WebServiceProxy -uri $URI -namespace WebServiceProxy -cla ss ZipClass Description ----------- This command uses the New-WebServiceProxy cmdlet to create a .NET Framework proxy of the US Zip Web service. The first command stores the URI of the Web service in the $URI variable. The second command creates the Web service proxy. The command uses the URI parameter to specify the URI and the Namespace and Class parameters to spec ify the namespace and class of the object. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$zip | get-member -type method TypeName: WebServiceProxy.USZip Name MemberType Definition ---- ---------- ---------- Abort Method System.Void Abort( BeginGetInfoByAreaCode Method System.IAsyncResul BeginGetInfoByCity Method System.IAsyncResul BeginGetInfoByState Method System.IAsyncResul BeginGetInfoByZIP Method System.IAsyncResul CreateObjRef Method System.Runtime.Rem Discover Method System.Void Discov Dispose Method System.Void Dispos EndGetInfoByAreaCode Method System.Xml.XmlNode EndGetInfoByCity Method System.Xml.XmlNode EndGetInfoByState Method System.Xml.XmlNode EndGetInfoByZIP Method System.Xml.XmlNode Equals Method System.Boolean Equ GetHashCode Method System.Int32 GetHa GetInfoByAreaCode Method System.Xml.XmlNode GetInfoByCity Method System.Xml.XmlNode GetInfoByState Method System.Xml.XmlNode GetInfoByZIP Method System.Xml.XmlNode GetLifetimeService Method System.Object GetL GetType Method System.Type GetTyp InitializeLifetimeService Method System.Object Init ToString Method System.String ToSt Description ----------- This command uses the Get-Member cmdlet to display the methods of the Web s ervice proxy object in the $zip variable. We will use these methods in the following example. Notice that the TypeName of the proxy object, WebServiceProxy, reflects the namespace and class names that were specified in the previous example. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$zip.getinfobyzip(20500).table CITY : Washington STATE : DC ZIP : 20500 AREA_CODE : 202 TIME_ZONE : E Description ----------- This command uses the Web service proxy stored in the Zip variable. The com mand uses the GetInfoByZip method of the proxy and its Table property. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135238 New-Service New-WSManInstance NAME New-WSManInstance SYNOPSIS Creates a new instance of a management resource. SYNTAX New-WSManInstance [-ApplicationName <string>] [-ComputerName <string>] [-Cr edential <PSCredential>] [-Port <int>] [-UseSSL] [-SelectorSet] <hashtable> -ResourceURI <Uri> [-AuthenticationMechanism <AuthenticationMechanism>] [- SessionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>] New-WSManInstance [-ConnectionURI <Uri>] [-SelectorSet] <hashtable> -Resour ceURI <Uri> [-AuthenticationMechanism <AuthenticationMechanism>] [-SessionO ption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>] DESCRIPTION The New-WSManInstance cmdlet creates a new instance of a management resourc e. It uses a resource URI and a value set or input file to create the new i nstance of the management resource. This cmdlet uses the WinRM connection/transport layer to create the managem ent resource instance. PARAMETERS -ApplicationName <string> Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for t he remote endpoint is in the following format: <transport>://<server>:<port>/ For example: http://server01:8080/WSMAN Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is desi gned to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hos ts Web Services for Management (WS-Management) for efficiency. Required? false Position? named Default value wsman Accept pipeline input? false Accept wildcard characters? false -AuthenticationMechanism <AuthenticationMechanism> Specifies the authentication mechanism to be used at the server. Possib le values are: - Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - Default : Use the authentication method implemented by the WS-Managem ent protocol. This is the default. - Digest: Digest is a challenge-response scheme that uses a server-spec ified data string for the challenge. - Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates. - Negotiate: Negotiate is a challenge-response scheme that negotiates w ith the server or proxy to determine the scheme to use for authenticati on. For example, this parameter value allows negotiation to determine w hether the Kerberos protocol or NTLM is used. - CredSSP: Use Credential Security Service Provider (CredSSP) authentic ation, which allows the user to delegate credentials. This option is de signed for commands that run on one remote computer but collect data fr om or run additional commands on other remote computers. Caution: CredSSP delegates the user's credentials from the local comput er to a remote computer. This practice increases the security risk of t he remote operation. If the remote computer is compromised, when creden tials are passed to it, the credentials can be used to control the netw ork session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name must be used. You can pipe a v alue for this parameter to the cmdlet. Required? false Position? named Default value localhost Accept pipeline input? false Accept wildcard characters? false -ConnectionURI <Uri> Specifies the connection endpoint. The format of this string is: <Transport>://<Server>:<Port>/ The following string is a properly formatted value for this parameter: http://Server01:8080/WSMAN The URI must be fully qualified. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or "User@Domain.com". Or, enter a PSCredential object, s uch as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -File <File> Specifies the path of a file that is used to create a management resour ce. You specify the management resource by using the ResourceURI parame ter and the SelectorSet parameter . For example, the following command uses the File parameter: invoke-wsmanaction -action stopservice -resourceuri wmicimv2/Win32_Serv ice -SelectorSet @{Name="spooler"} -File c:\input.xml -authentication d efault This command calls the StopService method [descriptor] on the Spooler service by using input from a file. The file, Input.xml, contains the f ollowing content: <p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1 /wmi/root/cimv2/Win32_Service"/> Required? Position? named Default value Accept pipeline input? false Accept wildcard characters? false -OptionSet <hashtable> Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be spec ified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: -OptionSet @{a=1;b=2;c=3} Required? Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Port <int> Specifies the port to use when the client connects to the WinRM service . When the transport is HTTP, the default port is 80. When the transpor t is HTTPS, the default port is 443. When you use HTTPS as the transpor t, the value of the ComputerName parameter must match the server's cert ificate common name (CN). However, if the SkipCNCheck parameter is spec ified as part of the SessionOption parameter, then the certificate comm on name of the server does not have to match the host name of the serve r. The SkipCNCheck parameter should be used only for trusted computers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ResourceURI <Uri> Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, suc h as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Log icalDisk http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSenso r Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SelectorSet <hashtable> Specifies a set of value pairs that are used to select particular manag ement resource instances. The SelectorSet parameter is used when more t han one instance of the resource exists. The value of the SelectorSet p arameter must be a hash table. The following example shows how to enter a value for this parameter: -SelectorSet @{Name="WinRM";ID="yyy"} Required? true Position? 2 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -SessionOption <hashtable> Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOpt ion cmdlet. For more information about the options that are available, see New-WSManSessionOption. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Specifies that the Secure Sockets Layer (SSL) protocol should be used t o establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is trans mitted over the network. The UseSSL parameter lets you specify the addi tional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter , the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ValueSet <hashtable> Specifies a hash table that helps modify a management resource. You spe cify the management resource by using the ResourceURI parameter and the SelectorSet parameter. The value of the ValueSet parameter must be a h ash table. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES The Set-WmiInstance cmdlet, a Windows Management Instrumentation (WMI) cmdlet, is similar. Set-WmiInstance uses the DCOM connection/transport layer to create or update WMI instances. -------------------------- EXAMPLE 1 -------------------------- C:\PS>New-WSManInstance winrm/config/Listener -SelectorSet @{Transport=HTTP S} -ValueSet @{Hostname="HOST";CertificateThumbprint="XXXXXXXXXX"} Description ----------- This command creates an instance of a WS-Management HTTPS listener on all I P addresses. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141448 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan New-WSManSessionOption NAME New-WSManSessionOption SYNOPSIS Creates a WS-Management session option hash table to use as input parameter s to the following WS-Management cmdlets: Get-WSManInstance Set-WSManInstance Invoke-WSManAction Connect-WSMan SYNTAX New-WSManSessionOption [-NoCompression <switch>] [-NoProxy <switch>] [-Prox yAuthentication <string>] [-ProxyPassword <string>] [-ProxyUserName <string >] [-SkipCACheck <switch>] [-SkipCNCheck <switch>] [-SkipRevocation <switch >] [-SPNPort <int>] [-Timeout <int>] [-UnEncrypted <switch>] [-UseIEProxyco nfig <switch>] [-UseProxyAutoDetection <switch>] [-UseWinHTTPProxyConfig <s witch>] [-UTF16 <switch>] [<CommonParameters>] DESCRIPTION Creates a WSMan Session option hashtable which can be passed into WSMan cmd lets: Get-WSManInstance Set-WSManInstance Invoke-WSManAction Connect-WSMan PARAMETERS -NoCompression <switch> Turns off packet compression in the session. Compression is enabled by default and the packets sent between the client and server are compress ed. Compression uses more processor cycles, but it makes transmission f aster. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -NoProxy <switch> Do not use a proxy server. All all host names will be resolved locally. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ProxyAuthentication <string> Specifies the authentication method to use at the proxy. Possible value s are: - Basic: Basic is a scheme in which the user name and password are sent in clear-text to the server or proxy. - Digest: Digest is a challenge-response scheme that uses a server-spec ified data string for the challenge. - Negotiate (the default): Negotiate is a challenge-response scheme tha t negotiates with the server or proxy to determine which scheme to use for authentication. Examples are the Kerberos protocol and NTLM. Required? false Position? named Default value Negotiate Accept pipeline input? false Accept wildcard characters? false -ProxyPassword <string> Specifies a password to to be used for proxy authentication. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ProxyUserName <string> Specifies a user name to to be used for proxy authentication. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SkipCACheck <switch> Specifies that when connecting over HTTPS, the client does not validate that the server certificate is signed by a trusted certificate authori ty (CA). Use this option only when the remote computer is trusted by ot her means, for example, if the remote computer is part of a network tha t is physically secure and isolated or the remote computer is listed as a trusted host in the WS-Management configuration. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SkipCNCheck <switch> Specifies that the certificate common name (CN) of the server does not need to match the hostname of the server. This is used only in remote o perations using HTTPS. This option should only be used for trusted comp uters. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SkipRevocation <switch> Do not validate the revocation status on the server certificate. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SPNPort <int> Specifies a port number to append to the connection Service Principal N ame <SPN> of the remote server. An SPN is used when the authentication mechanism is Kerberos or Negotiate. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Timeout <int> Defines the timeout in milliseconds for the WS-Management operation. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UnEncrypted <switch> Do not use encryption when doing remote operations over HTTP. Note: Unencrypted traffic is not allowed by default and must be enabled in the local configuration. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseIEProxyconfig <switch> Use the Internet Explorer proxy configuration for the current user. Th is is the default setting. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseProxyAutoDetection <switch> Force auto-detection of a proxy. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseWinHTTPProxyConfig <switch> Use the proxy settings configured for WinHTTP. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UTF16 <switch> Encode the request in UTF16 format rather than UTF8 format. The default is UTF8 encoding. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS OUTPUTS SessionOption NOTES RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141449 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Test-WSMan Out-Default NAME Out-Default SYNOPSIS Sends the output to the default formatter and to the default output cmdlet. SYNTAX Out-Default [-InputObject <psobject>] [<CommonParameters>] DESCRIPTION The Out-Default cmdlet sends output to the default formatter and the defaul t output cmdlet. This cmdlet has no effect on the formatting or output of W indows PowerShell commands. It is a placeholder that lets you write your ow n Out-Default function or cmdlet. PARAMETERS -InputObject <psobject> Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS OUTPUTS NOTES RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113362 Out-File NAME Out-File SYNOPSIS Sends output to a file. SYNTAX Out-File [-FilePath] <string> [[-Encoding] <string>] [-Append] [-Force] [-I nputObject <psobject>] [-NoClobber] [-Width <int>] [-Confirm] [-WhatIf] [<C ommonParameters>] DESCRIPTION The Out-File cmdlet sends output to a file. You can use this cmdlet instead of the redirection operator (>) when you need to use its parameters. PARAMETERS -Append [<SwitchParameter>] Adds the output to the end of an existing file, instead of replacing th e file contents. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Encoding <string> Specifies the type of character encoding used in the file. Valid values are "Unicode", "UTF7", "UTF8", "UTF32", "ASCII", "BigEndianUnicode", " Default", and "OEM". "Unicode" is the default. "Default" uses the encoding of the system's current ANSI code page. "OEM" uses the current original equipment manufacturer code page identi fier for the operating system. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -FilePath <string> Specifies the path to the output file. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to overwrite an existing read-only file. Even using t he Force parameter, the cmdlet cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be written to the file. Enter a variable that contains the objects or type a command or expression that gets the obje cts. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -NoClobber [<SwitchParameter>] Will not overwrite (replace the contents) of an existing file. By defau lt, if a file exists in the specified path, Out-File overwrites the fil e without warning. If both Append and NoClobber are used, the output is appended to the existing file. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Width <int> Specifies the number of characters in each line of output. Any addition al characters are truncated, not wrapped. If you omit this parameter, t he width is determined by the characteristics of the host. The default for the Windows PowerShell console is 80 (characters). Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Out-File. OUTPUTS None Out-File does not generate any output. NOTES The Out cmdlets do not format objects; they just render them and send t hem to the specified display destination. If you send an unformatted ob ject to an Out cmdlet, the cmdlet sends it to a formatting cmdlet befor e rendering it. The Out cmdlets do not have parameters for names or file paths. To send data to a cmdlet that contains the Out verb (an Out cmdlet), use a pip eline operator (|) to send the output of a Windows PowerShell command t o the cmdlet. You can also store data in a variable and use the InputOb ject parameter to pass the data to the cmdlet. For help, see the exampl es. Out-File sends data, but it does not emit any output objects. If you pi pe the output of Out-File to Get-Member, Get-Member reports that no obj ects have been specified. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process | out-file -filepath C:\Test1\process.txt Description ----------- This command sends a list of processes on the computer to the Process.txt f ile. If the file does not exist, Out-File creates it. Because the name of t he FilePath parameter is optional, you can omit it and submit the equivalen t command "get-process | outfile C:\Test1\process.txt". -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-process | out-file C:\Test1\process.txt -noclobber Out-File : File C:\Test1\process.txt already exists and NoClobber was speci fied. At line:1 char:23 + get-process | out-file < process.txt -noclobber Description ----------- This command also sends a list of processes to the Process.txt file, but it uses the NoClobber parameter, which prevents an existing file from being o verwritten. The output shows the error message that appears when NoClobber is used with an existing file. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$a = get-process C:\PS> out-file -filepath C:\Test1\process.txt -inputobject $a -encoding AS CII -width 50 Description ----------- These commands send a list of processes on the computer to the Process.txt file. The text is encoded in ASCII format so that it can be read by search programs like Findstr and Grep. By default, Out-File uses Unicode format. The first command gets the list of processes and stores them in the $a vari able. The second command uses the Out-File cmdlet to send the list to the P rocess.txt file. The command uses the InputObject parameter to specify that the input is in the $a variable. It uses the Encoding parameter to convert the output to AS CII format. It uses the Width parameter to limit each line in the file to 5 0 characters. Because the lines of output are truncated at 50 characters, t he rightmost column in the process table is omitted. -------------------------- EXAMPLE 4 -------------------------- C:\PS>set-location hklm:\software c:\PS>get-acl mycompany\mykey | out-file -filepath c:\ps\acl.txt c:\PS>get-acl mycompany\mykey | out-file -filepath filesystem::acl.txt Description ----------- These commands show how to use the Out-File cmdlet when you are not in a Fi leSystem drive. The first command sets the current location to the HKLM:\Software registry key. The second and third commands have the same effect. They use the Get-Acl cm dlet to get the security descriptor of the MyKey registry subkey (HKLM\Soft ware\MyCompany\MyKey). A pipeline operator passes the result to the Out-Fil e cmdlet, which sends it to the Acl.txt file. Because Out-File is not supported by the Windows PowerShell Registry provid er, you must specify either the file system drive name, such as "c:", or th e name of the provider followed by two colons, "FileSystem::", in the value of the FilePath parameter. The second and third commands demonstrate these methods. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113363 Out-String Out-Null Out-Host Out-Printer Out-Default Tee-Object Out-GridView NAME Out-GridView SYNOPSIS Sends output to an interactive table in a separate window. SYNTAX Out-GridView [-InputObject <psobject>] [-Title <string>] [<CommonParameters >] DESCRIPTION The Out-GridView cmdlet sends the output from a command to a grid view wind ow where the output is displayed in an interactive table. This feature req uires Microsoft .NET Framework 3.5 with Service Pack 1. You can use the following features of the table to examine your data: -- Hide, Show, and Reorder Columns: To hide, show, or reorder a column, rig ht-click a column header and then click "Select Columns." -- Sort. To sort the data, click a column header. Click again to toggle fro m ascending to descending order. -- Quick Filter. Use the "Filter" box at the top of the window to search th e text in the table. You can search for text in a particular column, search for literals, and search for multiple words. -- Criteria Filter. Use the "Add criteria" drop-down menu to create rules t o filter the data. This is very useful for very large data sets, such as ev ent logs. -- Copy and paste. To copy rows of data from Out-GridView, press CTRL+C (co py). You can paste the data into any text or spreadsheet program. For instructions for using these features, type "get-help out-gridview -ful l" and see "How to Use the Grid View Window Features" in the NOTES section. PARAMETERS -InputObject <psobject> Accepts input for Out-GridView. When you use the InputObject parameter to send a collection (more than one) of objects to Out-GridView, Out-GridView treats the collection as one collection object, and it displays one row that represents the coll ection. To display the each object in the collection, use a pipeline o perator (|) to send objects to Out-GridView. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Title <string> Specifies the text that appears in the title bar of the Out-GridView wi ndow. By default, the title bar displays the command that invokes Out-GridVie w. Required? false Position? named Default value The current command Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can send any object to Out-GridView. OUTPUTS None Out-GridView does not return any objects. NOTES NOTES FOR OUT-GRIDVIEW ---------------------- You can download the Microsoft .NET Framework 3.5 with Service Pack 1 f rom the Microsoft Download Center. Because this cmdlet requires a user interface, it does not work on Serv er Core installations of Windows Server. You cannot use a remote command to open a grid view window on a remote computer. The command output that you send cannot be pre-formatted, such as by us ing the Format-Table or Format-Wide cmdlets. To select properties, use the Select-Object cmdlet. Deserialized output from remote commands might not be formatted correct ly in the grid view window. KEYBOARD SHORTCUTS FOR OUT-GRIDVIEW ----------------------------------- By using the following keyboard shortcuts, you can perform many tasks q uickly. Use this key: To perform this action: ------------- ----------------------------------------------------- ----------- TAB Moves the cursor from the Filter box to the Add crite ria menu to the table and back. UP ARROW Move up one row. Will move to column headers. DOWN ARROW Move down one row. LEFT ARROW In column header row, move left one column. RIGHT ARROW In column header row, move right one column. CONTEXT MENU KEY In column header row, displays the "Select Columns" o ption. ENTER or SPACEBAR In column header row, sort column data (toggle A-Z, Z -A). HOW TO USE THE GRID VIEW WINDOW FEATURES ---------------------------------------- The following topics explain how to use the features of the window that Out-GridView displays. How to Hide, Show, and Reorder Columns -------------------------------------- To hide or show a column: 1. Right click any column header and click "Select Columns". 2. In the "Select Columns" dialog box, use the arrow keys to move the c olumns between the "Selected columns" to the "Available columns" boxes. Only columns in the "Selected Columns" box appear in the grid view win dow. To reorder columns: -- Drag and drop the column into the desired location. - or- 1. Right click any column header and click "Select Columns". 2. In the "Select Columns" dialog box, use the "Move up" and "Move down " buttons to reorder the columns. Columns at the top of the list appear to the left of columns at the bottom of the list in the grid view wind ow. How to Sort Table Data ---------------------- -- To sort the data, click a column header. -- To change the sort order, click the column header again. Each time y ou click the same header, the sort order toggles between ascending to d escending order. The current order is indicated by a triangle in the co lumn header. How to Select Table Data ------------------------ -- To select a row, click the row or use the up or down arrow to naviga te to the row. -- To select all rows (except for the header row), press CTRL+A. -- To select consecutive rows, press and hold the SHIFT key while click ing the rows or using the arrow keys. -- To select nonconsecutive rows, press the CTRL key and click to add a row to the selection. You cannot select columns, and you cannot select the entire column head er row. How to Copy Rows ---------------------- -- To copy one or more rows from the table, select the rows and then pr ess CTRL+C. You can paste the data into any text or spreadsheet program. You cannot copy columns or parts of rows and you cannot copy the column header ro w. How to Search in the Table (Quick Filter) --------------------------------- Use the "Filter" box to search for data in the table. When you type in the box, only items that include the typed text appear in the table. -- Search for text. To search for text in the table, in the "Filter" bo x, type the text to find. -- Search for multiple words. To search for multiple words in the table , type the words separated by spaces. Out-GridView displays rows that i nclude all of the words (logical AND). -- Search for literal phrases. To search for phrases that include space s or special characters, enclose the phrase in quotation marks. Out-Gri dView displays rows that include an exact match for the phrase. -- Search in columns. To search for text in one or more columns, use th e following format: <column>:<text> [<column>: For example, to find "Net" in the DisplayName column, in the "Filte r" box, type: displayname:net To find rows with "Net" in the DisplayName and Name columns, in the "Filter" box, type: displayname:net name:net -- Turn off search. To display the entire table again, click the red X button in the top right corner of the "Filter" box or delete the text f rom the Filter box. Use Criteria to Filter the Table -------------------------------- You can use rules or "criteria" to determine which items are displayed in the table. Items appear only when they satisfy all of the criteria t hat you establish. The available criteria are determined by the propert ies of the objects displayed in the grid view window and the .NET Frame work types of those properties. Each criterion has the following format: <column> <operator> <value> Criteria for different properties are connected by AND. Criteria for th e same property are connected by OR. You cannot change the logical conn ectors. The criteria only affects the display. It does not delete items from th e table. How to Add Criteria --------------------------- 1. To display the "Add criteria" menu button, in the upper right corner of the window, click the "Expand" arrow. 2. Click the "Add Criteria" menu button. 3. Click to select columns (properties). You can select one or many pro perties. 4. When you are finished selecting properties, click the Add button. 5. To cancel the additions, click Cancel. 6. To add more criteria, click the Add Criteria button again. How to Edit a Criterion -------------------- -- To change an operator, click the blue operator value, and then click to select a different operator from the drop-down list. -- To enter or change a value, type a value in the value box. If you en ter a value that is not valid, a circular X icon appears. To remove it, change the value. -- To create an OR statement, add a criteria with the same property. How to Delete Criteria ------------------------- -- To delete selected criteria, click the red X beside each criterion. -- To delete all criteria, click the "Clear All" button. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process | out-gridview Description ----------- This command gets the processes running on the local computer and sends the m to a grid view window. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$p = get-process C:\PS> $p | out-gridview Description ----------- This command also gets the processes running on the local computer and send s them to a grid view window. The first command uses the Get-Process command to get the processes on the computer and then saves the process objects in the $p variable. The second command uses a pipeline operator to send the $p variable to Out- GridView. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-process | select-object -property name, workingset, peakworkingse t | sort-object -property workingset -desc | out-gridview Description ----------- This command displays a formatted table in a grid view window. It uses the Get-Process cmdlet to get the processes on the computer. Then, it uses a pipeline operator (|) to send the process objects to the Se lect-Object cmdlet. The command uses the Property parameter of Select-Objec t to select the Name, WorkingSet, and PeakWorkingSet properties to be displ ayed in the table. Another pipeline operator sends the filtered objects to the Sort-Object cmd let, which sorts them in descending order by the value of the WorkingSet pr operty. The final part of the command uses a pipeline operator (|) to send the form atted table to Out-GridView. You can now use the features of the grid view to search, sort, and filter t he data. -------------------------- EXAMPLE 4 -------------------------- C:\PS>($a = get-childitem -path $pshome -recurse) | out-gridview Description ----------- This command saves its output in a variable and sends it to Out-GridView. The command uses the Get-ChildItem cmdlet to get the files in the Windows P owerShell installation directory and its subdirectories. The path to the in stallation directory is saved in the $pshome automatic variable. The command uses the assignment operator (=) to save the output in the $a v ariable and the pipeline operator (|) to send the output to Out-GridView. The parentheses in the command establish the order of operations. As a resu lt, the output from the Get-ChildItem command is saved in the $a variable b efore it is sent to Out-GridView. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-process -computername Server01| ogv -title "Processes - Server01" Description ----------- This command displays the processes that are running on the Server01 comput er in a grid view window. The command uses "ogv," which is the built-in alias for the Out-GridView cm dlet, it uses the Title parameter to specify the window title. -------------------------- EXAMPLE 6 -------------------------- C:\PS>invoke-command -ComputerName S1, S2, S3 -scriptblock {get-culture} | out-gridview Description ----------- This example shows the correct format for sending data collected from remot e computers to the Out-GridView cmdlet. The command uses the Invoke-Command cmdlet to run a Get-Culture command on three remote computers. It uses a pipeline operator to send the data that i s returned to the Out-GridView cmdlet. Notice that the script block that contains the commands that are run remote ly does not include the Out-GridView command. If it did, the command would fail when it tried to open a grid view window on each of the remote compute rs. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113364 Out-Host NAME Out-Host SYNOPSIS Sends output to the command line. SYNTAX Out-Host [-InputObject <psobject>] [-Paging] [<CommonParameters>] DESCRIPTION The Out-Host cmdlet sends output to the Windows PowerShell host for display . The host displays the output at the command line. Because Out-Host is the default, you do not need to specify it unless you want to use its paramete rs to change the display. PARAMETERS -InputObject <psobject> Specifies the objects that are written to the console. Enter a variable that contains the objects, or type a command or expression that gets t he objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Paging [<SwitchParameter>] Displays one page of output at a time, and waits for user input before displaying the remaining pages, much like the traditional "more" comman d. By default, all of the output is displayed on a single page. The pag e size is determined by the characteristics of the host. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Out-Host. OUTPUTS None Out-Host does not generate any output. However, the host might display the objects that Out-Host sends to it. NOTES You can also refer to Out-Host by its built-in alias, "oh". For more in formation, see about_Aliases. The cmdlets that contain the Out verb (the Out cmdlets) do not format o bjects; they just render them and send them to the specified display de stination. If you send an unformatted object to an Out cmdlet, the cmdl et sends it to a formatting cmdlet before rendering it. The Out cmdlets do not have parameters for names or file paths. To send data to an Out cmdlet, use a pipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the InputObject parameter to pass the data to the cmdlet. For help, see the examples. Out-Host sends data, but it does not emit any output objects. If you pi pe the output of Out-Host to Get-Member, Get-Member reports that no obj ects have been specified. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process | out-host -paging Description ----------- This command displays the processes on the system one page at a time. It us es the Get-Process command to get the processes on the system. The pipeline operator (|) sends the results to Out-Host, which displays them at the con sole. The Paging parameter displays one page of data at a time. The same command format is used for the Help function that is built into Wi ndows PowerShell. That function gets data from Get-Help and then uses the P aging parameter of Out-Host to display the data one page at a time by using this command format: get-help $args[0] | out-host -paging). -------------------------- EXAMPLE 2 -------------------------- C:\PS>$a = get-history C:\PS>out-host -InputObject $a Description ----------- These commands display the session history at the command line. The first c ommand uses the Get-History cmdlet to get the session history, and then it stores the history in the $a variable. The second command uses Out-Host to display the content of the $a variable, and it uses the InputObject paramet er to specify the variable to Out-Host. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113365 Out-Printer Out-Null Out-File Out-String Out-Default Write-Host Out-Null NAME Out-Null SYNOPSIS Deletes output instead of sending it to the console. SYNTAX Out-Null [-InputObject <psobject>] [<CommonParameters>] DESCRIPTION The Out-Null cmdlet sends output to NULL, in effect, deleting it. PARAMETERS -InputObject <psobject> Specifies the object that was sent to null (deleted). Enter a variable that contains the objects, or type a command or expression that gets th e objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Out-Null. OUTPUTS None Out-Null does not generate any output. NOTES The cmdlets that contain the Out verb (the Out cmdlets) do not have par ameters for names or file paths. To send data to an Out cmdlet, use a p ipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the Input Object parameter to pass the data to the cmdlet. For more information, see the examples. Out-Null does not return any output objects. If you pipe the output of Out-Null to Get-Member, Get-Member reports that no objects have been sp ecified. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-childitem | out-null Description ----------- This command gets the items in the local directory, but then it discards th em instead of passing them through the pipeline or displaying them at the c ommand line. This is useful for discarding output that you do not need. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113366 Out-Printer Out-Host Out-File Out-String Out-Default Out-Printer NAME Out-Printer SYNOPSIS Sends output to a printer. SYNTAX Out-Printer [[-Name] <string>] [-InputObject <psobject>] [<CommonParameters >] DESCRIPTION The Out-Printer cmdlet sends output to the default printer or to an alterna te printer, if one is specified. PARAMETERS -InputObject <psobject> Specifies the objects to be sent to the printer. Enter a variable that contains the objects, or type a command or expression that gets the obj ects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string> Specifies the alternate printer. The parameter name ("Name") is option al. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Out-Printer. OUTPUTS None Out-Printer does not return any objects. NOTES You can also refer to Out-Printer by its built-in alias, "lp". For more information, see about_Aliases. The cmdlets that contain the Out verb (the Out cmdlets) do not format o bjects; they just render them and send them to the specified display de stination. If you send an unformatted object to an Out cmdlet, the cmdl et sends it to a formatting cmdlet before rendering it. The Out cmdlets do not have parameters for names or file paths. To send data to an Out cmdlet, use a pipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the InputObject parameter to pass the data to the cmdlet. For more information, see the examples. Out-Printer sends data, but it does not emit any output objects. If you pipe the output of Out-Printer to Get-Member, Get-Member reports that no objects have been specified. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-content $pshome\about_signing.help.txt | Out-Printer Description ----------- This command prints the content of the about_Signing Help topic to the defa ult printer. This example shows you how to print a file, even though Out-Pr inter does not have a Path parameter. The command uses the Get-Content cmdlet to get the contents of the Help top ic. The path includes $pshome, a built-in variable that stores the installa tion directory for Windows PowerShell. A pipeline operator (|) passes the r esults to Out-Printer, which sends it to the default printer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>"Hello, World" | out-printer -name "\\Server01\Prt-6B Color" Description ----------- This command prints "Hello, World" to the "Prt-6B Color" printer on Server0 1. This command uses the Name parameter to specify the alternate printer. B ecause the parameter name is optional, you can omit it. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$h = get-help -full get-wmiobject C:\PS> out-printer -inputobject $h Description ----------- These commands print the full version of the Help topic for Get-WmiObject. The first command uses the Get-Help cmdlet to get the full version of the H elp topic for Get-WmiObject and stores it in the $h variable. The second co mmand sends the content to the default printer. It uses the InputObject par ameter to pass the value of the $h variable to Out-Printer. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113367 Out-Host Out-Null Out-String Out-File Out-Default Out-String NAME Out-String SYNOPSIS Sends objects to the host as a series of strings. SYNTAX Out-String [-InputObject <psobject>] [-Stream] [-Width <int>] [<CommonParam eters>] DESCRIPTION The Out-String cmdlet converts the objects that Windows PowerShell manages into an array of strings. By default, Out-String accumulates the strings an d returns them as a single string, but you can use the stream parameter to direct Out-String to return one string at a time. This cmdlet lets you sear ch and manipulate string output as you would in traditional shells when obj ect manipulation is less convenient. PARAMETERS -InputObject <psobject> Specifies the objects to be written to a string. Enter a variable that contains the objects, or type a command or expression that gets the obj ects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Stream [<SwitchParameter>] Sends the strings for each object separately. By default, the strings f or each object are accumulated and sent as a single string. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Width <int> Specifies the number of characters in each line of output. Any addition al characters are truncated, not wrapped. If you omit this parameter, t he width is determined by the characteristics of the host. The default for the PowerShell.exe host is 80 (characters). Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe objects to Out-String. OUTPUTS System.String Out-String returns the string that it creates from the input object. NOTES The cmdlets that contain the Out verb (the Out cmdlets) do not format o bjects; they just render them and send them to the specified display de stination. If you send an unformatted object to an Out cmdlet, the cmdl et sends it to a formatting cmdlet before rendering it. The Out cmdlets do not have parameters for names or file paths. To send data to an Out cmdlet, use a pipeline operator (|) to send the output of a Windows PowerShell command to the cmdlet. You can also store data in a variable and use the InputObject parameter to pass the data to the cmdlet. For more information, see the examples. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-content C:\test1\testfile2.txt | out-string Description ----------- This command sends the content of the Testfile2.txt file to the console as a single string. It uses the Get-Content cmdlet to get the content of the f ile. The pipeline operator (|) sends the content to Out-String, which sends the content to the console as a string. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$c = get-culture | select-object * C:\PS> out-string -inputobject $c -width 100 Description ----------- These commands get the regional settings for the current user and convert t he data to strings. The first command uses the Get-Culture cmdlet to get th e regional settings. The pipeline operator (|) sends the result to the Sele ct-Object cmdlet, which selects all properties (*) of the culture object th at Get-Culture retrieved. The command then stores the results in the $c var iable. The second command uses Out-String to convert the CultureInfo object to a s eries of strings (one string for each property). It uses the InputObject pa rameter to pass the $c variable to Out-String. The width parameter is set t o 100 characters per line to prevent truncation. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-alias | out-string -stream | select-string "Get-Command" Description ----------- This command displays aliases that include the phrase "Get-Command". It use s the Get-Alias cmdlet to get a set of AliasInfo objects (one for each alia s in the current session). This example demonstrates the difference between working with objects and working with strings. The pipeline operator (|) sends the output of Get-Alias to Out-String, whic h converts the objects to a series of strings. It uses the Stream parameter to send each string individually, instead of concatenating them into a sin gle string. Another pipeline operator sends the strings to Select-String, w hich selects the strings that include "Get-Command" anywhere in the string. If you omit the Stream parameter, the command displays all of the aliases, because Select-String finds "Get-Command" in the single string that Out-Str ing returns, and the formatter displays the string as a table. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113368 Out-File Out-Null Out-Host Out-Printer Out-Default Pop-Location NAME Pop-Location SYNOPSIS Changes the current location to the location most recently pushed onto the stack. You can pop the location from the default stack or from a stack that you create by using the Push-Location cmdlet. SYNTAX Pop-Location [-PassThru] [-StackName <string>] [-UseTransaction] [<CommonPa rameters>] DESCRIPTION The Pop-Location cmdlet changes the current location to the location most r ecently pushed onto the stack by using the Push-Location cmdlet. You can po p a location from the default stack or from a stack that you create by usin g a Push-Location command. PARAMETERS -PassThru [<SwitchParameter>] Passes an object representing the location to the pipeline. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -StackName <string> Specifies an alternate stack. Pop-Location pops the most recently added location from this stack. This stack then becomes the current stack. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to Pop-Location. OUTPUTS None or System.Management.Automation.PathInfo When you use the PassThru parameter, Pop-Location generates a System.Ma nagement.Automation.PathInfo object that represents the location. Other wise, this cmdlet does not generate any output. NOTES You can also refer to Pop-Location by its built-in alias, "popd". For m ore information, see about_Aliases. The Pop-Location cmdlet is designed to work with the data exposed by an y provider. To list the providers available in your session, type "Get- PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>pop-location Description ----------- This command changes your location to the location most recently added to t he current stack. -------------------------- EXAMPLE 2 -------------------------- C:\PS>pop-location -stackname Stack2 Description ----------- This command changes your location to the location most recently added to t he Stack2 stack. -------------------------- EXAMPLE 3 -------------------------- C:\PS>pushd HKLM:\Software\Microsoft\PowerShell pushd Cert:\LocalMachine\TrustedPublisher popd popd PS C:\> push-location HKLM:\Software\Microsoft\PowerShell PS HKLM:\Software\Microsoft\PowerShell> push-location Cert:\LocalMachine\Tr ustedPublisher PS cert:\LocalMachine\TrustedPublisher> popd PS HKLM:\Software\Microsoft\PowerShell> popd PS C:\ps-test> Description ----------- These commands use the Push-Location and Pop-Location cmdlets to move betwe en locations supported by different Windows PowerShell providers. The comma nds use the "pushd" alias for Push-Location and the "popd" alias for Pop-Lo cation. The first command pushes the current file system location onto the stack an d moves to the HKLM drive supported by the Windows PowerShell Registry prov ider. The second command pushes the registry location onto the stack and mo ves to a location supported by the Windows PowerShell certificate provider. The last two commands pop those locations off the stack. The first "popd" c ommand returns to the Registry: drive, and the second command returns to th e file system drive. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113369 about_Providers Push-Location Set-Location Get-Location prompt prompt Push-Location NAME Push-Location SYNOPSIS Adds the current location to the top of a list of locations (a "stack"). SYNTAX Push-Location [[-LiteralPath] <string>] [-PassThru] [-StackName <string>] [ -UseTransaction] [<CommonParameters>] Push-Location [[-Path] <string>] [-PassThru] [-StackName <string>] [-UseTra nsaction] [<CommonParameters>] DESCRIPTION The Push-Location cmdlet adds ("pushes") the current location to the top of a list of locations, called a "stack." You can push the current location o nto a default stack or onto a stack that you create. If you specify a path, Push-Location pushes the current location onto the stack and then changes the current location to the location specified by the path. You cannot push a location onto the stack unless it is the current location. PARAMETERS -LiteralPath <string> Specifies the path to the new location. Unlike the Path parameter, the value of the LiteralPath parameter is used exactly as it is typed. No c haracters are interpreted as wildcards. If the path includes escape cha racters, enclose it in single quotation marks. Single quotation marks t ell Windows PowerShell not to interpret any characters as escape sequen ces. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Passes an object representing the location to the pipeline. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Changes your location to the location specified by this path after it a dds (pushes) the current location onto the top of the stack. Enter a pa th to any location whose provider supports this cmdlet. Wildcards are p ermitted. The parameter name ("Path") is optional. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -StackName <string> Specifies the name of a stack. The current location is pushed onto this stack, and this stack becomes the current stack. If the stack does not yet exist, it is created. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path (but not a literal path) to Push-Location. OUTPUTS None or System.Management.Automation.PathInfo When you use the PassThru parameter, Push-Location generates a System.M anagement.Automation.PathInfo object that represents the location. Othe rwise, this cmdlet does not generate any output. NOTES You can also refer to Push-Location by its built-in alias, "pushd". For more information, see about_Aliases. A "stack" is a "last-in, first-out" (LIFO) data structure. It is like a vertical list in which only the top item is accessible. You can add (" push") items only to the top of the stack, and you can retrieve ("pop") items only from the top of the stack. To get to items below the top, y ou must retrieve all the items above. The Push-Location cmdlet is designed to work with the data exposed by a ny provider. To list the providers available in your session, type "Get -PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>push-location C:\Windows Description ----------- This command pushes the current location onto the default stack and then ch anges the location to C:\Windows. -------------------------- EXAMPLE 2 -------------------------- C:\PS>push-location HKLM:\Software\Policies -stackname RegFunction Description ----------- This command pushes the current location onto the RegFunction stack and cha nges the current location to the HKLM:\Software\Policies location. This com mand shows that you can use Push-Location with the Windows PowerShell regis try provider. -------------------------- EXAMPLE 3 -------------------------- C:\PS>push-location Description ----------- This command pushes the current location onto the default stack. -------------------------- EXAMPLE 4 -------------------------- C:\PS>push-location ~ -stackname Stack2 Description ----------- This command pushes the current location onto a new stack named Stack2 and then changes the current location to the home directory (%USERPROFILE%), wh ich is represented in the command by the tilde symbol (~) or $home. The Sta ck2 stack then becomes the current stack. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113370 about_Providers Pop-Location Set-Location Get-Location Read-Host NAME Read-Host SYNOPSIS Reads a line of input from the console. SYNTAX Read-Host [[-Prompt] <Object>] [-AsSecureString] [<CommonParameters>] DESCRIPTION The Read-Host cmdlet reads a line of input from the console. You can use it to prompt a user for input. Because you can save the input as a secure str ing, you can use this cmdlet to prompt users for secure data, such as passw ords, as well as shared data. PARAMETERS -AsSecureString [<SwitchParameter>] Displays asterisks (*) in place of the characters that the user types a s input. When you use this parameter, the output of the Read-Host cmdlet is a Se cureString object (System.Security.SecureString). Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Prompt <Object> Specifies the text of the prompt. Type a string. If the string includes spaces, enclose it in quotation marks. For example, "Type an integer: ". Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.String or System.Security.SecureString If the AsSecureString parameter is used, Read-Host returns a SecureStri ng. Otherwise, it returns a string. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$age = read-host "Please enter your age:" Description ----------- This command displays the string "Please enter your age:" as a prompt. When a value is entered and the Enter key is pressed, the value is stored in th e $age variable. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$pwd_secure_string = read-host "Enter a Password:" -assecurestring Description ----------- This command displays the string "Enter a Password:" as a prompt. As a valu e is being entered, asterisks (*) appear on the console in place of the inp ut. When the Enter key is pressed, the value is stored as a SecureString ob ject in the $pwd_secure_string variable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113371 Get-Host Out-Host Write-Host ConvertFrom-SecureString Receive-Job NAME Receive-Job SYNOPSIS Gets the results of the Windows PowerShell background jobs in the current s ession. SYNTAX Receive-Job [-Job] <Job[]> [[-ComputerName] <string[]>] [-Keep] [-NoRecurse ] [<CommonParameters>] Receive-Job [[-InstanceId] <Guid[]>] [-Keep] [-NoRecurse] [<CommonParameter s>] Receive-Job [-Job] <Job[]> [[-Location] <string[]>] [-Keep] [-NoRecurse] [ CommonParameters>] Receive-Job [[-Name] <string[]>] [-Keep] [-NoRecurse] [<CommonParameters>] Receive-Job [-Job] <Job[]> [[-Session] <PSSession[]>] [-Keep] [-NoRecurse] [<CommonParameters>] Receive-Job [-Id] <Int32[]> [-Keep] [-NoRecurse] [<CommonParameters>] DESCRIPTION The Receive-Job cmdlet gets the results of Windows Powershell background jo bs. Use Receive-Job to get the results of jobs started by using the Start-J ob cmdlet or the AsJob parameter of any cmdlet. You can get the results of all jobs or identify jobs by their name, ID, instance ID, computer name, lo cation, or session, or by submitting a job object. When you start a Windows PowerShell background job, the job starts, but the results do not appear immediately. Instead, the command returns an object that represents the background job. The job object contains useful informat ion about the job, but it does not contain the results. This method allows you to continue working in the session while the job runs. For more inform ation about background jobs in Windows PowerShell, see about_Jobs. To get the results of the command, use the Receive-Job cmdlet. Receive-Job gets the results that have been generated by the time that the Receive-Job command is submitted. If the results are not yet complete, you can run addi tional Receive-Job commands to get the remaining results. By default, job results are deleted from the system when you receive them, but you can use the Keep parameter to save the results so that you can rece ive them again. To delete the job results, receive them again (without the Keep parameter), close the session, or use the Remove-Job cmdlet to delete the job from the session. PARAMETERS -ComputerName <string[]> Gets the results of jobs that were run on the specified computers. Ente r the computer names. The default is all jobs in the current session. This parameter selects from among the job results that are stored on th e local computer. It does not get data from remote computers. To get jo b results that are stored on remote computers, use the Invoke-Command c mdlet to run a Receive-Job command remotely. Required? false Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Id <Int32[]> Gets the results of jobs with the specified IDs. The default is all job s in the current session. The ID is an integer that uniquely identifies the job within the curren t session. It is easier to remember and type than the instance ID, but it is unique only within the current session. You can type one or more IDs (separated by commas). To find the ID of a job, type "Get-Job" with out parameters. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InstanceId <Guid[]> Gets the results of jobs with the specified instance IDs. The default i s all jobs in the current session. An instance ID is a GUID that uniquely identifies the job on the comput er. To find the instance ID of a job, use the Get-Job cmdlet. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Job <Job[]> Specifies the job for which results are being retrieved. This parameter is required in a Receive-Job command. Enter a variable that contains t he job or a command that gets the job. You can also pipe a job object t o Receive-Job. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Keep [<SwitchParameter>] Saves the job results in the system, even after you have received them. By default, the job results are deleted when they are retrieved. To delete the results, use Receive-Job to receive them again without th e Keep parameter, close the session, or use the Remove-Job cmdlet to de lete the job from the session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Location <string[]> Gets only the results of jobs with the specified location. The default is all jobs in the current session. Required? false Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Gets the results of jobs with the specified friendly name. The default is all jobs in the current session. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -NoRecurse [<SwitchParameter>] Gets results only from the specified job. By default, Receive-Job also gets the results of all child jobs of the specified job. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Session <PSSession[]> Gets the results of jobs that were run in the specified Windows Powersh ell session (PSSession). Enter a variable that contains the PSSession o r a command that gets the PSSession, such as a Get-PSSession command. T he default is all jobs in the current session. Required? false Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.Job You can pipe job objects to Receive-Job. OUTPUTS PSObject Receive-Job returns the results of the commands in the job. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$job = start-job -scriptblock {get-process} C:\PS> receive-job -job $job Description ----------- These commands use the Job parameter to get the results of a particular job . The first command uses the Start-Job cmdlet to start a job that runs a "G et-Process" command. The command uses the assignment operator (=) to save t he resulting job object in the $job variable. The second command uses the Receive-Job cmdlet to get the results of the jo b. It uses the Job parameter to specify the job. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$job = start-job -scriptblock {get-process} C:\PS> $job | receive-job Description ----------- This example is the same as Example 2, except that the command uses a pipel ine operator (|) to send the job object to Receive-Job. As a result, the co mmand does not need a Job parameter to specify the job. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$j = invoke-command -computername Server01, Server02, Server03 -scrip tblock {get-service} -AsJob C:\PS> $j.childjobs Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 2 Job2 Completed True Server01 get-service 3 Job3 Completed True Server02 get-service 4 Job4 Completed True Server03 get-service C:\PS> receive-job -name Job3 -keep Status Name DisplayName PSComputerName ------ ----------- ----------- -------------- Running AeLookupSvc Application Experience Server02 Stopped ALG Application Layer Gateway Service Server02 Running Appinfo Application Information Server02 Running AppMgmt Application Management Server02 Description ----------- These commands use the Name parameter of Receive-Job to get the results of one of several background jobs run on remote computers. The first command uses the Invoke-Command cmdlet to start a background job that runs a Get-Service command on three remote computers. The command uses the AsJob parameter to run the command as a background job. The command sa ves the resulting job object in the $j variable. When you use the AsJob parameter of Invoke-Command to start a job, the job object is created on the local computer, even though the job runs on the re mote computers. As a result, you use local commands to manage the job. Also, when you use AsJob, Windows PowerShell returns one job object that co ntains a child job for each job that was started. In this case, the job obj ect contains three child jobs, one for each job on each remote computer. The second command uses the dot method to display the value of the ChildJob s property of the job object in $j. The display shows that the command crea ted three child jobs, one for the job on each remote computer. The third command uses the Receive-Job cmdlet to get the results of the Job 3 child job that ran on the Server02 computer. It uses the Name parameter t o specify the name of the child job and the Keep parameter to save the job results even after they are received. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$s = new-pssession -computername Server01, Server02, Server03 C:\PS> $j = invoke-command -session $s -scriptblock {start-job -scriptblock {get-eventlog -logname system}} C:\PS> $j Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job1 Completed True Localhost get-eventlog system 2 Job2 Completed True Localhost get-eventlog system 3 Job3 Completed True Localhost get-eventlog system C:\PS> $results = invoke-command -session $s -scriptblock {param($j) receiv e-job -job $j} -ArgumentList $j Description ----------- This example shows how to get the results of background jobs run on three r emote computers. The first command uses the New-PSSession cmdlet to create three PSSessions, one on each of the servers specified in the command. It saves the PSSessio ns in the $s variable. The second command uses the Invoke-Command cmdlet to run a Start-Job comman d in each of the PSSessions in the $s variable. The job runs a Get-Eventlog command that gets the events in the System log. The command saves the resu lts in the $j variable. Because the command used Invoke-Command to run the Start-Job command, the c ommand actually started three independent jobs on each of the three compute rs. As a result, the command returned three job objects representing three jobs run locally on three different computers. The third command displays the three job objects in $j. The fourth command uses Invoke-Command to run a Receive-Job command in each of the PSSessions in $s and save the results in the $results variable. Because $j is a local variable, the script block uses the "param" keyword t o declare the variables in the command and the ArgumentList parameter to su pply the value of $j. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113372 about_Jobs about_Job_Details about_Remote_Jobs Start-Job Get-Job Wait-Job Stop-Job Remove-Job Invoke-Command Register-EngineEvent NAME Register-EngineEvent SYNOPSIS Subscribes to events that are generated by the Windows PowerShell engine an d by the New-Event cmdlet. SYNTAX Register-EngineEvent [-SourceIdentifier] <string> [[-Action] <scriptblock>] [-Forward] [-MessageData <psobject>] [-SupportEvent] [<CommonParameters>] DESCRIPTION The Register-EngineEvent cmdlet subscribes to events that are generated by the Windows PowerShell engine and the New-Event cmdlet. Use the SourceIdent ifier parameter to specify the event. You can use this cmdlet to subscribe to the "Exiting" engine event and even ts generated by the New-Event cmdlet. These events are automatically added to your event queue in your session without subscribing. However, subscribi ng lets you forward the events, specify an action to respond to the events, and cancel the subscription. When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet. When you subscribe to a event, an event subcriber is added to your session. To get the event subscribers in the session, use the Get-EventSubscriber c mdlet. To cancel the subscription, use the Unregister-Event cmdlet, which d eletes the event subscriber from the session. PARAMETERS -Action <scriptblock> Specifies commands to handle the events. The commands in the Action run when an event is raised, instead of sending the event to the event que ue. Enclose the commands in braces ( { } ) to create a script block. The value of the Action parameter can include the $Event, $EventSubscri ber, $Sender, $SourceEventArgs, and $SourceArgs automatic variables, wh ich provide information about the event to the Action script block. For more information, see about_Automatic_Variables. When you specify an action, Register-EngineEvent returns an event job o bject that represents that action. You can use the Job cmdlets to manag e the event job. Required? false Position? 102 Default value None Accept pipeline input? false Accept wildcard characters? false -Forward [<SwitchParameter>] Sends events for this subscription to the session on the local computer . Use this parameter when you are registering for events on a remote co mputer or in a remote session. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -MessageData <psobject> Specifies additional data associated with the event. The value of this parameter appears in the MessageData property of the event object. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -SourceIdentifier <string> Specifies the source identifier of the event to which you are subscribi ng. The source identifier must be unique in the current session. This p arameter is required. The value of this parameter appears in the value of the SourceIdentifie r property of the subscriber object and of all event objects associated with this subscription. Required? true Position? 101 Default value Accept pipeline input? false Accept wildcard characters? false -SupportEvent [<SwitchParameter>] Hides the event subscription. Use this parameter when the current subsc ription is part of a more complex event registration mechanism and it s hould not be discovered independently. To view or cancel a subscription that was created with the SupportEvent parameter, use the Force parameter of the Get-EventSubscriber and Unre gister-Event cmdlets. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to Register-EngineEvent. OUTPUTS None or System.Management.Automation.PSEventJob If you use the Action parameter, Register-EngineEvent returns a System. Management.Automation.PSEventJob object. Otherwise, it does not generat e any output. NOTES Events, event subscriptions, and the event queue exist only in the curr ent session. If you close the current session, the event queue is disca rded and the event subscription is canceled. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$s = new-pssession -computername Server01, Server02 C:\PS> invoke-command -session $s { Register-EngineEvent -sourceIdentifier ([System.Management.Automation.PsEngineEvent]::Exiting) -forward } Description ----------- This command registers for a Windows PowerShell engine event on two remote computers. The first command creates a PSSession on each of the remote computers. The second command uses the Invoke-Command cmdlet to run the Register-Engin eEvent command in the remote sessions. The Register-EngineEvent command uses the SourceIdentifier parameter to ide ntify the event. It uses the Forward parameter to forward the events from t he remote session to the local session. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$j = register-engineEvent -sourceIdentifier PowerShell.ProcessCreated -action { $processName | add-content processLog.txt } C:\PS> get-event C:\PS> $results = $j | receive-job C:\PS> unregister-event PowerShell.ProcessCreated Description ----------- This command shows how to use the Job cmdlets to manage the event job objec t that Register-EngineEvent returns when you use the Action parameter. An event job is managed just like any other Windows PowerShell job. For mor e information, see about_jobs. In this example, the Receive-Job cmdlet is u sed to get the results of the job. To delete the job from the session, use Remove-Job. To cancel your event su bscription, use the Unregister-Event cmdlet. To delete the events in the ev ent queue, use Remove-Event. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135243 Register-ObjectEvent Register-WmiEvent Unregister-Event Get-Event New-Event Remove-Event Wait-Event Get-Job Receive-Job Remove-Job Wait-Job Register-ObjectEvent NAME Register-ObjectEvent SYNOPSIS Subscribes to the events that are generated by a Microsoft .NET Framework o bject. SYNTAX Register-ObjectEvent [-InputObject] <psobject> [-EventName] <string> [[-Sou rceIdentifier] <string>] [[-Action] <scriptblock>] [-Forward] [-MessageData <psobject>] [-SupportEvent] [<CommonParameters>] DESCRIPTION The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET Framework objects on the local computer or on a remote computer. When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet. You can use the parameters of Register-ObjectEvent to specify property valu es of the events that can help you to identify the event in the queue. You can also use the Action parameter to specify actions to take when a subscri bed event is raised and the Forward parameter to send remote events to the event queue in the local session. When you subscribe to an event, an event subcriber is added to your session . To get the event subscribers in the session, use the Get-EventSubscriber cmdlet. To cancel the subscription, use the Unregister-Event cmdlet, which deletes the event subscriber from the session. PARAMETERS -Action <scriptblock> Specifies commands to handle the events. The commands in the Action run when an event is raised, instead of sending the event to the event que ue. Enclose the commands in braces ( { } ) to create a script block. The value of the Action parameter can include the $Event, $EventSubscri ber, $Sender, $SourceEventArgs, and $SourceArgs automatic variables, wh ich provide information about the event to the Action script block. For more information, see about_Automatic_Variables. When you specify an action, Register-ObjectEvent returns an event job o bject that represents that action. You can use the Job cmdlets to manag e the event job. Required? false Position? 102 Default value None. Accept pipeline input? false Accept wildcard characters? false -EventName <string> Specifies the event to which you are subscribing. Enter the event name. This parameter is required. The value of this parameter is not a name that you select for the event subscription. It is the name of an event that the .NET Framework objec t exposes. For example, the ManagementEventWatcher class has events nam ed "EventArrived" and "Stopped." To find the event name of an event, us e the Get-Member cmdlet. Required? true Position? 2 Default value None Accept pipeline input? false Accept wildcard characters? false -Forward [<SwitchParameter>] Sends events for this subscription to a remote session. Use this parame ter when you are registering for events on a remote computer or in a re mote session. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the .NET Framework object that generates the events. Enter a variable that contains the object, or type a command or expression that gets the object. This parameter is required. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -MessageData <psobject> Specifies any additional data to be associated with this event subscrip tion. The value of this parameter appears in the MessageData property o f all events associated with this subscription. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -SourceIdentifier <string> Specifies a name that you select for the subscription. The name that yo u select must be unique in the current session. The default value is th e GUID that Windows PowerShell assigns. The value of this parameter appears in the value of the SourceIdentifie r property of the subcriber object and of all event objects associated with this subscription. Required? false Position? 101 Default value GUID Accept pipeline input? false Accept wildcard characters? false -SupportEvent [<SwitchParameter>] Hides the event subscription. Use this parameter when the current subsc ription is part of a more complex event registration mechanism and it s hould not be discovered independently. To view or cancel a subscription that was created with the SupportEvent parameter, use the Force parameter of the Get-EventSubscriber and Unre gister-Event cmdlets. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Register-ObjectEvent. OUTPUTS None This cmdlet does not generate any output. NOTES Events, event subscriptions, and the event queue exist only in the curr ent session. If you close the current session, the event queue is disca rded and the event subscription is canceled. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$query = New-Object System.Management.WqlEventQuery "__InstanceCreati onEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'" C:\PS> $processWatcher = New-Object System.Management.ManagementEventWatche r $query C:\PS> register-objectEvent -inputObject $processWatcher -eventName "EventA rrived" Description ----------- This example subscribes to events generated when a new process starts. The command uses the ManagementEventWatcher object to get EventArrived even ts. A query object specifies that the events are instance creation events f or the Win32_Process class. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$query = New-Object System.Management.WqlEventQuery "__InstanceCreati onEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'" C:\PS> $processWatcher = New-Object System.Management.ManagementEventWatche r $query C:\PS> $action = { New-Event "PowerShell.ProcessCreated" -Sender $sender -E ventArguments $SourceEventArgs.NewEvent.TargetInstance } C:\PS> register-objectEvent -inputObject $processWatcher -eventName "EventA rrived" -action $action Id Name State HasMoreData Location Comma nd -- ---- ----- ----------- -------- ----- -- 2 422cfe5a-65e... Running True New-E vent "PowerShe... Description ----------- This example shows how to specify an action to respond to an event. When yo u specify an action, events that are raised are not added to the event queu e. Instead, the action responds to the event. In this example, when an instance creation event is raised indicating that a new process is started, a new ProcessCreated event is raised. The action uses the $Sender and $SourceEventArgs automatic variables which are populated only for event actions. The Register-ObjectEvent command returns a job object that represents the a ction, which runs as a background job. You can use the Job cmdlets, such as Get-Job and Receive-Job, to manage the background job. For more information, see about_Jobs. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$s = new-pssession -computername Server01, Server02 C:\PS> invoke-command -session $s -filepath ProcessCreationEvent.ps1 C:\PS> invoke-command -session $s { get-event } # ProcessCreationEvent.ps1 function Enable-ProcessCreationEvent { $query = New-Object System.Management.WqlEventQuery "__InstanceCreationE vent", ` (New-Object TimeSpan 0,0,1), ` "TargetInstance isa 'Win32_Process'" $processWatcher = New-Object System.Management.ManagementEventWatcher $q uery $identifier = "WMI.ProcessCreated" Register-ObjectEvent -input $processWatcher -eventName "EventArrived" ` -sourceIdentifier $identifier -messageData "Test" -forward } } EnableProcessCreationEvent Description ----------- This example shows how to subscribe to object events on remote computers. The first command creates PSSessions on two remote computers and saves them in the $s variable. The second command uses the FilePath parameter of the Invoke-Command cmdlet to run the ProcessCreationEvent.ps1 script in the each of the PSSessions i n $s. The script includes a Register-ObjectEvent command that subscribes to insta nce creation events on the Win32_Process object through the ManagementEvent Watcher object and its EventArrived event. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$timer = New-Object Timers.Timer C:\PS> $timer.Interval = 500 C:\PS> $job = Register-ObjectEvent -inputObject $timer -eventName Elapsed - sourceIdentifier Timer.Random -Action {$random = Get-Random -Min 0 -Max 100 } C:\PS> $job.gettype().fullname System.Management.Automation.PSEventJob C:\PS> $job | format-list -property * State : Running Module : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0 StatusMessage : HasMoreData : True Location : Command : $random = Get-Random -Min 0 -Max 100 JobStateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : 88944290-133d-4b44-8752-f901bd8012e2 Id : 1 Name : Timer.Random ChildJobs : {} ... C:\PS> $timer.Enabled = $true C:\PS> & $job.module {$random} 60 C:\PS> & $job.module {$random} 47 Description ----------- This example shows how to use the dynamic module in the PSEventJob object t hat is created when you include an Action in a event registration. The first command uses the New-Object cmdlet to create a timer object. The second command sets the interval of the timer to 500 (milliseconds). The third command uses the Register-ObjectEvent cmdlet to register the Elap sed event of the timer object. The command includes an action that handles the event. Whenever the timer interval elapses, an event is raised and the commands in the action run. In this case, the Get-Random cmdlet generates a random number between 0 and 100 and saves it in the $random variable. When you use an Action parameter in a Register-ObjectEvent command, the com mand returns a PSEventJob object that represents the action. The command sa ves the job object in the $job variable. The PSEventJob object that the Register-ObjectEvent cmdlet returns is also available in the Action property of the event subscriber. For more informat ion, see Get-EventSubscriber. The fourth command shows that the $job variable contains a PSEventJob objec t. The fifth command uses the Format-List cmdlet to display all of the prop erties of the PSEventJob object in a list. The PSEventJob has a Module property that contains a dynamic script module that implements the action. The sixth command enables the timer. The remaining commands use the call operator (&) to invoke the command in t he module and display the value of the $random variable. You can use the ca ll operator to invoke any command in a module, including commands that are not exported. In this case, the commands show the random number that is bei ng generated when the Elapsed event occurs. For more information about modules, see about_Modules. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135244 Register-EngineEvent Register-WmiEvent Unregister-Event Get-Event New-Event Remove-Event Wait-Event Register-PSSessionConfiguration NAME Register-PSSessionConfiguration SYNOPSIS Creates and registers a new session configuration. SYNTAX Register-PSSessionConfiguration [-AssemblyName] <string> [-ConfigurationTyp eName] <string> [-ApplicationBase <string>] [-Name] <string> [-Force] [-Max imumReceivedDataSizePerCommandMB <double>] [-MaximumReceivedObjectSizeMB <d ouble>] [-NoServiceRestart] [-ProcessorArchitecture <string>] [-SecurityDes criptorSDDL <string>] [-ShowSecurityDescriptorUI] [-StartupScript <string>] [-ThreadApartmentState {STA | MTA | Unknown}] [-ThreadOptions {Default | U seNewThread | ReuseThread | UseCurrentThread}] [-Confirm] [-WhatIf] [<Commo nParameters>] DESCRIPTION The Register-PSSessionConfiguration cmdlet creates and registers a new ses sion configuration on the local computer. This is an advanced cmdlet that i s designed to be used by system administrators to manage customized session configurations for their users. Every Windows PowerShell remote session uses a session configuration. When users create a session that connects to the computer, they can select a con figuration or use the default configurations that are registered when you e nable Windows PowerShell remoting. Users can also set the $PSSessionConfigu rationName preference variable, which specifies a default configuration for sessions created in the current session. The session configuration configures the environment for the session. You c an define the configuration by using an assembly that implements a new conf iguration class and by using a script that runs in the session. The configu ration can determine which commands are available in the session, and it ca n include settings that protect the computer, such as those that limit the amount of data that the session can receive remotely in a single object or command. You can also specify a security descriptor that determines the pe rmissions that are required to use the configuration. PARAMETERS -ApplicationBase <string> Specifies the path to the assembly file (*.dll) that is specified in th e value of the AssemblyName parameter. Use this parameter when the valu e of the AssemblyName parameter does not include a path. The default is the current directory. Required? false Position? named Default value Current directory Accept pipeline input? false Accept wildcard characters? false -AssemblyName <string> Specifies the name of an assembly file (*.dll) in which the configurati on type is defined. You can specify the path to the .dll in this parame ter or in the value of the ApplicationBase parameter. This parameter is required when the ConfigurationTypeName parameter is specified. Required? true Position? 2 Default value None Accept pipeline input? false Accept wildcard characters? false -ConfigurationTypeName <string> Specifies the fully qualified name of the Microsoft .NET Framework type that is used for this configuration. The type that you specify must im plement the System.Management.Automation.Remoting.PSSessionConfiguratio n class. To specify the assembly file (.dll) that implements the configuration t ype, use the AssemblyName and AssemblyBase parameters. Creating a type allows you to control more aspects of the session confi guration, such as exposing or hiding certain parameters of cmdlets, or setting data size and object size limits that users cannot override. If you omit this parameter, the DefaultRemotePowerShellConfiguration cl ass is used for the session configuration. Required? true Position? 3 Default value System.Management.Automation.Remoting.PSSe ssionConfiguration Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Suppresses all users prompts and restarts the WinRM service without pro mpting. Restarting the service makes the configuration change effective . To prevent a restart and suppress the restart prompt, use the NoService Restart parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -MaximumReceivedDataSizePerCommandMB <double> Limits the amount of data that can be sent to this computer in any sing le remote command. Enter the data size in megabytes (MB). The default i s 50 MB. If a data size limit is defined in the configuration type that is speci fied in the ConfigurationTypeName parameter, the limit in the configura tion type is used and the value of this parameter is ignored. Required? false Position? named Default value 50 Accept pipeline input? false Accept wildcard characters? false -MaximumReceivedObjectSizeMB <double> Limits the amount of data that can be sent to this computer in any sing le object. Enter the data size in megabytes (MB). The default is 10 MB. If an object size limit is defined in the configuration type that is sp ecified in the ConfigurationTypeName parameter, the limit in the config uration type is used and the value of this parameter is ignored. Required? false Position? named Default value 10 Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies a name for the session configuration. This parameter is requi red. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -NoServiceRestart [<SwitchParameter>] Does not restart the WinRM service, and suppresses the prompt to restar t the service. By default, when you enter a Register-PSSessionConfiguration command, y ou are prompted to restart the WinRM service to make the new session co nfiguration effective. Until the WinRM service is restarted, the new s ession configuration is not effective. To restart the WinRM service without prompting, use the Force parameter . To restart the WinRM service manually, use the Restart-Service cmdlet . Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -ProcessorArchitecture <string> Specifies a processor architecture for the configuration. This value de termines whether a 32-bit or 64-bit version of the process that hosts W indows PowerShell is started when the configuration is used. Valid valu es are x86, AMD64, and IA64. The default is determined by the processor architecture of the computer that hosts the session configuration. Required? false Position? named Default value The processor architecture of the host com puter. Accept pipeline input? false Accept wildcard characters? false -SecurityDescriptorSDDL <string> Specifies a Security Descriptor Definition Language (SDDL) string for t he configuration. This string determines the permissions that are required to use the new session configuration. To use a session configuration in a session, us ers must have at least "Execute(Invoke)" permission for the configurati on. If the security descriptor is complex, consider using the ShowSecurityD escriptorUI parameter instead of this parameter. You cannot use both pa rameters in the same command. If you omit this parameter, the root SDDL for the WinRM service is used for this configuration. To view or change the root SDDL, use the WS-Ma nagement provider. For example "get-item wsman:\localhost\service\rootS DDL". For more information about the WS-Management provider, type "get- help wsman". Required? false Position? named Default value The value of the root SDDL Accept pipeline input? false Accept wildcard characters? false -ShowSecurityDescriptorUI [<SwitchParameter>] Displays a property sheet that helps you to create the SDDL for the ses sion configuration. The property sheet appears after you enter the Regi ster-PSSessionConfiguration command and then restart the WinRM service. When setting the permissions for the configuration, remember that users must have at least "Execute(Invoke)" permission to use the session con figuration in a session. You cannot use the SecurityDescriptorSDDL parameter and this parameter in the same command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -StartupScript <string> Specifies the fully qualified path to a Windows PowerShell script. The specified script runs in the new session that uses the session configur ation. You can use the script to further configure the session. If the script generates an error (even a non-terminating error), the session is not c reated and the user's New-PSSession command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ThreadApartmentState <ApartmentState> Determines the apartment state of the threads in the session. Valid val ues are STA, MTA, and Unknown. Unknown is the default. Required? false Position? named Default value Unknown Accept pipeline input? false Accept wildcard characters? false -ThreadOptions <PSThreadOptions> Defines how threads are created and used when a command is executed in the session. Valid values are Default, ReuseThread, UseCurrentThread, a nd UseNewThread. UseCurrentThread is the default. Required? false Position? named Default value UseCurrentThread Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS Microsoft.WSMan.Management.WSManConfigContainerElement NOTES To run this cmdlet on Windows Vista, Windows Server 2008, and later ver sions of Windows, you must start Windows PowerShell with the "Run as ad ministrator" option. This cmdlet generates XML that represents a Web Services for Management (WS-Management) plug-in configuration and sends the XML to WS-Manageme nt, which registers the plug-in on the local computer ("new-item wsman: \localhost\plugin"). -------------------------- EXAMPLE 1 -------------------------- C:\PS>register-pssessionConfiguration -name NewShell -applicationBase c:\My Shells\ -assemblyName MyShell.dll -configurationTypeName MyClass Description ----------- This command registers the NewShell session configuration. It uses the Appl icationName and ApplicationBase parameters to specify the location of the M yShell.dll file, which specifies the cmdlets and providers in the session c onfiguration. It also uses the ConfigurationTypeName parameter to specify a new class that further configures the session. To use this configuration, users would type "new-pssession -configurationna me newshell". -------------------------- EXAMPLE 2 -------------------------- C:\PS>register-pssessionConfiguration -name MaintenanceShell -startupScript c:\ps-test\Maintenance.ps1 Description ----------- This command registers the MaintenanceShell configuration on the local comp uter. The command uses the StartupScript parameter to specify the Maintenan ce.ps1 script. When a user uses a New-PSSession command and selects the MaintenanceShell c onfiguration, the Maintenance.ps1 script runs in the new session. The scrip t can configure the session, including importing modules, adding Windows Po werShell snap-ins, and setting the execution policy for the session. If the script generates any errors, including non-terminating errors, the New-PSS ession command fails. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$sddl = "O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;FA;SA;GWGX;;WD) " C:\PS> register-pssessionconfiguration -name AdminShell -securityDescriptor SDDL $sddl -maximumReceivedObjectSizeMB 20 -startupScript c:\scripts\AdminS hell.ps1 Description ----------- This example registers the AdminShell session configuration. The first command saves a custom SDDL in the $sddl variable. The second command registers the new shell. The command uses the SecurityDe scritorSDDL parameter to specify the SDDL in the value of the $sddl variabl e and the MaximumReceivedObjectSizeMB parameter to increase the object size limit. It also uses the StartupScript parameter to specify a script that c onfigures the session. As an alternative to using the SecurityDescriptorSDDL parameter, you can us e the ShowSecurityDescriptorUI parameter, which displays a property sheet t hat you can use to set permissions for the session configuration. When you click "OK" in the property sheet, the tool generates an SDDL for the sessio n configuration. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$s = register-pssessionConfiguration -name MaintenanceShell -startupS cript c:\ps-test\Maintenance.ps1 C:\PS> $s WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin Name Type Keys ---- ---- ---- MaintenanceShell Container {Name=MaintenanceShell} C:\PS> $s.getType().fullname TypeName: Microsoft.WSMan.Management.WSManConfigContainerElement C:\PS> $s | format-list -property * PSPath : Microsoft.WSMan.Management\WSMan::localhost\Plugin\Main tenanceShell PSParentPath : Microsoft.WSMan.Management\WSMan::localhost\Plugin PSChildName : MaintenanceShell PSDrive : WSMan PSProvider : Microsoft.WSMan.Management\WSMan PSIsContainer : True Keys : {Name=MaintenanceShell} Name : MaintenanceShell TypeNameOfElement : Container C:\PS> dir wsman:\localhost\plugin Name Type Keys ---- ---- ---- MaintenanceShell Container {Name=MaintenanceShell} microsoft.powershell Container {Name=microsoft.powershell} microsoft.powershell32 Container {Name=microsoft.powershell32 } Description ----------- This example shows that a Register-PSSessionConfiguration command returns a WSManConfigContainerElement. It also shows how to find the container eleme nts in the WSMan: drive. The first command uses the Register-PSSessionConfiguration cmdlet to regist er the MaintenanceShell configuration. It saves the object that the cmdlet returns in the $s variable. The second command displays the contents of the $s variable. The third command uses the GetType method and its FullName property to disp lay the type name of the object that Register-PSSessionConfiguration return s. The fourth command uses the Format-List cmdlet to display all the propertie s of the object that Register-PSSessionConfiguration returns in a list. The PSPath property shows that the object is stored in a directory of the WSMa n: drive. The fifth command uses the Get-ChildItem cmdlet to display the items in the WSMan:\LocalHost\PlugIn path. These include the new MaintenanceShell confi guration and the two default configurations that come with Windows PowerShe ll. -------------------------- EXAMPLE 5 -------------------------- C:\PS>register-pssessionconfiguration -name WithProfile -startupScript add- profile.ps1 # Add-Profile.ps1 . c:\users\admin01\documents\windowspowershell\profile.ps1 Description ----------- This command creates and registers the WithProfile session configuration on the local computer. The command uses the StartupScript parameter to direct Windows PowerShell to run the specified script in any session that uses th e session configuration. The content of the specified script, Add-Profile.ps1, is also displayed. Th e script contains a single command that uses dot sourcing to run the user's CurrentUserAllHosts profile in the current scope of the session. For more information about profiles, see about_Profiles. For more informati on about dot sourcing, see about_Scopes. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144306 about_Session_Configurations Disable-PSSessionConfiguration Enable-PSSessionConfiguration Get-PSSessionConfiguration Set-PSSessionConfiguration Unregister-PSSessionConfiguration WS-Management Provider Register-WmiEvent NAME Register-WmiEvent SYNOPSIS Subscribes to a Windows Management Instrumentation (WMI) event. SYNTAX Register-WmiEvent [-Class] <string> [[-SourceIdentifier] <string>] [[-Actio n] <scriptblock>] [-ComputerName <string>] [-Credential <PSCredential>] [-F orward] [-MessageData <psobject>] [-Namespace <string>] [-SupportEvent] [-T imeout <Int64>] [<CommonParameters>] Register-WmiEvent [-Query] <string> [[-SourceIdentifier] <string>] [[-Actio n] <scriptblock>] [-ComputerName <string>] [-Credential <PSCredential>] [-F orward] [-MessageData <psobject>] [-Namespace <string>] [-SupportEvent] [-T imeout <Int64>] [<CommonParameters>] DESCRIPTION The Register-WmiEvent cmdlet subscribes to WMI events on the local computer or on a remote computer. When the subscribed WMI event is raised, it is added to the event queue in your local session even if the event occurs on a remote computer. To get ev ents in the event queue, use the Get-Event cmdlet. You can use the parameters of Register-WmiEvent to subscribe to events on r emote computers and to specify the property values of the events that can h elp you to identify the event in the queue. You can also use the Action par ameter to specify actions to take when a subscribed event is raised. When you subscribe to an event, an event subscriber is added to your sessio n. To get the event subscribers in the session, use the Get-EventSubscriber cmdlet. To cancel the subscription, use the Unregister-Event cmdlet, which deletes the event subscriber from the session. PARAMETERS -Action <scriptblock> Specifies commands that handle the events. The commands in the Action p arameter run when an event is raised instead of sending the event to th e event queue. Enclose the commands in braces ( { } ) to create a scrip t block. The value of the Action parameter can include the $Event, $EventSubscri ber, $Sender, $SourceEventArgs, and $SourceArgs automatic variables, wh ich provide information about the event to the Action script block. For more information, see about_Automatic_Variables. When you specify an action, Register-WmiEvent returns an event job obje ct that represents that action. You can use the cmdlets that contain th e Job noun (the Job cmdlets) to manage the event job. Required? false Position? 102 Default value The event is added to the event queue. Accept pipeline input? false Accept wildcard characters? false -Class <string> Specifies the event to which you are subscribing. Enter the WMI class t hat generates the events. A Class or Query parameter is required in eve ry command. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies a remote computer. The default is the local computer. Enter a NetBIOS name, an IP address, or a fully qualified domain name. Required? false Position? named Default value Local computer Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Ty pe a user name, such as "User01" or "Domain01\User01". Or, enter a PSCr edential object, such as one from the Get-Credential cmdlet. If you typ e a user name, you will be prompted for a password. Required? false Position? named Default value The credentials of the current user Accept pipeline input? false Accept wildcard characters? false -Forward [<SwitchParameter>] Sends events for this subscription to the session on the local computer . Use this parameter when you are registering for events on a remote co mputer or in a remote session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -MessageData <psobject> Specifies any additional data to be associated with this event subscrip tion. The value of this parameter appears in the MessageData property o f all events associated with this subscription. Required? false Position? named Default value None. The MessageData property is NULL. Accept pipeline input? false Accept wildcard characters? false -Namespace <string> Specifies the namespace of the WMI class. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Query <string> Specifies a query in WMI Query Language (WQL) that identifies the WMI e vent class, such as "select * from __InstanceDeletionEvent". Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -SourceIdentifier <string> Specifies a name that you select for the subscription. The name that yo u select must be unique in the current session. The default value is th e GUID that Windows PowerShell assigns. The value of this parameter appears in the value of the SourceIdentifie r property of the subscriber object and of all event objects associated with this subscription. Required? false Position? 101 Default value GUID Accept pipeline input? false Accept wildcard characters? false -SupportEvent [<SwitchParameter>] Hides the event subscription. Use this parameter when the current subsc ription is part of a more complex event registration mechanism and it s hould not be discovered independently. To view or cancel a subscription that was created with the SupportEvent parameter, use the Force parameter of the Get-EventSubscriber and Unre gister-Event cmdlets. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Timeout <Int64> Determines how long Windows PowerShell waits for this command to comple te. The default value, 0 (zero), means that there is no time-out, and it ca uses Windows PowerShell to wait indefinitely. Required? false Position? named Default value 0 Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to Register-WmiEvent. OUTPUTS None This cmdlet does not generate any output. NOTES To use this cmdlet in Windows Vista or a later version of Windows, star t Windows PowerShell with the "Run as administrator" option. Events, event subscriptions, and the event queue exist only in the curr ent session. If you close the current session, the event queue is disca rded and the event subscription is canceled. -------------------------- EXAMPLE 1 -------------------------- C:\PS>register-wmiEvent -class 'Win32_ProcessStartTrace' -sourceIdentifier "ProcessStarted" Description ----------- This command subscribes to the events generated by the Win32_ProcessStartTr ace class. This class raises an event whenever a process starts. -------------------------- EXAMPLE 2 -------------------------- C:\PS>register-wmiEvent -query "select * from __instancecreationevent withi n 5 where targetinstance isa 'win32_process'" -sourceIdentifier "WMIProcess " -messageData "Test 01" -timeout 500 Description ----------- This command uses a query to subscribe to Win32_process instance creation e vents. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$action = { get-history | where { $_.commandline -like "*start-proces s*" } | export-cliXml "commandHistory.clixml" } C:\PS> register-wmiEvent -class 'Win32_ProcessStartTrace' -sourceIdentifier "ProcessStarted" -action $action Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 ProcessStarted NotStarted False get-history | wher e {... Description ----------- This example shows how to use an action to respond to an event. In this cas e, when a process starts, any Start-Process commands in the current session are written to an XML file. When you use the Action parameter, Register-WmiEvent returns a background j ob that represents the event action. You can use the Job cmdlets, such as G et-Job and Receive-Job, to manage the event job. For more information, see about_Jobs. -------------------------- EXAMPLE 4 -------------------------- C:\PS>register-wmiEvent -class 'Win32_ProcessStartTrace' -sourceIdentifier "Start" -computername Server01 C:\PS> get-event -sourceIdentifier "Start" Description ----------- This example registers for events on the Server01 remote computer. WMI returns the events to the local computer and stores them in the event q ueue in the current session. To retrieve the events, run a local Get-Event command. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135245 Register-ObjectEvent Register-EngineEvent Unregister-Event Get-Event New-Event Remove-Event Wait-Event Registry PROVIDER NAME Registry DRIVES HKLM:, HKCU: SYNOPSIS Provides access to the system registry keys and values from Windows PowerSh ell. DESCRIPTION The Windows PowerShell Registry provider lets you get, add, change, clear, and delete registry keys and values in Windows PowerShell. Registry keys are represented as instances of the Microsoft.Win32.RegistryK ey class. Registry values are represented as instances of the PSCustomObjec t class. The Registry provider lets you access a hierarchical namespace that consist s of registry keys and subkeys. Registry values and data are not components of that hierarchy. Instead, they are properties of each of the keys. The Registry provider supports all the cmdlets that contain the Item noun ( the Item cmdlets), such as Get-Item, Copy-Item, and Rename Item. Use the It em cmdlets when you work with registry keys and subkeys. The Registry provi der also supports the cmdlets that contain the ItemProperty noun (the ItemP roperty cmdlets). Use the ItemProperty cmdlets when you work with registry values and data. You cannot use the cmdlets that contain the Content noun ( the Content cmdlets) with the Registry provider. Each registry key is protected by a security descriptor. You can use Get-Ac l to view the security descriptor of a key. CAPABILITIES ShouldProcess TASKS TASK: Navigating the Registry -------------------------- EXAMPLE 1 -------------------------- This command sets the current location to the HKEY_LOCAL_MACHINE\Softwa re registry key: set-location hklm:\software -------------------------- EXAMPLE 2 -------------------------- This command displays the current location: get-location TASK: Managing Registry Keys -------------------------- EXAMPLE 1 -------------------------- This command displays information about each immediate subkey of the HK EY_LOCAL_MACHINE\Software registry key: get-childitem -path hklm:\software -------------------------- EXAMPLE 2 -------------------------- This command creates the TestNew subkey under the HKCU:\Environment sub key: new-item -path hkcu:\Environment\TestNew -------------------------- EXAMPLE 3 -------------------------- This command removes the TestNew subkey of the HKEY_CURRENT_USER\Enviro nment key: remove-item -path hkcu:\Environment\TestNew -------------------------- EXAMPLE 4 -------------------------- This command copies the TestNew key to the TestCopy subkey: copy-item -path hkcu:\Environment\TestNew hkcu:\Environment\TestNew\T estCopy -------------------------- EXAMPLE 5 -------------------------- This command displays information about all the subkeys of the HKEY_LOC AL_MACHINE\Software registry key: get-childitem -path hklm:\Software -recurse -------------------------- EXAMPLE 6 -------------------------- This command moves the HKEY_CURRENT_USER\Environment\testnewcopy regist ry key, its properties, and all its subkeys and their properties to HKE Y_CURRENT_USER\Environment\testnew: move-item -path hkcu:\environment\testnewcopy ` -destination hkcu:\environment\testnew -------------------------- EXAMPLE 7 -------------------------- This command renames the HKEY_CURRENT_USER\Environment\testnew registry key to HKEY_CURRENT_USER\Environment\test: rename-item -path hkcu:\environment\testnew\ -newname test -------------------------- EXAMPLE 8 -------------------------- This command displays the security descriptor for the specified registr y item: get-acl -path hkcu:\environment\testnew | format-list -property * TASK: Managing Registry Entries -------------------------- EXAMPLE 1 -------------------------- This command displays the value name and value data for each registry e ntry in the HKEY_CURRENT_USER\Environment registry key: get-itemproperty -path hkcu:\Environment The Default registry entry is returned only if it has a value. -------------------------- EXAMPLE 2 -------------------------- This command displays the value name and value data for the Temp regist ry entry in the HKEY_CURRENT_USER\Environment registry key: get-itemproperty -path hkcu:\Environment -name Temp -------------------------- EXAMPLE 3 -------------------------- This command creates the pstest registry entry in the HKEY_CURRENT_USER key and sets its value to pstestvalue: new-itemproperty -path hkcu:\environment -name "pstest" -value "pstestv alue" -------------------------- EXAMPLE 4 -------------------------- This command updates the value of the pstest registry entry to updatedv alue in the HKEY_CURRENT_USER\Environment key: set-itemproperty -path hkcu:\environment -name pstest -value "updatedvalue" -------------------------- EXAMPLE 5 -------------------------- This command renames the value name of the pstest registry entry to pst estnew in the HKEY_CURRENT_USER\Environment key: rename-itemproperty -path hkcu:\environment -name pstest ` -newname pstestnew -------------------------- EXAMPLE 6 -------------------------- This command copies the pstestnew registry entry from the HKEY_CURRENT_ USER\Environment key to the HKEY_CURRENT_USER\Environment\testnewcopy k ey: copy-itemproperty -path hkcu:\environment ` -destination hkcu:\environment\testnewcopy -name pstestnew -------------------------- EXAMPLE 7 -------------------------- The command moves the pstestnew registry entry from the HKEY_CURRENT_US ER\environment\testnewcopy key to the HKEY_CURRENT_USER\environment\tes tnew key: move-itemproperty -path hkcu:\environment\testnewcopy ' -destination hkcu:\environment\testnew -name pstestnew -------------------------- EXAMPLE 8 -------------------------- This command clears the value of the pstestnew registry entry in the HK EY_CURRENT_USER\Environment\testnew key: clear-itemproperty -path hkcu:\environment\testnew -name pstestnew You can use the Clear-Item cmdlet to clear the value of the default reg istry entry for a subkey. For example, the following command clears the value of the default entry of the HKEY_CURRENT_USER\Environment\testne w registry key: clear-item -path hkcu:\environment\testnew -------------------------- EXAMPLE 9 -------------------------- This command removes the pstestnew registry entry from the HKEY_CURRENT _USER\Environment\testnew registry key: remove-itemproperty -path hkcu:\environment\testnew ` -name pstestnew -------------------------- EXAMPLE 10 -------------------------- This command updates the value of the default registry entry in the HKE Y_CURRENT_USER\Environment\testnew key to "default value": set-itemproperty -path hkcu:\environment\testnew ` -name "(default)" -value "default value" You can also update the default value of a registry key by using the Se t-Item cmdlet. For example, the following command updates the default v alue of the testnew key: set-item -path hkcu:\environment\testnew -value "another default value" DYNAMIC PARAMETERS -Type <Microsoft.Win32.RegistryValueKind> Specifies the data types to use when storing values in the registry, or identifies the data type of a value in the registry. String Specifies a null-terminated string. Equivalent to REG_SZ. ExpandString Specifies a null-terminated string that contains unexpanded ref erences to environment variables that are expanded when the val ue is retrieved. Equivalent to REG_EXPAND_SZ. Binary Specifies binary data in any form. Equivalent to REG_BINARY. DWord Specifies a 32-bit binary number. Equivalent to REG_DWORD. MultiString Specifies an array of null-terminated strings terminated by two null characters. Equivalent to REG_MULTI_SZ. QWord Specifies a 64-bit binary number. Equivalent to REG_QWORD. Unknown Indicates an unsupported registry data type, such as REG_RESOUR CE_LIST. Cmdlets Supported: Set-Item NOTES RELATED LINKS about_Providers Remove-Computer NAME Remove-Computer SYNOPSIS Remove the local computer from a workgroup or domain. SYNTAX Remove-Computer [[-Credential] <PSCredential>] [-Force] [-PassThru] [-Confi rm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Remove-Computer cmdlet removes the local computer from its current work group or domain. When you remove a computer from a domain, Remove-Computer also disables the computer's domain account. When the computer is in a domain, you must provide credentials, even when t hey are the credentials of the current user, and you must restart the compu ter to make the change effective. To get the results of the command, use the Verbose and PassThru parameters. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. To remove a computer from a domain, you must use the Credential paramet er, even when you are using the credentials of the current user. Required? false Position? 2 Default value The credentials of the current user Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns the results of the command. Otherwise, this cmdlet does not gen erate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet OUTPUTS Microsoft.PowerShell.Commands.ComputerChangeInfo When you use the PassThru parameter, Remove-Computer returns a Computer ChangeInfo object. Otherwise, this cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-computer Description ----------- This command removes the computer from a workgroup. -------------------------- EXAMPLE 2 -------------------------- C:\PS>remove-computer -credential domain01\admin01 -passthru -verbose; rest art-computer Description ----------- These commands remove the local computer from the domain to which it is joi ned. The first command removes the computer from the domain. The command uses th e Credential parameter to supply the credentials of a domain administrator. It uses the PassThru parameter and the Verbose common parameter to display information about the success or failure of the command. The second command uses the Restart-Computer cmdlet to restart the computer , which is required to complete the remove operation. The semi-colon (;) separates the two commands. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135246 Add-Computer Checkpoint-Computer Remove-Computer Restart-Computer Restore-Computer Stop-Computer Test-Connection Remove-Event NAME Remove-Event SYNOPSIS Deletes events from the event queue. SYNTAX Remove-Event [-EventIdentifier] <int> [-Confirm] [-WhatIf] [<CommonParamete rs>] Remove-Event [-SourceIdentifier] <string> [-Confirm] [-WhatIf] [<CommonPara meters>] DESCRIPTION The Remove-Event cmdlet deletes events from the event queue in the current session. This cmdlet deletes only the events currently in the queue. To cancel event registrations or unsubscribe, use the Unregister-Event cmdlet. PARAMETERS -EventIdentifier <int> Deletes only the event with the specified event identifier. An EventIde ntifier or SourceIdentifier parameter is required in every command. Required? true Position? 1 Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -SourceIdentifier <string> Deletes only the events with the specified source identifier. Wildcards are not permitted. An EventIdentifier or SourceIdentifier parameter is required in every command. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSEventArgs You can pipe events from Get-Event to Remove-Event. OUTPUTS None The cmdlet does not generate any output. NOTES Events, event subscriptions, and the event queue exist only in the curr ent session. If you close the current session, the event queue is disca rded and the event subscription is canceled. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-event -sourceIdentifier "ProcessStarted" Description ----------- This command deletes events with a source identifier of "Process Started" f rom the event queue. -------------------------- EXAMPLE 2 -------------------------- C:\PS>remove-event -eventIdentifier 30 Description ----------- This command deletes the event with an event ID of 30 from the event queue. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-event | remove-event Description ----------- This command deletes all events from the event queue. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135247 Register-ObjectEvent Register-EngineEvent Register-WmiEvent Unregister-Event Get-Event New-Event Remove-Event Wait-Event Remove-EventLog NAME Remove-EventLog SYNOPSIS Deletes an event log or unregisters an event source. SYNTAX Remove-EventLog [-LogName] <string[]> [[-ComputerName] <string[]>] [-Confir m] [-WhatIf] [<CommonParameters>] Remove-EventLog [[-ComputerName] <string[]>] [-Source <string[]>] [-Confirm ] [-WhatIf] [<CommonParameters>] DESCRIPTION The Remove-EventLog cmdlet deletes an event log file from a local or remote computer and unregisters all of its event sources for the log. You can als o use this cmdlet to unregister event sources without deleting any event lo gs. The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinE vent. PARAMETERS -ComputerName <string[]> Specifies a remote computer. The default is the local computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qu alified domain name of a remote computer. To specify the local computer , type the computer name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Remove-EventLog even if your computer i s not configured to run remote commands. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -LogName <string[]> Specifies the event logs. Enter the log name (the value of the Log prop erty; not the LogDisplayName) of one or more event logs , separated by commas. Wildcard characters are not permitted. This parameter is requi red. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Source <string[]> Unregisters the specified event sources. Enter the source names (not th e executable name), separated by commas. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not return any output. NOTES To use Remove-EventLog on Windows Vista and later versions of Windows, start Windows PowerShell with the "Run as administrator" option. If you remove an event log and then re-create the log, you will not be able to register the same event sources. Applications that used the eve nts sources to write entries to the original log will not be able to wr ite to the new log. When you unregister an event source for a particular log, the event sou rce might be prevented from writing entries in other event logs. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-eventlog -logname MyLog Description ----------- This command deletes the MyLog event log from the local computer and unregi sters its event sources. -------------------------- EXAMPLE 2 -------------------------- C:\PS>remove-eventlog -logname MyLog, TestLog -computername Server01, Serve r02, localhost Description ----------- This command deletes the MyLog and TestLog event logs from the local comput er ("localhost") and the Server01 and Server02 remote computers. The comman d also unregisters the event sources for these logs. -------------------------- EXAMPLE 3 -------------------------- C:\PS>remove-eventlog -source MyApp Description ----------- This command deletes the MyApp event source from the logs on the local comp uter. When the command completes, the MyApp program cannot write to any eve nt logs. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-eventlog -list Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 15,168 0 OverwriteAsNeeded 22,923 Application 15,168 0 OverwriteAsNeeded 53 DFS Replication 512 7 OverwriteOlder 0 Directory Service 15,168 7 OverwriteOlder 0 Hardware Events 512 7 OverwriteOlder 0 Internet Explorer 20,480 0 OverwriteAsNeeded 0 Key Management Service 30,016 0 OverwriteAsNeeded 50,060 Security 15,168 0 OverwriteAsNeeded 27,592 System 15,360 0 OverwriteAsNeeded 18,355 Windows PowerShell 15,168 7 OverwriteAsNeeded 12 ZapLog C:\PS> remove-eventlog -logname ZapLog C:\PS> get-eventlog -list Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 15,168 0 OverwriteAsNeeded 22,923 Application 15,168 0 OverwriteAsNeeded 53 DFS Replication 512 7 OverwriteOlder 0 Directory Service 15,168 7 OverwriteOlder 0 Hardware Events 512 7 OverwriteOlder 0 Internet Explorer 20,480 0 OverwriteAsNeeded 0 Key Management Service 30,016 0 OverwriteAsNeeded 50,060 Security 15,168 0 OverwriteAsNeeded 27,592 System 15,360 0 OverwriteAsNeeded 18,355 Windows PowerShell Description ----------- These commands show how to list the event logs on a computer and verify tha t a Remove-EventLog command was successful. The first command lists the event logs on the local computer. The second command deletes the ZapLog event log. The third command lists the event logs again. The ZapLog event log no longe r appears in the list. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-wmiobject win32_nteventlogfile -filter "logfilename='TestLog'" | foreach {$_.sources} MyApp TestApp C:\PS> remove-eventlog -source MyApp C:\PS> get-wmiobject win32_nteventlogfile -filter "logfilename='TestLog'} | foreach {$_.sources} TestApp Description ----------- These commands use the Get-WmiObject cmdlet to list the event sources on th e local computer. You can these commands to verify the success of a command or to delete an event source. The first command gets the event sources of the TestLog event log on the lo cal computer. MyApp is one of the sources. The second command uses the Source parameter of Remove-EventLog to delete t he MyApp event source. The third command is identical to the first. It shows that the MyApp event source was deleted. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135248 Clear-EventLog Get-EventLog Limit-EventLog New-EventLog Remove-EventLog Show-EventLog Write-EventLog Get-WinEvent Remove-Item NAME Remove-Item SYNOPSIS Deletes the specified items. SYNTAX Remove-Item [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclud e <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Recurse] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] Remove-Item [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <stri ng[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-Recurse] [-Confi rm] [-WhatIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Remove-Item cmdlet deletes one or more items. Because it is supported b y many providers, it can delete many different types of items, including fi les, directories, registry keys, variables, aliases, and functions. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to remove items that cannot otherwise be changed, suc h as hidden or read-only files or read-only aliases or variables. The c mdlet cannot remove constant aliases or variables. Implementation vari es from provider to provider. For more information, see about_Providers . Even using the Force parameter, the cmdlet cannot override security r estrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Deletes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the items being removed. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpret ed as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies a path to the items being removed. Wildcards are permitted. T he parameter name ("-Path") is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Recurse [<SwitchParameter>] Deletes the items in the specified locations and in all child items of the locations. The Recurse parameter in this cmdlet does not work properly. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path (but not a literal path) to Remove-Item. OUTPUTS None This cmdlet does not return any output. NOTES You can also refer to Remove-Item by any of its built-in aliases, "del" , "erase", "rmdir", "rd", "ri", or "rm". For more information, see abou t_Aliases. The Remove-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-P sProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-item C:\Test\*.* Description ----------- This command deletes all of the files with names that include a dot (.) fro m the C:\Test directory. Because the command specifies a dot, the command d oes not delete directories or files with no file name extension. -------------------------- EXAMPLE 2 -------------------------- C:\PS>remove-item * -include *.doc -exclude *1* Description ----------- This command deletes from the current directory all files with a .doc file name extension and a name that does not include "1". It uses the wildcard c haracter (*) to specify the contents of the current directory. It uses the Include and Exclude parameters to specify the files to delete. -------------------------- EXAMPLE 3 -------------------------- C:\PS>remove-item -path C:\Test\hidden-RO-file.txt -force Description ----------- This command deletes a file that is both hidden and read-only. It uses the Path parameter to specify the file. It uses the Force parameter to give per mission to delete it. Without Force, you cannot delete read-only or hidden files. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-childitem * -include *.csv -recurse | remove-item Description ----------- This command deletes all of the CSV files in the current directory and all subdirectories recursively. Because the Recurse parameter in this cmdlet is faulty, the command uses th e Get-Childitem cmdlet to get the desired files, and it uses the pipeline o perator to pass them to the Remove-Item cmdlet. In the Get-ChildItem command, the Path parameter has a value of *, which re presents the contents of the current directory. It uses the Include paramet er to specify the CSV file type, and it uses the Recurse parameter to make the retrieval recursive. If you try to specify the file type in the path, such as "-path *.csv", the cmdlet interprets the subject of the search to be a file that has no child items, and Recurse fails. -------------------------- EXAMPLE 5 -------------------------- C:\PS>remove-item hklm:\software\mycompany\OldApp -recurse Description ----------- This command deletes the OldApp registry key and all of its subkeys and val ues. It uses the Remove-Item cmdlet to remove the key. The path is specifie d, but the optional parameter name (Path) is omitted. The Recurse parameter deletes all of the contents of the OldApp key recursi vely. If the key contains subkeys and you omit the Recurse parameter, you a re prompted to confirm that you want to delete the contents of the key. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113373 about_Providers Clear-Item Copy-Item Get-Item Invoke-Item Move-Item New-Item Remove-ItemProperty Rename-Item Set-Item Remove-ItemProperty NAME Remove-ItemProperty SYNOPSIS Deletes the property and its value from an item. SYNTAX Remove-ItemProperty [-LiteralPath] <string[]> [-Name] <string[]> [-Credenti al <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Incl ude <string[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] Remove-ItemProperty [-Path] <string[]> [-Name] <string[]> [-Credential <PSC redential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <st ring[]>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Remove-ItemProperty cmdlet deletes a property and its value from an ite m. You can use it to delete registry values and the data that they store. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to remove a property of an object that cannot otherwi se be accessed by the user. Implementation varies from provider to prov ider. For more information, see about_Providers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Deletes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation ma rks. Single quotation marks tell Windows PowerShell not to interpret an y characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Specifies the names of the properties to be retrieved. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the path to the item whose properties are being removed. Wild cards are permitted. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path (but not a literal path) to Remove-ItemProperty. OUTPUTS None This cmdlet does not return any output. NOTES You can also refer to Remove-ItemProperty by its built-in alias, "rp". For more information, see about_Alias. In the Windows PowerShell Registry provider, registry values are consid ered to be properties of a registry key or subkey. You can use the Item Property cmdlets to manage these values. The Remove-ItemProperty cmdlet is designed to work with the data expose d by any provider. To list the providers available in your session, typ e "Get-PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-itemproperty -path HKLM:\Software\SmpApplication -name SmpProp erty Description ----------- This command deletes the SmpProperty registry value, and its data, from the SmpApplication subkey of the HKEY_LOCAL_MACHINE\Software registry key. Because the command is issued from a file system drive (C:\PS>), it include s the fully qualified path to the SmpApplication subkey, including the driv e, HKLM:, and the Software key. It uses the Name parameter to identify the registry value that is being del eted. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-location HKCU:\Software\MyCompany\MyApp PS HKCU:\Software\MyCompany\MyApp> remove-itemproperty -path . -Name Option s -confirm Description ----------- These commands delete the Options registry value, and its data, from the My App subkey of HKEY_CURRENT_USER\Software\MyCompany. The first command uses the Set-Location cmdlet to change the current locati on to the HKEY_CURRENT_USER drive (HKCU:) and the Software\MyCompany\MyApp subkey. The second command uses the Remove-Item cmdlet to remove the Options regist ry value, and its data, from the MyApp subkey. Because the Path parameter i s required, the command uses a dot (.) to indicate the current location. It uses the Name parameter to specify which registry value to delete. It uses the Confirm parameter to request a user prompt before deleting the value. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-item -path HKLM:\Software\MyCompany | remove-itemproperty -name N oOfEmployees Description ----------- This command deletes the NoOfEmployees registry value, and its data, from t he HKLM\Software\MyCompany registry key. The command uses the Get-Item cmdlet to get an item that represents the reg istry key. It uses a pipeline operator (|) to send the object to the Remove -ItemProperty cmdlet. Then, it uses the Name parameter of Remove-ItemProper ty to specify the name of the registry value. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113374 about_Providers Clear-ItemProperty Copy-ItemProperty Get-ItemProperty Move-ItemProperty New-ItemProperty Remove-Item Rename-ItemProperty Set-ItemProperty Remove-Job NAME Remove-Job SYNOPSIS Deletes a Windows PowerShell background job. SYNTAX Remove-Job [-Id] <Int32[]> [-Force] [-Confirm] [-WhatIf] [<CommonParameters >] Remove-Job [-Command <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>] Remove-Job [[-InstanceId] <Guid[]>] [-Force] [-Confirm] [-WhatIf] [<CommonP arameters>] Remove-Job [-Job] <Job[]> [-Force] [-Confirm] [-WhatIf] [<CommonParameters> ] Remove-Job [[-Name] <string[]>] [-Force] [-Confirm] [-WhatIf] [<CommonParam eters>] Remove-Job [-State {NotStarted | Running | Completed | Failed | Stopped | B locked}] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Remove-Job cmdlet deletes Windows PowerShell background jobs that were started by using Start-Job or the AsJob parameter of any cmdlet. You can use this cmdlet to delete all jobs or delete selected jobs based on their name, ID, instance ID, command, or state, or by passing a job object to Remove-Job. Without parameters or parameter values, Remove-Job has no e ffect. Before deleting a running job, use the Stop-Job cmdlet to stop the job. If you try to delete a running job, the command fails. You can use the Force p arameter of Remove-Job to delete a running job. If you do not delete a background job, the job remains in the global job ca che until you close the session in which the job was created. PARAMETERS -Command <string[]> Removes jobs that include the specified words in the command. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Force [<SwitchParameter>] Deletes the job even if the status is "Running". Without the Force para meter, Remove-Job will not delete a running job. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Id <Int32[]> Deletes background jobs with the specified IDs. The ID is an integer that uniquely identifies the job within the curren t session. It is easier to remember and type than the instance ID, but it is unique only within the current session. You can type one or more IDs (separated by commas). To find the ID of a job, type "Get-Job" with out parameters. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InstanceId <Guid[]> Deletes jobs with the specified instance IDs. An instance ID is a GUID that uniquely identifies the job on the comput er. To find the instance ID of a job, use Get-Job or display the job ob ject. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Job <Job[]> Specifies the jobs to be deleted. Enter a variable that contains the jo bs or a command that gets the jobs. You can also use a pipeline operato r to submit jobs to the Remove-Job cmdlet. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Name <string[]> Deletes only the jobs with the specified friendly names. Wildcards are permitted. Because the friendly name is not guaranteed to be unique, even within t he session, use the WhatIf and Confirm parameters when deleting jobs by name. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -State <JobState> Deletes only jobs with the specified status. Valid values are NotStarte d, Running, Completed, Stopped, Failed, and Blocked. To delete jobs wit h a status of Running, use the Force parameter. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.Job You can pipe a job object to Remove-Job. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$batch = get-job -name BatchJob C:\PS> $batch | remove-job Description ----------- These commands delete a background job named BatchJob from the current sess ion. The first command uses the Get-Job cmdlet to get an object representin g the job, and then it saves the job in the $batch variable. The second com mand uses a pipeline operator (|) to send the job to the Remove-Job cmdlet. This command is equivalent to using the Job parameter of Remove-Job, for ex ample, "remove-job -job $batch". -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-job | remove-job Description ----------- This command deletes all of the jobs in the current session. -------------------------- EXAMPLE 3 -------------------------- C:\PS>remove-job -state NotStarted Description ----------- This command deletes all jobs from the current session that have not yet be en started. -------------------------- EXAMPLE 4 -------------------------- C:\PS>remove-job -name *batch -force Description ----------- This command deletes all jobs with friendly names that end with "batch" fro m the current session, including jobs that are running. It uses the Name parameter of Remove-Job to specify a job name pattern, and it uses the Force parameter to ensure that all jobs are removed, even thos e that might be in progress. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$j = invoke-command -computername Server01 -scriptblock {get-process} -asJob C:\PS> $j | remove-job Description ----------- This example shows how to use the Remove-Job cmdlet to remove a job that wa s started on a remote computer by using the AsJob parameter of the Invoke-C ommand cmdlet. The first command uses the Invoke-Command cmdlet to run a job on the Server 01 computer. It uses the AsJob parameter to run the command as a background job, and it saves the resulting job object in the $j variable. Because the command used the AsJob parameter, the job object is created on the local computer, even though the job runs on a remote computer. As a res ult, you use local commands to manage the job. The second command uses the Remove-Job cmdlet to remove the job. It uses a pipeline operator (|) to send the job in $j to Remove-Job. Note that this i s a local command. A remote command is not required to remove a job that wa s started by using the AsJob parameter. -------------------------- EXAMPLE 6 -------------------------- C:\PS>$s = new-pssession -computername Server01 C:\PS> invoke-command -session $s -scriptblock {start-job -scriptblock {get -process} -name MyJob} C:\PS> invoke-command -session $s -scriptblock {remove-job -name MyJob} Description ----------- This example shows how to remove a job that was started by using Invoke-Com mand to run a Start-Job command. In this case, the job object is created on the remote computer and you use remote commands to manage the job. The first command uses the New-PSSession cmdlet to create a PSSession (a pe rsistent connection) to the Server01 computer. A persistent connection is r equired when running a Start-Job command remotely. The command saves the PS Session in the $s variable. The second command uses the Invoke-Command cmdlet to run a Start-Job comman d in the PSSession in $s. The job runs a Get-Process command. It uses the N ame parameter of Start-Job to specify a friendly name for the job. The third command uses the Invoke-Command cmdlet to run a Remove-Job comman d in the PSSession in $s. The command uses the Name parameter of Remove-Job to identify the job to be deleted. -------------------------- EXAMPLE 7 -------------------------- C:\PS>$j = start-job -script {get-process powershell} C:\PS> $j | format-list -property * C:\PS> remove-job -instanceID dce2ee73-f8c9-483e-bdd7-a549d8687eed C:\PS> $j = start-job -script {get-process powershell} C:\PS> $j | format-list -property * HasMoreData : False StatusMessage : Location : localhost Command : get-process powershell JobStateInfo : Failed Finished : System.Threading.ManualResetEvent InstanceId : dce2ee73-f8c9-483e-bdd7-a549d8687eed Id : 1 Name : Job1 ChildJobs : {Job2} Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} StateChanged : C:\PS> remove-job -instanceID dce2ee73-f8c9-483e-bdd7-a549d8687eed Description ----------- This example shows how to remove a job based on its instance ID. The first command uses the Start-Job cmdlet to start a background job. The command saves the resulting job object in the $j variable. The second command uses a pipeline operator (|) to send the job object in $ j to a Format-List command. The Format-List command uses the Property param eter with a value of * (all) to display all of the properties of the job ob ject in a list. The job object display shows the values of the ID and InstanceID properties , along with the other properties of the object. The third command uses a Remove-Job command to remove the job from the curr ent session. To generate the command, you can copy and paste the InstanceID value from the object display. To copy a value in the Windows PowerShell console, use the mouse to select the value, and then press Enter to copy it. To paste a value, right-click. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113377 about_Jobs about_Job_Details about_Remote_Jobs Start-Job Get-Job Receive-Job Wait-Job Stop-Job Invoke-Command Remove-Module NAME Remove-Module SYNOPSIS Removes modules from the current session. SYNTAX Remove-Module [-ModuleInfo] <PSModuleInfo[]> [-Force] [-Confirm] [-WhatIf] [<CommonParameters>] Remove-Module [-Name] <string[]> [-Force] [-Confirm] [-WhatIf] [<CommonPara meters>] DESCRIPTION The Remove-Module cmdlet removes the members of a module from the current s ession. If the module includes an assembly (.dll), all members that are implemented by the assembly are removed, but the assembly is not unloaded. PARAMETERS -Force [<SwitchParameter>] Removes modules even when their access mode is read-only. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ModuleInfo <PSModuleInfo[]> Specifies the module objects to remove. Enter a variable that contains a module object (PSModuleInfo) or a command that gets a module object, such as a Get-Module command. You can also pipe module objects to Remov e-Module. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the names of modules to remove. Wildcards are permitted. You can also pipe name strings to Remove-Module. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? true -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String, System.Management.Automation.PSModuleInfo You can pipe module names (strings) and module objects to Remove-Module . OUTPUTS None Remove-Module does not generate any output. NOTES You can also refer to Remove-Module by its alias, "rmo". For more infor mation, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-module -name BitsTransfer Description ----------- This command removes the BitsTransfer module from the current session. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-module | remove-module Description ----------- This command removes all modules from the current session. -------------------------- EXAMPLE 3 -------------------------- C:\PS>"FileTransfer", "PSDiagnostics" | remove-module -verbose VERBOSE: Performing operation "Remove-Module" on Target "filetransfer (Path : 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\f iletransfer\filetransfer.psd1')". VERBOSE: Performing operation "Remove-Module" on Target "Microsoft.Backgrou ndIntelligentTransfer.Management (Path: 'C:\Windows\ assembly\GAC_MSIL\Microsoft.BackgroundIntelligentTransfer.Management\1.0.0. 0__31bf3856ad364e35\Microsoft.BackgroundIntelligentTransfe r.Management.dll')". VERBOSE: Performing operation "Remove-Module" on Target "psdiagnostics (Pat h: 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ psdiagnostics\psdiagnostics.psd1')". VERBOSE: Removing imported function 'Start-Trace'. VERBOSE: Removing imported function 'Stop-Trace'. VERBOSE: Removing imported function 'Enable-WSManTrace'. VERBOSE: Removing imported function 'Disable-WSManTrace'. VERBOSE: Removing imported function 'Enable-PSWSManCombinedTrace'. VERBOSE: Removing imported function 'Disable-PSWSManCombinedTrace'. VERBOSE: Removing imported function 'Set-LogProperties'. VERBOSE: Removing imported function 'Get-LogProperties'. VERBOSE: Removing imported function 'Enable-PSTrace'. VERBOSE: Removing imported function 'Disable-PSTrace'. VERBOSE: Performing operation "Remove-Module" on Target "PSDiagnostics (Pat h: 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ psdiagnostics\PSDiagnostics.psm1')". Description ----------- This command removes the FileTransfer and PSDiagnostics modules from the cu rrent session. The command uses a pipeline operator (|) to send the module names to Remove -Module. It uses the Verbose common parameter to get detailed information a bout the members that are removed. The Verbose messages show the items that are removed. The messages differ b ecause the BitsTransfer module includes an assembly that implements its cmd lets and a nested module with its own assembly. The PSDiagnostics module in cludes a module script file (.psm1) that exports functions. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$a = get-module BitsTransfer C:\PS> remove-module -moduleInfo $a Description ----------- This command uses the ModuleInfo parameter to remove the BitsTransfer modul e. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=141556 Get-Module Import-Module about_modules Remove-PSBreakpoint NAME Remove-PSBreakpoint SYNOPSIS Deletes breakpoints from the current console. SYNTAX Remove-PSBreakpoint [-Id] <Int32[]> [-Confirm] [-WhatIf] [<CommonParameters >] Remove-PSBreakpoint [-Breakpoint] <Breakpoint[]> [-Confirm] [-WhatIf] [<Com monParameters>] DESCRIPTION The Remove-PSBreakpoint cmdlet deletes a breakpoint. Enter a breakpoint obj ect or a breakpoint ID. When you remove a breakpoint, the breakpoint object is no longer available or functional. If you have saved a breakpoint object in a variable, the ref erence still exists, but the breakpoint does not function. Remove-PSBreakpoint is one of several cmdlets designed for debugging Window s PowerShell scripts. For more information about the Windows PowerShell deb ugger, see about_Debuggers. PARAMETERS -Breakpoint <Breakpoint[]> Specifies the breakpoints to delete. Enter a variable that contains bre akpoint objects or a command that gets breakpoint objects, such as a Ge t-PSBreakpoint command. You can also pipe breakpoint objects to Remove- PSBreakpoint. Required? true Position? 1 Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? false -Id <Int32[]> Deletes breakpoints with the specified breakpoint IDs. Required? true Position? 1 Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.Breakpoint You can pipe breakpoint objects to Remove-PSBreakpoint. OUTPUTS None The cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-breakpoint | remove-breakpoint Description ----------- This command deletes all of the breakpoints in the current console. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$b = set-psbreakpoint -script sample.ps1 -variable Name C:\PS> $b | remove-psbreakpoint Description ----------- This command deletes a breakpoint. The first command uses the Set-PSBreakpoint cmdlet to create a breakpoint o n the Name variable in the Sample.ps1 script. Then, it saves the breakpoint object in the $b variable. The second command uses the Remove-PSBreakpoint cmdlet to delete the new br eakpoint. It uses a pipeline operator (|) to send the breakpoint object in the $b variable to the Remove-PSBreakpoint cmdlet. As a result of this command, if you run the script, it runs to completion w ithout stopping. Also, the Get-PSBreakpoint cmdlet does not return this bre akpoint. -------------------------- EXAMPLE 3 -------------------------- C:\PS>remove-psbreakpoint -id 2 Description ----------- This command deletes the breakpoint with breakpoint ID 2. -------------------------- EXAMPLE 4 -------------------------- C:\PS>function del-psb { get-psbreakpoint | remove-psbreakpoint } Description ----------- This simple function deletes all of the breakpoints in the current console. It uses the Get-PSBreakpoint cmdlet to get the breakpoints. Then, it uses a pipeline operator (|) to send the breakpoints to the Remove-PSBreakpoint cmdlet, which deletes them. As a result, you can type "del-psb" instead of the longer command. To save the function, add it to your Windows PowerShell profile. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113375 about_Debuggers Set-PSBreakpoint Get-PSBreakpoint Enable-PSBreakpoint Disable-PSBreakpoint Get-PSCallStack Remove-PSDrive NAME Remove-PSDrive SYNOPSIS Removes a Windows PowerShell drive from its location. SYNTAX Remove-PSDrive [-LiteralName] <string[]> [-Force] [-PSProvider <string[]>] [-Scope <string>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters >] Remove-PSDrive [-Name] <string[]> [-Force] [-PSProvider <string[]>] [-Scope <string>] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Remove-PSDrive cmdlet deletes Windows PowerShell drives that you create d by using New-PSDrive. Remove-PSDrive cannot delete Windows drives or mapped network drives create d by using other methods and it cannot delete the current working drive. PARAMETERS -Force [<SwitchParameter>] Allows the cmdlet to remove the current Windows PowerShell drive. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralName <string[]> Specifies the name of the Windows PowerShell drive. The value of LiteralName is used exactly as typed. No characters are in terpreted as wildcards. If the name includes escape characters, enclose it in single quotation marks ('). Single quotation marks instruct Wind ows PowerShell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Specifies the names of the Windows PowerShell drives to remove. Do not type a colon (:) after the drive name. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PSProvider <string[]> Removes all of the Windows PowerShell drives associated with the specif ied Windows PowerShell provider. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Scope <string> Accepts an index that identifies the scope from which the drive is bein g removed. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSDriveInfo You can pipe a drive object to Remove-PSDrive. OUTPUTS None This cmdlet does not return any output. NOTES The Remove-PSDrive cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "ge t-psprovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-psdrive -name smp Description ----------- This command removes a Windows PowerShell drive named "smp". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113376 about_Providers Get-PSDrive New-PSDrive Remove-PSSession NAME Remove-PSSession SYNOPSIS Closes one or more Windows PowerShell sessions (PSSessions). SYNTAX Remove-PSSession [[-ComputerName] <string[]>] [-Confirm] [-WhatIf] [<Common Parameters>] Remove-PSSession [-Id] <Int32[]> [-Confirm] [-WhatIf] [<CommonParameters>] Remove-PSSession [-InstanceId <Guid[]>] [-Confirm] [-WhatIf] [<CommonParame ters>] Remove-PSSession [-Name <string[]>] [-Confirm] [-WhatIf] [<CommonParameters >] Remove-PSSession [-Session] <PSSession[]> [-Confirm] [-WhatIf] [<CommonPara meters>] DESCRIPTION The Remove-PSSession cmdlet closes Windows PowerShell sessions (PSSessions) in the current session. It stops any commands that are running in the PSSe ssions, ends the PSSession, and releases the resources that the PSSession w as using. If the PSSession is connected to a remote computer, Remove-PSSess ion also closes the connection between the local and remote computers. To remove a PSSession, enter the Name, ComputerName, ID, or InstanceID of t he session. If you have saved the PSSession in a variable, the session object remains i n the variable, but the state of the PSSession is "Closed." PARAMETERS -ComputerName <string[]> Closes the PSSessions that are connected to the specified computers. Wi ldcards are permitted. Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more remote computers. To specify the local computer, type th e computer name, "localhost", or a dot (.). Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Id <Int32[]> Closes the PSSessions with the specified IDs. Type one or more IDs (sep arated by commas) or use the range operator (..) to specify a range of IDs An ID is an integer that uniquely identifies the PSSession in the curre nt session. It is easier to remember and type than the InstanceId, but it is unique only within the current session. To find the ID of a PSSe ssion, use Get-PSSession without parameters. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InstanceId <Guid[]> Closes the PSSessions with the specified instance IDs. The instance ID is a GUID that uniquely identifies a PSSession in the c urrent session. The InstanceID is unique, even when you have multiple s essions running on a single computer. The InstanceID is stored in the InstanceID property of the object that represents a PSSession. To find the InstanceID of the PSSessions in the current session, type "get-pssession | format-table Name, ComputerName , InstanceId". Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string[]> Closes the PSSessions with the specified friendly names. Wildcards are permitted. Because the friendly name of a PSSession might not be unique, when usin g the Name parameter, consider also using the WhatIf or Confirm parame ter in the Remove-PSSession command. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Session <PSSession[]> Specifies the session objects of the PSSessions to close. Enter a vari able that contains the PSSessions or a command that creates or gets the PSSessions, such as a New-PSSession or Get-PSSession command. You can also pipe one or more session objects to Remove-PSSession. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.Runspaces.PSSession You can pipe a session object to Remove-PSSession. OUTPUTS None Remove-PSSession does not return any objects. NOTES The ID parameter is mandatory. You cannot type "remove-pssession" witho ut parameters. To delete all the PSSessions in the current session, typ e "get-pssession | remove-pssession". A PSSession uses a persistent connection to a remote computer. Create a PSSession to run a series of commands that share data. For more inform ation, see about_PSSessions. PSSessions are specific to the current session. When you end a session, the PSSessions that you created in that session are forcibly closed. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-pssession -id 1, 2 Description ----------- This command removes the PSSessions that have IDs 1 and 2. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-pssession | remove-pssession C:\PS> remove-pssession -session (get-pssession) C:\PS> $s = get-pssession C:\PS> remove-pssession -session $s". Description ----------- These commands remove all of the PSSessions in the current session. Althoug h the three command formats look different, they have the same effect. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$r = get-pssession -computername Serv* $r | remove-pssession Description ----------- These commands close the PSSessions that are connected to computers that ha ve names that begin with "Serv". -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-pssession | where {$_.port -eq 90} | remove-pssession Description ----------- This command closes the PSSessions that are connected to port 90. You can u se this command format to identify PSSessions by properties other than Comp uterName, Name, InstanceID, and ID. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-pssession | ft computername, instanceID -auto ComputerName InstanceId ------------ ---------------- Server01 875d231b-2788-4f36-9f67-2e50d63bb82a localhost c065ffa0-02c4-406e-84a3-dacb0d677868 Server02 4699cdbc-61d5-4e0d-b916-84f82ebede1f Server03 4e5a3245-4c63-43e4-88d0-a7798bfc2414 TX-TEST-01 fc4e9dfa-f246-452d-9fa3-1adbdd64ae85 C:\PS> remove-pssession -InstanceID fc4e9dfa-f246-452d-9fa3-1adbdd64ae85 Description ----------- These commands show how to close a PSSession based on its instance ID (Remo teRunspaceID). The first command uses the Get-PSsession cmdlet to get the PSSessions in th e current session. It uses a pipeline operator (|) to send the PSSessions t o the Format-Table cmdlet (alias: ft), which formats their ComputerName and InstanceID properties in a table. The AutoSize parameter ("auto") compress es the columns for display. From the resulting display, the administrator can identify the PSSession to be closed, and copy and paste the InstanceID of that PSSession into the se cond command. The second command uses the Remove-PSSession cmdlet to remove the PSSession with the specified instance ID. -------------------------- EXAMPLE 6 -------------------------- C:\PS>function EndPSS { get-pssession | remove-pssession } Description ----------- This function deletes all of the PSSessions in the current session. After y ou add this function to your Windows Powershell profile, to delete all sess ions, just type "endpss". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135250 about_PSSessions about_Remote New-PSSession Get-PSSession Enter-PSSession Exit-PSSession Invoke-Command Remove-PSSnapin NAME Remove-PSSnapin SYNOPSIS Removes Windows PowerShell snap-ins from the current session. SYNTAX Remove-PSSnapin [-Name] <string[]> [-PassThru] [-Confirm] [-WhatIf] [<Commo nParameters>] DESCRIPTION The Remove-PSSnapin cmdlet removes a Windows PowerShell snap-in from the cu rrent session. You can use it to remove snap-ins that you have added to Win dows PowerShell, but you cannot use it to remove the snap-ins that are inst alled with Windows PowerShell. After a snap-in is removed from the current session, it is still loaded, bu t the cmdlets and providers in the snap-in are no longer available in the s ession. PARAMETERS -Name <string[]> Specifies the names of Windows PowerShell snap-ins to remove from the c urrent session. The parameter name ("Name") is optional, and wildcard c haracters (*) are permitted in the value. Required? true Position? 1 Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -PassThru [<SwitchParameter>] Returns an object representing the snap-in. By default, this cmdlet doe s not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSSnapInInfo You can pipe a snap-in object to Remove-PSSnapin. OUTPUTS None or System.Management.Automation.PSSnapInInfo By default, Remove-PsSnapin does not generate any output. However, if y ou use the PassThru parameter, it generates a System.Management.Automat ion.PSSnapInInfo object representing the snap-in. NOTES You can also refer to Remove-PSSnapin by its built-in alias, "rsnp". Fo r more information, see about_Aliases. Remove-PSSnapin does not check the version of Windows PowerShell before removing a snap-in from the session. If a snap-in cannot be removed, a warning appears and the command fails. Remove-PSSnapin affects only the current session. If you have added an Add-PSSnapin command to your Windows PowerShell profile, you should del ete the command to remove the snap-in from future sessions. For instruc tions, see about_Profiles. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-pssnapin -name Microsoft.Exchange Description ----------- This command removes the Microsoft.Exchange snap-in from the current sessio n. When the command is complete, the cmdlets and providers that the snap-in supported are not available in the session. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-PSSnapIn smp* | remove-PSSnapIn Description ----------- This command removes the Windows PowerShell snap-ins that have names beginn ing with "smp" from the current session. The command uses the Get-PSSnapin cmdlet to get objects representing the sn ap-ins. The pipeline operator (|) sends the results to the Remove-PSSnapin cmdlet, which removes them from the session. The providers and cmdlets that this snap-in supports are no longer available in the session. When you pipe objects to Remove-PSSnapin, the names of the objects are asso ciated with the Name parameter, which accepts objects from the pipeline tha t have a Name property. -------------------------- EXAMPLE 3 -------------------------- C:\PS>remove-pssnapin -name *event* Description ----------- This command removes all Windows PowerShell snap-ins that have names that i nclude "event". This command specifies the "Name" parameter name, but the p arameter name can be omitted because it is optional. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113378 Add-PSSnapin Get-PSSnapin about_Profiles Remove-Variable NAME Remove-Variable SYNOPSIS Deletes a variable and its value. SYNTAX Remove-Variable [-Name] <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Remove-Variable cmdlet deletes a variable and its value from the scope in which it is defined, such as the current session. You cannot use this cm dlet to delete variables that are set as constants or those that are owned by the system. PARAMETERS -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Na me parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to remove a variable even if it is read-only. Even us ing the Force parameter, the cmdlet cannot remove a constant. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Deletes only the specified items. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wil dcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the name of the variable to be removed. The parameter name (" Name") is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Scope <string> Specifies the scope in which this alias is valid. Valid values are "Glo bal", "Local", or "Script", or a number relative to the current scope ( 0 through the number of scopes, where 0 is the current scope and 1 is i ts parent). "Local" is the default. For more information, see about_Sco pes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSVariable You can pipe a variable object to Remove-Variable. OUTPUTS None This cmdlet does not return any output. NOTES Changes affect only the current scope, such as a session. To delete a v ariable from all sessions, add a Remove-Variable command to your Window s PowerShell profile. You can also refer to RemoveVariable by its built-in alias, "rv". For m ore information, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>remove-variable Smp Description ----------- This command deletes the $Smp variable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113380 Set-Variable Get-Variable Clear-Variable New-Variable about_Profiles Remove-WmiObject NAME Remove-WmiObject SYNOPSIS Deletes an instance of an existing Windows Management Instrumentation (WMI) class. SYNTAX Remove-WmiObject [-Class] <string> [-Authentication {Default | None | Conne ct | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Author ity <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-Ena bleAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Imperso nate | Delegate}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-Throt tleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] Remove-WmiObject [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Co mputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-ThrottleLimit <int>] [- Confirm] [-WhatIf] [<CommonParameters>] Remove-WmiObject -InputObject <ManagementObject> [-AsJob] [-ThrottleLimit int>] [-Confirm] [-WhatIf] [<CommonParameters>] Remove-WmiObject -Path <string> [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-Enable AllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonat e | Delegate}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-Throttle Limit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] Remove-WmiObject [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Co mputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-ThrottleLimit <int>] [- Confirm] [-WhatIf] [<CommonParameters>] Remove-WmiObject [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Co mputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-ThrottleLimit <int>] [- Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Remove-WmiObject cmdlet deletes an instance of an existing WMI class. PARAMETERS -AsJob [<SwitchParameter>] Runs the command as a background job. Use this parameter to run comman ds that take an extensive time to complete. Runs the command as a background job. Use this parameter to run command s that take a long time to finish. When you use the AsJob parameter, the command returns an object that re presents the background job and then displays the command prompt. You c an continue to work in the session while the job finishes. If Remove-Wm iObject is used against a remote computer, the job is created on the lo cal computer, and the results from remote computers are automatically r eturned to the local computer. To manage the job, use the cmdlets that contain the Job noun (the Job cmdlets). To get the job results, use the Receive-Job cmdlet. Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must star t Windows PowerShell by using the "Run as administrator" option in Wind ows Vista and later versions of Windows,. For more information, see abo ut_Remote_Requirements. For more information about Windows PowerShell background jobs, see abo ut_Jobs and about_Remote_Jobs. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationLevel> Specifies the authentication level to be used with the WMI connection. Valid values are: -1: Unchanged 0: Default 1: None (No authentication in performed.) 2: Connect (Authentication is performed only when the client establishe s a relationship with the application.) 3: Call (Authentication is performed only at the beginning of each call when the application receives the request.) 4: Packet (Authentication is performed on all the data that is received from the client.) 5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.) 6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.) Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authority <string> Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to "ntlmdomain:<DomainName>", where <DomainName> identifies a valid NTLM domain name. To use Kerberos, specify "kerberos :<DomainName>\<ServerName>". You cannot include the authority setting w hen you connect to the local computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Class <string> Specifies the name of a WMI class that you want to delete. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name. You can set the value of this parameter by piping the value to the parameter. This parameter does not rely on Windows PowerShell remoting, which uses WS-Management ). You can use the ComputerName parameter of Get-WmiObje ct even if your computer is not configured to run WS-Management remote commands. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or "User@Contoso.com". Or, enter a PSCredential object, such as an object that is returned by the Get-Credential cmdlet. When y ou type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -EnableAllPrivileges [<SwitchParameter>] Enables all the privileges of the current user before the command makes the WMI call. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Impersonation <ImpersonationLevel> Specifies the impersonation level to use. Valid values are: 0: Default (Reads the local registry for the default impersonation leve l, which is usually set to "3: Impersonate".) 1: Anonymous (Hides the credentials of the caller.) 2: Identify (Allows objects to query the credentials of the caller.) 3: Impersonate (Allows objects to use the credentials of the caller.) 4: Delegate (Allows objects to permit other objects to use the credenti als of the caller.) Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ManagementObject> Specifies a ManagementObject object to use as input. When this paramete r is used, all other parameters are ignored. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Locale <string> Specifies the preferred locale for WMI objects. The Locale parameter is specified as an array in the MS_<LCID> format in the preferred order. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Namespace <string> When used with the Class parameter, this parameter specifies the WMI re pository namespace where the referenced WMI class is located. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the WMI object path of a WMI class, or specifies the WMI obje ct path of an instance of a WMI class to delete. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Allows the user to specify a throttling value for the number of WMI ope rations that can be executed simultaneously. This parameter is used tog ether with the AsJob parameter. The throttle limit applies only to the current command, not to the session or to the computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.ManagementObject You can pipe a management object to Remove-WmiObject. OUTPUTS None or System.Management.Automation.RemotingJob When you use the AsJob parameter, this cmdlet returns a job object. Oth erwise, it does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>notepad C:\PS> $np = get-wmiobject -query "select * from win32_process where name=' notepad.exe'" C:\PS> $np | remove-wmiobject Description ----------- This command closes all the instances of Notepad.exe. The first command starts an instance of Notepad. The second command uses the Get-WmiObject cmdlet to retrieve the instances of the Win32_Process that correspond to Notepad.exe and stores them in the $np variable. The third command passes the object in the $np variable to the Remove-WmiOb ject cmdlet, which deletes all the instances of Notepad.exe. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$a = Get-WMIObject -query "Select * From Win32_Directory Where Name = 'C:\\Test'" C:\PS> $a | Remove-WMIObject Description ----------- This command deletes the C:\Test directory. The first command uses the Get-WMIObject cmdlet to query for the C:\Test di rectory and then stores the object in the $a variable. The second command pipes the $a variable to the Remove-WMIObject, which del etes the directory. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113381 Get-WmiObject Invoke-WmiMethod Set-WmiInstance Get-WSManInstance Invoke-WSManAction New-WSManInstance Remove-WSManInstance Remove-WSManInstance NAME Remove-WSManInstance SYNOPSIS Deletes a management resource instance. SYNTAX Remove-WSManInstance [-ApplicationName <string>] [-ComputerName <string>] [ -Port <int>] [-UseSSL] [[-SelectorSet] <hashtable>] [-AuthenticationMechani sm <AuthenticationMechanism>] [-Credential <PSCredential>] [-OptionSet <has htable>] [-ResourceURI <Uri>] [-SessionOption <hashtable>] [<CommonParamete rs>] Remove-WSManInstance [-ConnectionURI <Uri>] [[-SelectorSet] <hashtable>] [- AuthenticationMechanism <AuthenticationMechanism>] [-Credential <PSCredenti al>] [-OptionSet <hashtable>] [-ResourceURI <Uri>] [-SessionOption <hashtab le>] [<CommonParameters>] DESCRIPTION The Remove-WSManInstance deletes an instance of a management resource that is specified in the ResourceURI and SelectorSet parameters. This cmdlet uses the WinRM connection/transport layer to delete the managem ent resource instance. PARAMETERS -ApplicationName <string> Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for t he remote endpoint is in the following format: <transport>://<server>:<port>/ For example: http://server01:8080/WSMAN Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is desi gned to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hos ts Web Services for Management (WS-Management) for efficiency. Required? false Position? named Default value wsman Accept pipeline input? false Accept wildcard characters? false -AuthenticationMechanism <AuthenticationMechanism> Specifies the authentication mechanism to be used at the server. Possib le values are: - Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - Default : Use the authentication method implemented by the WS-Managem ent protocol. This is the default. - Digest: Digest is a challenge-response scheme that uses a server-spec ified data string for the challenge. - Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates. - Negotiate: Negotiate is a challenge-response scheme that negotiates w ith the server or proxy to determine the scheme to use for authenticati on. For example, this parameter value allows negotiation to determine w hether the Kerberos protocol or NTLM is used. - CredSSP: Use Credential Security Service Provider (CredSSP) authentic ation, which allows the user to delegate credentials. This option is de signed for commands that run on one remote computer but collect data fr om or run additional commands on other remote computers. Caution: CredSSP delegates the user's credentials from the local comput er to a remote computer. This practice increases the security risk of t he remote operation. If the remote computer is compromised, when creden tials are passed to it, the credentials can be used to control the netw ork session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name must be used. You can pipe a v alue for this parameter to the cmdlet. Required? false Position? named Default value localhost Accept pipeline input? false Accept wildcard characters? false -ConnectionURI <Uri> Specifies the connection endpoint. The format of this string is: <Transport>://<Server>:<Port>/ The following string is a properly formatted value for this parameter: http://Server01:8080/WSMAN The URI must be fully qualified. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or "User@Domain.com". Or, enter a PSCredential object, s uch as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -OptionSet <hashtable> Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be spec ified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: -OptionSet @{a=1;b=2;c=3} Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Port <int> Specifies the port to use when the client connects to the WinRM service . When the transport is HTTP, the default port is 80. When the transpor t is HTTPS, the default port is 443. When you use HTTPS as the transpor t, the value of the ComputerName parameter must match the server's cert ificate common name (CN). However, if the SkipCNCheck parameter is spec ified as part of the SessionOption parameter, then the certificate comm on name of the server does not have to match the host name of the serve r. The SkipCNCheck parameter should be used only for trusted computers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ResourceURI <Uri> Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, suc h as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Log icalDisk http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSenso r Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SelectorSet <hashtable> Specifies a set of value pairs that are used to select particular manag ement resource instances. The SelectorSet parameter is used when more t han one instance of the resource exists. The value of the SelectorSet p arameter must be a hash table. The following example shows how to enter a value for this parameter: -SelectorSet @{Name="WinRM";ID="yyy"} Required? false Position? 2 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -SessionOption <hashtable> Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOpt ion cmdlet. For more information about the options that are available, see New-WSManSessionOption. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Specifies that the Secure Sockets Layer (SSL) protocol should be used t o establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is trans mitted over the network. The UseSSL parameter lets you specify the addi tional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter , the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES The Remove-WmiObject cmdlet, a Windows Management Instrumentation (WMI) cmdlet, is similar. Remove-WmiObject uses the DCOM connection/transpor t layer to create or update WMI instances. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Remove-WSManInstance winrm/config/Listener -SelectorSet Address=test. fabrikam.com;Transport=http Description ----------- Deletes the WS-Management HTTP listener on a computer. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141453 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance New-WSManSessionOption Set-WSManInstance Set-WSManQuickConfig Test-WSMan Remove-WmiObject Rename-Item NAME Rename-Item SYNOPSIS Renames an item in a Windows PowerShell provider namespace. SYNTAX Rename-Item [-Path] <string> [-NewName] <string> [-Credential <PSCredential >] [-Force] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonPara meters>] DESCRIPTION The Rename-Item cmdlet changes the name of a specified item. This cmdlet do es not affect the content of the item being renamed. You cannot use Rename-Item to move an item, such as by specifying a path al ong with the new name. To move and rename an item, use the Move-Item cmdlet . PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to rename items that cannot otherwise be changed, suc h as hidden or read-only files or read-only aliases or variables. The c mdlet cannot change constant aliases or variables. Implementation varie s from provider to provider. For more information, see about_Providers. Even using the Force parameter, the cmdlet cannot override security re strictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -NewName <string> Specifies the new name of the item. Enter only a name, not a path and n ame. If you enter a path that is different from the path that is specif ied in the Path parameter, Rename-Item generates an error. To rename an d move an item, use the Move-Item cmdlet. You cannot use wildcard characters in the value of NewName. To specify a name for multiple files, use the Replace operator in a regular expres sion. For more information about the Replace operator, type "get-help a bout_comparison_operators". For a demonstration, see the examples. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Passes an object representing the item to the pipeline. By default, thi s cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the path to the item to rename. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Rename-Item. OUTPUTS None or an object representing the renamed item. When you use the Passthru parameter, Rename-Item generates an object re presenting the renamed item. Otherwise, this cmdlet does not generate a ny output. NOTES The Rename-Item cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-P sProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>rename-item -path c:\logfiles\daily_file.txt -newname monday_file.txt Description ----------- This command renames the file daily_file.txt to monday_file.txt. -------------------------- EXAMPLE 2 -------------------------- C:\PS>rename-item -path project.txt -newname d:\archive\old-project.txt Rename-Item : Cannot rename because the target specified represents a path or device name. At line:1 char:12 + rename-item < -path project.txt -newname d:\archive\old-project.txt + CategoryInfo : InvalidArgument: (:) [Rename-Item], PSArgumen tException + FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.Rename ItemCommand C:\PS> move-item -path project.txt -destination d:\archive\old-project.txt # Command succeeds Description ----------- This example shows that you cannot use the Rename-Item cmdlet to both renam e and move an item. Specifically, you cannot supply a path for the value of the NewName parameter, unless the path is identical to the path specified in the Path parameter. Otherwise, only a new name is permitted. The first command uses the Rename-Item cmdlet to rename the project.txt fil e in the current directory to old-project.txt in the D:\Archive directory. The result is the error shown in the output. The second command shows the correct way to move and rename a file by using the Move-Item cmdlet. The Move-Item cmdlet lets you specify both a new pat h and a new name in the value of its Destination parameter. -------------------------- EXAMPLE 3 -------------------------- C:\PS>rename-item HKLM:\Software\MyCompany\Advertising -NewName Marketing Description ----------- This command uses the Rename-Item cmdlet to rename a registry key from Adve rtising to Marketing. When the command is complete, the key is renamed, but the registry entries in the key are unchanged. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-childItem *.txt | rename-item -newname { $_.name -replace '\.txt' ,'.log' } Description ----------- This example shows how to use the Replace operator to rename multiple files , even though the NewName parameter does not accept wildcard characters. This command renames all of the .txt files in the current directory to .log . The command uses a Get-ChildItem cmdlet to get all of the files in the curr ent directory that have a .txt file name extension. Then, it uses the pipel ine operator (|) to send the resulting files to the Rename-Item cmdlet. In the Rename-Item command, the value of the NewName parameter is a script block that is executed before the value is submitted to the NewName paramet er. In the script block, the $_ automatic variable represents each file object as it comes to the command through the pipeline. The command uses the dot f ormat (.) to get the Name property of each file object. The Replace operato r replaces the ".txt" file name extension of each file with ".log". Because the Replace operator works with regular expressions, the dot preced ing "txt" is interpreted to match any character. To ensure that it matches only a dot (.), it is escaped with a backslash character (\). The backslash character is not required in ".log" because it is a string, not a regular expression. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113382 about_Providers Clear-Item Invoke-Item Move-Item Rename-ItemProperty Set-Item New-Item Remove-Item Get-Item Copy-Item Rename-ItemProperty NAME Rename-ItemProperty SYNOPSIS Renames a property of an item. SYNTAX Rename-ItemProperty [-LiteralPath] <string> [-Name] <string> [-NewName] <st ring> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTrans action] [<CommonParameters>] Rename-ItemProperty [-Path] <string> [-Name] <string> [-NewName] <string> [ -Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Forc e] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Rename-ItemProperty cmdlet changes the name of a specified item propert y. The value of the property is not changed. For example, you can use Renam e-ItemProperty to change the name of a registry entry. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to rename a property of an object that cannot otherwi se be accessed by the user. Implementation varies from provider to prov ider. For more information, see about_Providers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Specifies only those items upon which the cmdlet will act, excluding al l others. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string> Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation ma rks. Single quotation marks tell Windows PowerShell not to interpret an y characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies the current name of the property to be renamed. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -NewName <string> Specifies the new name for the property. Required? true Position? 3 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the item property. By default, this cmdl et does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies the path to the item to be renamed. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path (but not a literal path) to Rename-ItemProperty. OUTPUTS None or System.Management.Automation.PSCustomObject When you use the PassThru parameter, Rename-ItemProperty generates a PS CustomObject representing the renamed item property. Otherwise, this cm dlet does not generate any output. NOTES The Remove-ItemProperty cmdlet is designed to work with the data expose d by any provider. To list the providers available in your session, typ e "Get-PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>rename-itemproperty -path HKLM:\Software\SmpApplication -name config -newname oldconfig Description ----------- This command renames the config registry entry contained in the HKEY_LOCAL_ MACHINE\Software\SmpApplication key to oldconfig. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113383 about_Providers Rename-Item Clear-ItemProperty Copy-ItemProperty Get-ItemProperty Move-ItemProperty New-ItemProperty Remove-ItemProperty Set-ItemProperty Reset-ComputerMachinePassword NAME Reset-ComputerMachinePassword SYNOPSIS Resets the machine account password for the computer. SYNTAX Reset-ComputerMachinePassword [-Server <string>] [-Confirm] [-WhatIf] [<Com monParameters>] DESCRIPTION The Reset-ComputerMachinePassword cmdlet changes the machine account passwo rd that the computers use to authenticate to the domain controllers in the domain. You can use it to reset the password of the local computer. PARAMETERS -Server <string> Specifies the name of a domain controller to use when setting the machi ne account password. This parameter is optional. If you omit this parameter, a domain contro ller is chosen to service the command. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>Reset-ComputerMachinePassword Description ----------- This command resets the machine password for the local computer. The comman d runs with the credentials of the current user. -------------------------- EXAMPLE 2 -------------------------- C:\PS>Reset-ComputerMachinePassword -server DC01 Description ----------- This command resets the machine password of the local computer using the DC 01 domain controller. -------------------------- EXAMPLE 3 -------------------------- C:\PS>invoke-command -computername Server01 -scriptblock {reset-computermac hinepassword} Description ----------- This command uses the Invoke-Command cmdlet to run a Reset-ComputerMachineP assword command on the Server01 remote computer. For more information about remote commands in Windows PowerShell, see about _Remote and Invoke-Command. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135252 Resolve-Path NAME Resolve-Path SYNOPSIS Resolves the wildcard characters in a path, and displays the path contents. SYNTAX Resolve-Path [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Relat ive] [-UseTransaction] [<CommonParameters>] Resolve-Path [-Path] <string[]> [-Credential <PSCredential>] [-Relative] [- UseTransaction] [<CommonParameters>] DESCRIPTION The Resolve-Path cmdlet interprets the wildcard characters in a path and di splays the items and containers at the location specified by the path, such as the files and folders or registry keys and subkeys. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PS Credential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -LiteralPath <string[]> Specifies the path to be resolved. The value of LiteralPath is used exa ctly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any ch aracters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the Windows PowerShell path to resolve. This parameter is req uired. You can also pipe a path string to Resolve-Path. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Relative [<SwitchParameter>] Returns a relative path. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Resolve-Path. OUTPUTS System.String Resolve-Path returns a string that contains the resolved path. NOTES The cmdlets that contain the Path noun (the Path cmdlets) manipulate pa th names and return the names in a concise format that all Windows Powe rShell providers can interpret. They are designed for use in programs a nd scripts where you want to display all or part of a path name in a pa rticular format. Use them like you would use Dirname, Normpath, Realpat h, Join, or other path manipulators. You can use the Path cmdlets with several providers, including the File System, Registry, and Certificate providers. The Resolve-Path cmdlet is designed to work with the data exposed by an y provider. To list the providers available in your session, type "Get- PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>resolve-path ~ C:\Users\User01 Description ----------- This command resolves the path represented by the tilde character (~), whic h signifies the home path. -------------------------- EXAMPLE 2 -------------------------- C:\PS>resolve-path windows C:\Windows Description ----------- When run from the root of the C: drive, this command returns the path to th e Windows directory in the C: drive. -------------------------- EXAMPLE 3 -------------------------- C:\PS>"C:\windows\*" | resolve-path Description ----------- This command returns all of the directories in the C:\Windows directory. Th e command uses a pipeline operator (|) to send a path string to Resolve-Pat h. -------------------------- EXAMPLE 4 -------------------------- C:\PS>resolve-path \\Server01\public Description ----------- This command resolves a Universal Naming Convention (UNC) path and returns the shares in the path. -------------------------- EXAMPLE 5 -------------------------- C:\PS>resolve-path c:\prog* -relative ..\Program Files ..\Program Files (x86) ..\programs.txt Description ----------- This command returns relative paths for the directories at the root of the C: drive. -------------------------- EXAMPLE 6 -------------------------- C:\PS>resolve-path -literalPath test[xml] Description ----------- This command resolves the path to the Test[xml] subdirectory of the current directory. It uses the LiteralPath parameter to indicate that the brackets are not regular expression characters. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113384 about_Providers Test-Path Split-Path Convert-Path Join-Path Restart-Computer NAME Restart-Computer SYNOPSIS Restarts ("reboots") the operating system on local and remote computers. SYNTAX Restart-Computer [[-ComputerName] <string[]>] [[-Credential] <PSCredential> ] [-AsJob] [-Authentication {Default | None | Connect | Call | Packet | Pac ketIntegrity | PacketPrivacy | Unchanged}] [-Force] [-Impersonation {Defaul t | Anonymous | Identify | Impersonate | Delegate}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Restart-Computer cmdlet restarts the operating system on the local and remote computers. You can use the parameters of Restart-Computer to run the restart operation s as a background job, to specify the authentication levels and alternate c redentials, to limit the operations that run concurrently, and to force an immediate restart. This cmdlet does not require Windows PowerShell remoting unless you use the AsJob parameter. PARAMETERS -AsJob [<SwitchParameter>] Runs the command as a background job. Note: To use this parameter, the local and remote computers must be con figured for remoting and, on Windows Vista and later versions of Window s, you must open Windows PowerShell with the "Run as administrator" opt ion. For more information, see about_Remote_Requirements. When you use the AsJob parameter, the command immediately returns an ob ject that represents the background job. You can continue to work in th e session while the job completes. The job is created on the local comp uter and the results from remote computers are automatically returned t o the local computer. To manage the job, use the Job cmdlets. To get th e job results, use the Receive-Job cmdlet. For more information about Windows PowerShell background jobs, see abou t_Jobs and about_Remote_Jobs. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationLevel> Specifies the authentication level that is used for the WMI connection . (Restart-Computer uses WMI.) The default value is Packet. Valid values are: Unchanged: The authentication level is the same as the previous c ommand. Default: Windows Authentication None: No COM authentication Connect: Connect-level COM authentication Call: Call-level COM authentication Packet: Packet-level COM authentication. PacketIntegrity: Packet Integrity-level COM authentication PacketPrivacy: Packet Privacy-level COM authentication. Required? false Position? named Default value 4 Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Specifies one or more remote computers. The default is the local comput er. Type the NETBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter even if your computer is not configured to run remote commands. Required? false Position? 1 Default value . Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one from the Get-Credential cmdlet. Required? false Position? 2 Default value Current user Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Forces an immediate restart of the computers. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Impersonation <ImpersonationLevel> Specifies the impersonation level to use when calling WMI. (Restart-Com puter uses WMI.) The default value is "Impersonate". Valid values are: Default: Default impersonation. Anonymous: Hides the identity of the caller. Identify: Allows objects to query the credentials of the caller. Impersonate: Allows objects to use the credentials of the caller. Required? false Position? named Default value Impersonate Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Specifies the maximum number of concurrent connections that can be esta blished to run this command. If you omit this parameter or enter a valu e of 0, the default value, 32, is used. The throttle limit applies only to the current command, not to the sess ion or to the computer. Required? false Position? named Default value 32 Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None or System.Management.Automation.RemotingJob When you use the AsJob parameter, the cmdlet returns a job object. Othe rwise, it does not generate any output. NOTES This cmdlet uses the Win32Shutdown method of the WMI WIN32_OperatingSy stem class. -------------------------- EXAMPLE 1 -------------------------- C:\PS>restart-computer Description ----------- This command restarts the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>restart-computer -computername Server01, Server02, localhost Description ----------- This command restarts two remote computers, Server01 and Server02, and the local computer, identified as "localhost". -------------------------- EXAMPLE 3 -------------------------- C:\PS>$j = restart-computer -computername Server01, Server02 -asjob C:\PS> $results = $j | receive-job C:\PS> $results Description ----------- These commands run a Restart-Computer command as a background job on two re mote computers, and then get the results. The first command uses the AsJob parameter to run the command as a backgrou nd job. The command saves the resulting job object in the $j variable. The second command uses a pipeline operator to send the job object in $j to the Receive-Job cmdlet, which gets the job results. The command saves the results in the $results variable. The third command displays the result saved in the $results variable. Because the AsJob parameter creates the job on the local computer and autom atically returns the results to the local computer, you can run the Receive -Job command as a local command. -------------------------- EXAMPLE 4 -------------------------- C:\PS>restart-computer -comp Server01 -impersonation anonymous -authenticat ion PacketIntegrity Description ----------- This command restarts the Server01 remote computer. The command uses custom ized impersonation and authentication settings. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$s = get-content domain01.txt C:\PS> $c = get-credential domain01\admin01 C:\PS> restart-computer -computername $s -force -throttlelimit 10 -credenti al $c Description ----------- These commands force an immediate restart of all of the computers in Domain 01. The first command gets a list of computers in the domain and saves it in th e $s variable. The second command gets the credentials of a domain administrator and saves them in the $c variable. The third command restarts the computers. It uses the ComputerName paramete r to submit the list of computers in the $s variable, the Force parameter t o force an immediate restart, and the Credential parameter to submit the cr edentials saved in the $c variable. It also uses the ThrottleLimit paramete r to limit the command to 10 concurrent connections. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135253 Add-Computer Checkpoint-Computer Remove-Computer Restore-Computer Stop-Computer Test-Connection Restart-Service NAME Restart-Service SYNOPSIS Stops and then starts one or more services. SYNTAX Restart-Service [-Name] <string[]> [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Restart-Service -DisplayName <string[]> [-Exclude <string[]>] [-Force] [-In clude <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Restart-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonPar ameters>] DESCRIPTION The Restart-Service cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. If a service was a lready stopped, it is started without notifying you of an error. You can sp ecify the services by their service names or display names, or you can use the InputObject parameter to pass an object that represents each service th at you want to restart. PARAMETERS -DisplayName <string[]> Specifies the display names of services to be restarted. Wildcards are permitted. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Overrides restrictions that prevent the command from succeeding, just s o the changes do not compromise security. For example, Force will stop and restart a service that has dependent services. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Restarts only the specified services. The value of this parameter quali fies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ServiceController[]> Specifies ServiceController objects that represent the services to be r estarted. Enter a variable that contains the objects, or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the service names of the services to be restarted. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object that represents the service. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.ServiceProcess.ServiceController, System.String You can pipe a service object or a string that contains a service name to Restart-Service. OUTPUTS None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Restart-Service generates a System .ServiceProcess.ServiceController object that represents the restarted service. Otherwise, this cmdlet does not generate any output. NOTES Restart-Service can control services only when the current user has per mission to do so. If a command does not work correctly, you might not h ave the required permissions. To find the service names and display names of the services on your sys tem, type "get-service". The service names appears in the Name column, and the display names appear in the DisplayName column. -------------------------- EXAMPLE 1 -------------------------- C:\PS>restart-service wmi Description ----------- This command restarts the Windows Management Instrumentation (WMI) service on the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>restart-service -displayname net* -exclude "net logon" Description ----------- This command restarts the services that have a display name that begins wit h "Net", except for the "Net Logon" service. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-service net* | where-object {$_.Status -eq "Stopped"} | restart-s ervice Description ----------- This command starts all of the stopped network services on the computer. It uses the Get-Service cmdlet to get objects representing the services who se service name begins with "net". (The optional Name parameter name is omi tted.) The pipeline operator (|) sends the services object to the Where-Obj ect cmdlet, which selects only the services with a status of "stopped." Ano ther pipeline operator sends the selected services to Restart-Service. In p ractice, you would use the WhatIf parameter to see the effect of the comman d before using it. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113385 Start-Service Stop-Service Suspend-Service Resume-Service New-Service Get-Service Set-Service Restore-Computer NAME Restore-Computer SYNOPSIS Starts a system restore on the local computer. SYNTAX Restore-Computer [-RestorePoint] <int> [-Confirm] [-WhatIf] [<CommonParamet ers>] DESCRIPTION The Restore-Computer cmdlet restores the local computer to the specified sy stem restore point. A Restore-Computer command restarts the computer. The restore is completed during the restart operation. PARAMETERS -RestorePoint <int> Specifies the sequence number of the restore point. To find the sequen ce number, use Get-ComputerRestorePoint. This parameter is required. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not generate any output. NOTES To run a Restore-Computer command on Windows Vista and later versions o f Windows, open Windows PowerShell with the "Run as administrator" opti on. This cmdlet uses the Windows Management Instrumentation (WMI) SystemRes tore class. -------------------------- EXAMPLE 1 -------------------------- C:\PS>restore-computer -RestorePoint 253 Description ----------- This command restores the local computer to the restore point with sequence number 253. Because the RestorePoint parameter is positional, you can omit the paramete r name. -------------------------- EXAMPLE 2 -------------------------- C:\PS>restore-computer 255 -confirm Confirm Are you sure you want to perform this action? Performing operation "Restore-Computer" . [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (defa ult is "Y"): Description ----------- This command restores the local computer to the restore point with sequence number 255. It uses the Confirm parameter to prompt the user before actual ly performing the operation. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Get-ComputerRestorePoint C:\PS> Restore-Computer -RestorePoint 255 C:\PS> Get-ComputerRestorePoint -LastStatus Description ----------- These commands run a system restore and then check its status. The first command uses the Get-ComputerRestorePoint cmdlet to get the resto re points on the local computer. The second command uses Restore-Computer to restore the computer to the res tore point with sequence number 255. The third command uses the LastStatus parameter of Get-ComputerRestorePoint cmdlet to check the status of the restore operation. Because the Restore-C omputer command forces a restart, this command would be entered when the co mputer restarted. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135254 Get-ComputerRestorePoint Enable-ComputerRestore Disable-ComputerRestore Restart-Computer Resume-Service NAME Resume-Service SYNOPSIS Resumes one or more suspended (paused) services. SYNTAX Resume-Service [-Name] <string[]> [-Exclude <string[]>] [-Include <string[] >] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Resume-Service -DisplayName <string[]> [-Exclude <string[]>] [-Include <str ing[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Resume-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [ -Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Resume-Service cmdlet sends a resume message to the Windows Service Con troller for each of the specified services. If they have been suspended, th ey will resume service. If they are currently running, the message is ignor ed. You can specify the services by their service names or display names, o r you can use the InputObject parameter to pass a service object that repre sents the services that you want to resume. PARAMETERS -DisplayName <string[]> Specifies the display names of the services to be resumed. Wildcards ar e permitted. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Resumes only the specified services. The value of this parameter qualif ies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ServiceController[]> Specifies ServiceController objects representing the services to be res umed. Enter a variable that contains the objects, or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the service names of the services to be resumed. The parameter name is optional. You can use "-Name" or its alias, "-Ser viceName", or you can omit the parameter name. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the service. By default, this cmdlet doe s not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.ServiceProcess.ServiceController or System.String You can pipe a service object or a string that contains a service name to Resume-Service. OUTPUTS None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Resume-Service generates a System. ServiceProcess.ServiceController object representing the resumed servic e. Otherwise, this cmdlet does not generate any output. NOTES The status of services that have been suspended is "Paused". When servi ces are resumed, their status is "Running". Resume-Service can control services only when the current user has perm ission to do so. If a command does not work correctly, you might not ha ve the required permissions. To find the service names and display names of the services on your sys tem, type "get-service". The service names appear in the Name column, a nd the display names appear in the DisplayName column. -------------------------- EXAMPLE 1 -------------------------- C:\PS>resume-service sens Description ----------- This command resumes the System Event Notification service (the service nam e is represented in the command by "sens") on the local computer. The comma nd uses the Name parameter to specify the service name of the service, but the command omits the parameter name because the parameter name is optional . -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-service | where-object {$_.Status -eq "Paused"} | resume-service Description ----------- This command resumes all of the suspended (paused) services on the computer . The first command gets all of the services on the computer. The pipeline operator (|) passes the results to the Where-Object cmdlet, which selects t he services with a Status property of "Paused". The next pipeline operator sends the results to Resume-Service, which resumes the paused services. In practice, you would use the WhatIf parameter to determine the effect of the command before running it without WhatIf. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113386 Get-Service Start-Service Stop-Service Restart-Service Suspend-Service Set-Service New-Service Select-Object NAME Select-Object SYNOPSIS Selects specified properties of an object or set of objects. It can also se lect unique objects from an array of objects, or it can select a specified number of objects from the beginning or end of an array of objects. SYNTAX Select-Object [[-Property] <Object[]>] [-ExcludeProperty <string[]>] [-Expa ndProperty <string>] [-First <int>] [-InputObject <psobject>] [-Last [-Skip <int>] [-Unique] [<CommonParameters>] Select-Object [-Index <Int32[]>] [-InputObject <psobject>] [-Unique] [<Comm onParameters>] DESCRIPTION The Select-Object cmdlet gets only the specified properties of an object or set of objects. It can also select unique objects from an array of objects , or it can select a specified number of objects from the beginning or end of an array of objects. If you use Select-Object to select specified properties, it copies the valu es of those properties from the input objects and creates new objects that have the specified properties and copied values. Use the Property parameter to specify the properties you want to select. Or , use the First, Last, Unique, Skip, and Index parameters to select particu lar objects from an array of input objects. For more specific object filter ing, use the Where-Object cmdlet. PARAMETERS -ExcludeProperty <string[]> Removes the specifies properties from the selection. Wildcards are perm itted. This parameter is effective only when the command also includes the Property parameter. The value of the property parameter can be a calculated property, which is a hash table that specifies a name and calculates a value for the p roperty display. Valid keys are: -- Name or Label <string> -- Expression <string> or <scriptblock> For more information, see the examples. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -ExpandProperty <string> Specifies a property to select, and indicates that an attempt should be made to expand that property. Wildcards are permitted in the property name. For example, if the specified property is an array, each value of the a rray is included in the output. If the property contains an object, the properties of that object are displayed in the output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? true -First <int> Specifies the number of objects to select from the beginning of an arra y of input objects. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Index <Int32[]> Selects objects from an array based on their index values. Enter the in dexes in a comma-separated list. Indexes in an array begin with 0, where 0 represents the first value an d (n-1) represents the last value. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies objects to send to the cmdlet through the pipeline. This para meter enables you to pipe objects to Select-Object. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Last <int> Specifies the number of objects to select from the end of an array of i nput objects. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Property <Object[]> Specifies the properties to select. Wildcards are permitted. The value of the Property parameter can be a new calculated property. T o create a calculated, property, use a hash table. Valid keys are: -- Name (or Label) <string> -- Expression <string> or <script block> Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? true -Skip <int> Skips (does not select) the specified number of items. By default, the Skip parameter counts from the beginning of the array or list of object s, but if the command uses the Last parameter, it counts from the end o f the list or array. Unlike the Index parameter, which starts counting from 0, the Skip para meter begins at 1. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Unique [<SwitchParameter>] Specifies that if a subset of the input objects has identical propertie s and values, only a single member of the subset will be selected. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object to Select-Object. OUTPUTS System.Management.Automation.PSObject NOTES You can also refer to Select-Object by its built-in alias, "select". Fo r more information, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process | select-object ProcessName,Id,WS Description ----------- This command displays a list of processes. Only the name, ID, and working s et (WS) properties of the processes are displayed. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-process | select-object processname -expandproperty modules | format-list ProcessName : 00THotkey Size : 256 Company : TOSHIBA Corporation FileVersion : 1, 0, 0, 27 ProductVersion : 6, 2, 0, 0 Description : THotkey Product : TOSHIBA THotkey ModuleName : 00THotkey.exe FileName : C:\WINDOWS\system32\00THotkey.exe BaseAddress : 4194304 Description ----------- This command displays information about the modules used by the processes r unning on a computer. It uses the ExpandProperty parameter to display the d etails contained within the modules property. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-process | sort-object -property WS | select-object -Last 5 Handles NPM(K) PM(K) WS(K) VS(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 2866 320 33432 45764 203 222.41 1292 svchost 577 17 23676 50516 265 50.58 4388 WINWORD 826 11 75448 76712 188 19.77 3780 Ps 1367 14 73152 88736 216 61.69 676 Ps 1612 44 66080 92780 380 900.59 6132 INFOPATH Description ----------- This command displays the five processes that are using the most memory. Th e Sort-Object cmdlet is used to sort the processes according to memory (wor king set) usage, and the Select-Object cmdlet is used to select only the la st five members of the resulting array of objects. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-process | select-object -property ProcessName,@{Name="Start Day"; Expression = {$_.StartTime.DayOfWeek}} ProcessName StartDay ---- -------- alg Wednesday ati2evxx Wednesday ati2evxx Thursday ... Description ----------- This command displays the name and start day of the processes running on a computer. The values of the Property parameter are ProcessName and a calculated prope rty named "Start Day." The "Start Day" property is added by using a hash ta ble with Name and Expression keys. -------------------------- EXAMPLE 5 -------------------------- C:\PS>"a","b","c","a","a","a" | select-object -unique a b c Description ----------- This command displays unique characters from an array of characters. -------------------------- EXAMPLE 6 -------------------------- C:\PS>$a = get-eventlog -log "Windows PowerShell" C:\PS> $a | select-object -index 0, ($a.count - 1) Description ----------- These commands get the first (newest) and last (oldest) events in the Windo ws Powershell event log. The first command uses the Get-EventLog cmdlet to get all events in the Win dows Powershell log. It saves the events in the $a variable. The second command uses a pipeline operator (|) to send the events in $a to the Select-Object cmdlet. The Select-Object command uses the Index paramet er to select items by their index number. The index for the first event is 0. The index for the last event is the number of items in $a minus 1. -------------------------- EXAMPLE 7 -------------------------- C:\PS>new-pssession -computername (get-content servers.txt | select-object -skip 1) Description ----------- This command creates a new PSSession on each of the computers listed in the Servers.txt files, except for the first one. This command uses the Select-Object cmdlet to select all but the first comp uter in a list of computer names. The resulting list of computers is set as the value of the ComputerName parameter of the New-PSSession cmdlet. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113387 Where-Object Group-Object Sort-Object Select-String NAME Select-String SYNOPSIS Finds text in strings and files. SYNTAX Select-String [-Path] <string[]> [-Pattern] <string[]> [-AllMatches] [-Case Sensitive] [-Context <Int32[]>] [-Encoding <string>] [-Exclude <string[]>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<CommonP arameters>] Select-String -InputObject <psobject> [-Pattern] <string[]> [-AllMatches] [ -CaseSensitive] [-Context <Int32[]>] [-Encoding <string>] [-Exclude <string []>] [-Include <string[]>] [-List] [-NotMatch] [-Quiet] [-SimpleMatch] [<Co mmonParameters>] DESCRIPTION The Select-String cmdlet searches for text and text patterns in input strin gs and files. You can use it like Grep in UNIX and Findstr in Windows. Select-String is based on lines of text. By default, Select-String finds th e first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match. However, you can direct it to detect multiple matches per line, display tex t before and after the match, or display only a Boolean value (true or fals e) that indicates whether a match is found. Select-String uses regular expression matching, but it can also perform a s imple match that searches the input for the text that you specify. Select-String can display all of the text matches or stop after the first m atch in each input file. It can also display all text that does not match t he specified pattern. You can also specify that Select-String should expect a particular characte r encoding, such as when you are searching files of Unicode text. PARAMETERS -AllMatches [<SwitchParameter>] Searches for more than one match in each line of text. Without this par ameter, Select-String finds only the first match in each line of text. When Select-String finds more than one match in a line of text, it stil l emits only one MatchInfo object for the line, but the Matches propert y of the object contains all of the matches. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -CaseSensitive [<SwitchParameter>] Makes matches case-sensitive. By default, matches are not case-sensitiv e. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Context <Int32[]> Captures the specified number of lines before and after the line with t he match. This allows you to view the match in context. If you enter one number as the value of this parameter, that number det ermines the number of lines captured before and after the match. If you enter two numbers as the value, the first number determines the number of lines before the match and the second number determines the number of lines after the match. In the default display, lines with a match are indicated by a right ang le bracket (ASCII 62) in the first column of the display. Unmarked line s are the context. This parameter does not change the number of objects generated by Selec t-String. Select-String generates one MatchInfo (Microsoft.PowerShell.C ommands.MatchInfo) object for each match. The context is stored as an a rray of strings in the Context property of the object. When you pipe the output of a Select-String command to another Select-S tring command, the receiving command searches only the text in the matc hed line (the value of the Line property of the MatchInfo object), not the text in the context lines. As a result, the Context parameter is no t valid on the receiving Select-String command. When the context includes a match, the MatchInfo object for each match includes all of the context lines, but the overlapping lines appear onl y once in the display. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Encoding <string> Specifies the character encoding that Select-String should assume when searching the file. The default is UTF8. Valid values are "UTF7", "UTF8", "UTF32", "ASCII", "Unicode", "BigEndia nUnicode", "Default", and "OEM". "Default" is the encoding of the syste m's current ANSI code page. "OEM" is the current original equipment man ufacturer code page identifier for the operating system. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Exclude the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildc ards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Include only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the text to be searched. Enter a variable that contains the t ext, or type a command or expression that gets the text. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -List [<SwitchParameter>] Returns only the first match in each input file. By default, Select-Str ing returns a MatchInfo object for each match it finds. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -NotMatch [<SwitchParameter>] Finds text that does not match the specified pattern. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the files to be searched. Wildcards are permitted . The default location is the local directory. Specify files in the directory, such as "log1.txt", "*.doc", or "*.*". If you specify only a directory, the command fails. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Pattern <string[]> Specifies the text to find. Type a string or regular expression. If you type a string, use the SimpleMatch parameter. To learn about regular expressions, see about_Regular_Expressions. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Quiet [<SwitchParameter>] Returns a Boolean value (true or false), instead of a MatchInfo object. The value is "true" if the pattern is found; otherwise, the value is " false". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SimpleMatch [<SwitchParameter>] Uses a simple match rather than a regular expression match. In a simple match, Select-String searches the input for the text in the Pattern pa rameter. It does not interpret the value of the Pattern parameter as a regular expression statement. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe any object that has a ToString method to Select-String. OUTPUTS Microsoft.PowerShell.Commands.MatchInfo or System.Boolean By default, the output is a set of MatchInfo objects, one for each matc h found. If you use the Quiet parameter, the output is a Boolean value indicating whether the pattern was found. NOTES Select-String is like the Grep command in UNIX and the FindStr command in Windows. To use Select-String, type the text that you want to find as the value of the Pattern parameter. To specify the text to be searched, do the following: -- Type the text in a quoted string, and then pipe it to Select-String. -- Store a text string in a variable, and then specify the variable as the value of the InputObject parameter. -- If the text is stored in files, use the Path parameter to specify th e path to the files. By default, Select-String interprets the value of the Pattern parameter as a regular expression. (For more information, see about_Regular_Expr essions.) However, you can use the SimpleMatch parameter to override th e regular expression matching. The SimpleMatch parameter finds instance s of the value of the Pattern parameter in the input. The default output of Select-String is a MatchInfo object, which includ es detailed information about the matches. The information in the objec t is useful when you are searching for text in files, because MatchInfo objects have properties such as Filename and Line. When the input is n ot from the file, the value of these parameters is "InputStream". If you do not need the information in the MatchInfo object, use the Qui et parameter, which returns a Boolean value (true or false) to indicate whether it found a match, instead of a MatchInfo object. When matching phrases, Select-String uses the current that is set for t he system. To find the current culture, use the Get-Culture cmdlet. To find the properties of a MatchInfo object, type the following: select-string -path test.txt -pattern "test" | get-member | format-list -property * -------------------------- EXAMPLE 1 -------------------------- C:\PS>"Hello","HELLO" | select-string -pattern "HELLO" -casesensitive Description ----------- This command performs a case-sensitive match of the text that was piped to the Select-String command. As a result, Select-String finds only "HELLO", because "Hello" does not mat ch. Because each of the quoted strings is treated as a line, without the CaseSe nsitive parameter, Select-String would recognize both of the strings as mat ches. -------------------------- EXAMPLE 2 -------------------------- C:\PS>select-string -path *.xml -pattern "the the" Description ----------- This command searches through all files with the .xml file name extension i n the current directory and displays the lines in those files that include the string "the the". -------------------------- EXAMPLE 3 -------------------------- C:\PS>select-string -path $pshome\en-US\*.txt -pattern "@" Description ----------- This command searches the Windows PowerShell conceptual Help files (about_* .txt) for information about the use of the at sign (@). To indicate the path, this command uses the value of the $pshome automatic variable, which stores the path to the Windows PowerShell installation dire ctory. In this example, the command searches the en-US subdirectory, which contains the English (US) language Help files for Windows PowerShell. -------------------------- EXAMPLE 4 -------------------------- C:\PS>function search-help { $pshelp = "$pshome\es\about_*.txt", "$pshome\en-US\*dll-help.xml" select-string -path $pshelp -pattern $args[0] } Description ----------- This simple function uses the Select-String cmdlet to search the Windows Po werShell Help files for a particular string. In this example, the function searches the "en-US" subdirectory for English-United States language files. To use the function to find a string, such as "psdrive", type "search-help psdrive". To use this function in any Windows PowerShell console, change the path to point to the Windows PowerShell Help files on your system, and then paste t he function in your Windows PowerShell profile. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$events = get-eventlog -logname application -newest 100 C:\PS> $events | select-string -inputobject {$_.message} -pattern "failed" Description ----------- This example searches for the string "failed" in the 100 newest events in t he Application log in Event Viewer. The first command uses the Get-EventLog cmdlet to get the 100 most recent e vents from the Application event log. Then it stores the events in the $eve nts variable. The second command uses a pipeline operator (|) to send the objects in the $events variable to Select-String. It uses the InputObject parameter to rep resent the input from the $events variable. The value of the InputObject pa rameter is the Message property of each object as it travels through the pi peline. The current object is represented by the $_ symbol. As each event arrives in the pipeline, Select-String searches the value of its Message property for the "failed" string, and then displays any lines t hat include a match. -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-childitem c:\windows\system32\* -include *.txt -recurse | select-string -pattern "Microsoft" -casesensitive Description ----------- This command examines all files in the subdirectories of C:\Windows\System3 2 with the .txt file name extension and searches for the string "Microsoft" . The CaseSensitive parameter indicates that the "M" in "Microsoft" must be capitalized and that the rest of the characters must be lowercase for Sele ct-String to find a match. -------------------------- EXAMPLE 7 -------------------------- C:\PS>select-string -path process.txt -pattern idle, svchost -notmatch Description ----------- This command finds lines of text in the Process.txt file that do not includ e the words "idle" or "svchost". -------------------------- EXAMPLE 8 -------------------------- C:\PS>$f = select-string -path audit.log -pattern "logon failed" -context 2 , 3 C:\PS> $f.count C:\PS> ($f)[0].context | format-list Description ----------- The first command searches the Audit.Log file for the phrase "logon failed. " It uses the Context parameter to capture 2 lines before the match and 3 l ines after the match. The second command uses the Count property of object arrays to display the number of matches found, in this case, 2. The third command displays the lines stored in the Context property of the first MatchInfo object. It uses array notation to indicate the first match (match 0 in a zero-based array), and it uses the Format-List cmdlet to disp lay the value of the Context property as a list. The output consists of two MatchInfo objects, one for each match detected. The context lines are stored in the Context property of the MatchInfo objec t. -------------------------- EXAMPLE 9 -------------------------- C:\PS>$a = get-childitem $pshome\en-us\about*.help.txt | select-string -pat tern transcript C:\PS> $b = get-childitem $pshome\en-us\about*.help.txt | select-string -pa ttern transcript -allmatches C:\PS> $a C:\Windows\system32\WindowsPowerShell\v1.0\en-us\about_Pssnapins.help.txt:3 9: Start-Transcript and Stop-Transcript. C:\PS> $b C:\Windows\system32\WindowsPowerShell\v1.0\en-us\about_Pssnapins.help.txt:3 9: Start-Transcript and Stop-Transcript. C:\PS>> $a.matches Groups : {Transcript} Success : True Captures : {Transcript} Index : 13 Length : 10 Value : Transcript C:\PS> $b.matches Groups : {Transcript} Success : True Captures : {Transcript} Index : 13 Length : 10 Value : Transcript Groups : {Transcript} Success : True Captures : {Transcript} Index : 33 Length : 10 Value : Transcript Description ----------- This example demonstrates the effect of the AllMatches parameter of Select- String. AllMatches finds all pattern matches in a line, instead of just fin ding the first match in each line. The first command in the example searches the Windows PowerShell conceptual Help files ("about" Help) for instances of the word "transcript". The seco nd command is identical, except that it uses the AllMatches parameter. The output of the first command is saved in the $a variable. The output of the second command is saved in the $b variable. When you display the value of the variables, the default display is identic al, as shown in the example output. However, the fifth and sixth commands display the value of the Matches prop erty of each object. The Matches property of the first command contains jus t one match (that is, one System.Text.RegularExpressions.Match object), whe reas the Matches property of the second command contains objects for both o f the matches in the line. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113388 about_Comparison_Operators about_Regular_Expressions Select-XML NAME Select-XML SYNOPSIS Finds text in an XML string or document. SYNTAX Select-XML -Content <string[]> [-Xpath] <string> [-Namespace <hashtable>] [ <CommonParameters>] Select-XML [-Path] <string[]> [-Xpath] <string> [-Namespace <hashtable>] [ CommonParameters>] Select-XML [-Xml] <XmlNode[]> [-Xpath] <string> [-Namespace <hashtable>] [ CommonParameters>] DESCRIPTION The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. PARAMETERS -Content <string[]> Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. Required? true Position? named Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? false -Namespace <hashtable> Specifies a hash table of the namespaces used in the XML. Use the forma t @{<namespaceName> = <namespaceValue>}. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path and file names of the XML files to search. Wildcard s are permitted. Required? true Position? 2 Default value None Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -Xml <XmlNode[]> Specifies one or more XML nodes. A Path or XML parameter is required in every command. An XML document will be processed as a collection of XML nodes. If you pipe an XML document to Select-XML, each document node will be searched separately as it comes through the pipeline. Required? true Position? 2 Default value None Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Xpath <string> Specifies an XPath search query. The query language is case-sensitive. This parameter is required. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String or System.Xml.XmlNode You can pipe a path or XML node to Select-XML. OUTPUTS System.Xml.XmlElement or System.Xml.XmlText NOTES XPath is a standard language that is designed to identify parts of an X ML document. For more information about the XPath language, see the "Se lection Filters" section of the "Event Selection" topic in the MSDN (Mi crosoft Developer Network) library at http://go.microsoft.com/fwlink/?L inkId=143608. And, see "XPath Reference" in the MSDN library at http:// go.microsoft.com/fwlink/?LinkId=143609. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$path = "$env:windir\System32\WindowsPowerShell\v1.0\Types.ps1xml" C:\PS> select-xml -path $path -xpath "/Types/Type/Members/AliasProperty" Description ----------- This example searches the Types.ps1xml file for child items of the AliasPro perty node. -------------------------- EXAMPLE 2 -------------------------- C:\PS>select-xml -path test*.xml, help.xml -xpath "/Tests/Test[1]/Name" Description ----------- This command uses Select-XML to search in several XML files. -------------------------- EXAMPLE 3 -------------------------- C:\PS>[xml]$Types = get-content "$env:windir\System32\WindowsPowerShell\v1. 0\Types.ps1xml" C:\PS> select-xml -xml $Types -xpath "//MethodName" Description ----------- This example shows how to pipe an XML document to Search-Path. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$namespace = @{command="http://schemas.microsoft.com/maml/dev/command /2004/10"; maml="http://schemas.microsoft.com/maml/2004/10"; dev="http://sc hemas.microsoft.com/maml/dev/2004/10"} C:\PS> $path = "$env:windir\System32\WindowsPowerShell\V1.0\en-us\*dll-Help .xml" C:\PS> select-xml -path $path -namespace $namespace -xpath "//command:name" Text Node Path ---- ---- ---- Add-Computer name C:\Windows\System32\WindowsPowerShell\V ... Add-Content name C:\Windows\System32\WindowsPowerShell\V ... Checkpoint-Computer name C:\Windows\System32\WindowsPowerShell\V ... Clear-Content name C:\Windows\System32\WindowsPowerShell\V ... Clear-EventLog name C:\Windows\System32\WindowsPowerShell\V ... ... Description ----------- This example shows how to use the Select-XML cmdlet to search the Windows P owerShell XML-based cmdlet help files. The first command creates a hash table that represents the XML namespace an d saves it in the $namespace variable. The second command saves the path to the help files in the $path variable. The third command uses Select-Xml to search the XML for cmdlet names by fin ding Command:Name tags anywhere in the files. -------------------------- EXAMPLE 5 -------------------------- C:\PS>select-xml -content $xml -xpath "//edition" C:\PS> $xml = @" <?xml version="1.0" encoding="utf-8"?> <Book> <projects> <project name="Book1" date="2009-01-20"> <editions> <edition language="English">En.Book1.com</edition> <edition language="German">Ge.Book1.Com</edition> <edition language="French">Fr.Book1.com</edition> <edition language="Polish">Pl.Book1.com</edition> </editions> </project> </projects> </Book> "@ C:\PS> select-xml -content $xml -xpath "//edition" Text Node Path ---- ---- ---- En.Book1.com edition InputStream Ge.Book1.Com edition InputStream Fr.Book1.com edition InputStream Pl.Book1.com edition InputStream C:\PS> $xml | select-xml -xpath "//edition" Text Node Path ---- ---- ---- En.Book1.com edition InputStream Ge.Book1.Com edition InputStream Fr.Book1.com edition InputStream Pl.Book1.com edition InputStream Description ----------- This example uses the Content parameter of Select-XML to search XML content in a here-string. The first command saves the here-string in the $xml variable. The second command uses the Content parameter to specify the XML in the $xm l variable. The third command is equivalent to the second. It uses a pipeline operator (|) to send the XML in the $xml variable to the Select-XML cmdlet. For more information about here-strings, type about_Quoting_Rules. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135255 ConvertTo-XML Send-MailMessage NAME Send-MailMessage SYNOPSIS Sends an e-mail message. SYNTAX Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Bod y] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>] [-Bcc ng[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-Delive ryNotificationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Enco ding <Encoding>] [-Priority {Normal | Low | High}] [-UseSsl] [<CommonParame ters>] DESCRIPTION The Send-MailMessage cmdlet sends an e-mail message from within Windows Pow erShell. PARAMETERS -Attachments <string[]> Specifies the path and file names of files to be attached to the e-mail message. You can use this parameter or pipe the paths and file names t o Send-MailMessage. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Bcc <string[]> Specifies the e-mail addresses that receive a copy of the mail but are not listed as recipients of the message. Enter names (optional) and the e-mail address, such as "Name <someone@example.com>". Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Body <string> Specifies the body (content) of the e-mail message. Required? false Position? 3 Default value None Accept pipeline input? false Accept wildcard characters? false -BodyAsHtml [<SwitchParameter>] Indicates that the value of the Body parameter contains HTML. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Cc <string[]> Specifies the e-mail addresses to which a carbon copy (CC) of the e-mai l message is sent. Enter names (optional) and the e-mail address, such as "Name <someone@example.com>". Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PS Credential object, such as one from the Get-Credential cmdlet. Required? false Position? named Default value Current user Accept pipeline input? false Accept wildcard characters? false -DeliveryNotificationOption <DeliveryNotificationOptions> Specifies the delivery notification options for the e-mail message. You can specify multiple values. "None" is the default value. The alias f or this parameter is "dno". The delivery notifications are sent in an e-mail message to the address specified in the value of the To parameter. Valid values are: -- None: No notification. -- OnSuccess: Notify if the delivery is successful. -- OnFailure: Notify if the delivery is unsuccessful. -- Delay: Notify if the delivery is delayed. -- Never: Never notify. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Encoding <Encoding> Specifies the encoding used for the body and subject. Valid values are ASCII, UTF8, UTF7, UTF32, Unicode, BigEndianUnicode, Default, and OEM. ASCII is the default. Required? false Position? named Default value ASCII Accept pipeline input? false Accept wildcard characters? false -From <string> Specifies the address from which the mail is sent. Enter a name (option al) and e-mail address, such as "Name <someone@example.com>". This para meter is required. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Priority <MailPriority> Specifies the priority of the e-mail message. The valid values for this are Normal, High, and Low. Normal is the default. Required? false Position? named Default value Normal. Accept pipeline input? false Accept wildcard characters? false -SmtpServer <string> Specifies the name of the SMTP server that sends the e-mail message. The default value is the value of the $PSEmailServer preference variabl e. If the preference variable is not set and this parameter is omitted, the command fails. Required? false Position? 4 Default value $PSEmailServer Accept pipeline input? false Accept wildcard characters? false -Subject <string> Specifies the subject of the e-mail message. This parameter is required . Required? true Position? 2 Default value None Accept pipeline input? false Accept wildcard characters? false -To <string[]> Specifies the addresses to which the mail is sent. Enter names (optiona l) and the e-mail address, such as "Name <someone@example.com>". This p arameter is required. Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -UseSsl [<SwitchParameter>] Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer to send mail. By default, SSL is not used. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe the path and file names of attachments to Send-MailMessage . OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>send-mailmessage -to "User01 <user01@example.com>" -from "User02 <use r02@example.com>" -subject "Test mail" Description ----------- This command sends an e-mail message from User01 to User02. The mail message has a subject, which is required, but it does not have a b ody, which is optional. Also, because the SmtpServer parameter is not speci fied, Send-MailMessage uses the value of the $PSEmailServer preference vari able for the SMTP server. -------------------------- EXAMPLE 2 -------------------------- C:\PS>send-mailmessage -from "User01 <user01@example.com>" -to "User02 <use r02@example.com>", "User03 <user03@example.com>" -subject "Sending the Atta chment" -body "Forgot to send the attachment. Sending now." -Attachment "da ta.csv" -priority High -dno onSuccess, onFailure -smtpServer smtp.fabrikam. com Description ----------- This command sends an e-mail message with an attachment from User01 to two other users. It specifies a priority value of "High" and requests a delivery notificatio n by e-mail when the e-mail messages are delivered or when they fail. -------------------------- EXAMPLE 3 -------------------------- C:\PS>send-mailmessage -to "User01 <user01@example.com>" -from "ITGroup <it dept@example.com>" -cc "User02 <user02@example.com>" -bcc ITMgr <itmgr@exam ple.com> -subject "Don't forget today's meeting" -credential domain01\admi n01 -useSSL Description ----------- This command sends an e-mail message from User01 to the ITGroup mailing lis t with a copy (CC) to User02 and a blind carbon copy (BCC) to the IT manage r (ITMgr). The command uses the credentials of a domain administrator and the UseSSL p arameter. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135256 Set-Acl NAME Set-Acl SYNOPSIS Changes the security descriptor of a specified resource, such as a file or a registry key. SYNTAX Set-Acl [-Path] <string[]> [-AclObject] <ObjectSecurity> [-Exclude <string[ ]>] [-Filter <string>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatI f] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Set-Acl cmdlet changes the security descriptor of a specified resource, such as a file or a registry key, to match the values in a security descri ptor that you supply. To use Set-Acl, use the Path parameter to identify the resource whose secur ity descriptor you want to change, and use the AclObject parameter to suppl y a security descriptor that has the values you want to apply. Set-Acl uses the value of the AclObject parameter as a model and changes the values in the resource's security descriptor to match the values in the AclObject par ameter. PARAMETERS -AclObject <ObjectSecurity> Specifies an ACL with the desired property values. Set-Acl changes the ACL of resource specified by the Path parameter to match the values in the specified security object. You can save the output of a Get-Acl command in a variable and then use the AclObject parameter to pass the variable, or type a Get-Acl comman d. Required? true Position? 2 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Changes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the security descriptor. By default, th is cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Identifies the resource whose security descriptor you want to change. E nter the path to a resource, such as a path to a file or registry key. Wildcards are permitted. If you pass a security object to Set-Acl (either by using the AclObject parameter or by passing an object from Get-Acl to Set-Acl), and you om it the Path parameter (name and value), Set-Acl uses the path that is i ncluded in the security object. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Security.AccessControl.ObjectSecurity You can pipe a security descriptor to Set-Acl. OUTPUTS None or security object By default, Set-Acl does not generate any output. However, if you use t he -Passthru parameter, it generates a security object. The type of the security object depends on the type of the resource. NOTES The Set-Acl cmdlet is supported by the Windows PowerShell file system a nd registry providers. As such, you can use it to change the security d escriptors of files, directories, and registry keys. When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>". -------------------------- EXAMPLE 1 -------------------------- C:\PS>$DogACL = get-acl c:\dog.txt C:\PS>set-acl -path C:\cat.txt -AclObject $DogACL Description ----------- These commands copy the values from the security descriptor of the Dog.txt file to the security descriptor of the Cat.txt file. When the commands comp lete, the security descriptors of the Dog.txt and Cat.txt files are identic al. The first command uses the Get-Acl cmdlet to get the security descriptor of the Dog.txt file. The assignment operator (=) stores the security descript or in the value of the $DogACL variable. The second command uses Set-Acl to change the values in the ACL of Cat.txt to the values in $DogACL. The value of the Path parameter is the path to the Cat.txt file. The value of the AclObject parameter is the model ACL, in this case, the ACL of Dog.t xt as saved in the $DogACL variable. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-acl c:\dog.txt | set-acl -path C:\cat.txt Description ----------- This command is almost the same as the command in the previous example, exc ept that it uses a pipeline operator to send the security descriptor retrie ved in a Get-Acl command to a Set-Acl command. The first command uses the Get-Acl cmdlet to get the security descriptor of the Dog.txt file. The pipeline operator (|) passes an object that represen ts the Dog.txt security descriptor to the Set-Acl command. The second command uses Set-Acl to apply the security descriptor of Dog.tx t to Cat.txt. When the command completes, the ACLs of the Dog.txt and Cat.t xt files are identical. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$newACL = get-acl file0.txt C:\PS>get-childitem c:\temp -recurse -include *.txt -force | set-acl -aclob ject $newacl Description ----------- These commands apply the security descriptors in the File0.txt file to all text files in the C:\Temp directory and all of its subdirectories. The first command gets the security descriptor of the File0.txt file in the current directory and uses the assignment operator (=) to store it in the $newACL variable. The first command in the pipeline uses the Get-ChildItem cmdlet to get all of the text files in the C:\Temp directory. The Recurse parameter extends t he command to all subdirectories of C:\temp. The Include parameter limits t he files retrieved to those with the ".txt" file name extension. The Force parameter gets hidden files, which would otherwise be excluded. (You cannot use "c:\temp\*.txt", because the Recurse parameter works on directories, n ot on files.) The pipeline operator (|) sends the objects representing the retrieved file s to Set-Acl command, which applies the security descriptor in the AclObjec t parameter to all of the files in the pipeline. In practice, it is best to use the Whatif parameter with all Set-Acl comman ds that can affect more than one resource. In this case, the second command in the pipeline would be "set-acl -aclobject $newacl -whatif". This comman d lists the files that would be affected by the command. After reviewing th e result, you can run the command again without the Whatif parameter. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113389 Get-Acl Set-Alias NAME Set-Alias SYNOPSIS Creates or changes an alias (alternate name) for a cmdlet or other command element in the current Windows PowerShell session. SYNTAX Set-Alias [-Name] <string> [-Value] <string> [-Description <string>] [-Forc e] [-Option {None | ReadOnly | Constant | Private | AllScope}] [-PassThru] [-Scope <string>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Set-Alias cmdlet creates or changes an alias (alternate name) for a cmd let or for a command element, such as a function, a script, a file, or othe r executable. You can also use Set-Alias to reassign a current alias to a n ew command, or to change any of the properties of an alias, such as its des cription. Unless you add the alias to the Windows PowerShell profile, the c hanges to an alias are lost when you exit the session or close Windows Powe rShell. PARAMETERS -Description <string> Specifies a description of the alias. You can type any string. If the d escription includes spaces, enclose it quotation marks. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to set a read-only alias. Use the Option parameter to create a read-only alias. The Force parameter cannot set a constant al ias. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies the new alias. You can use any alphanumeric characters in an alias, but the first character cannot be a number. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Option <ScopedItemOptions> Sets the value of the Options property of the alias. Valid values are: -- None: Sets no options. (default) -- ReadOnly: The properties of the alias cannot be changed, except by u sing the Force parameter. You can use Remove-Item to delete the alias. -- Constant: The alias cannot be deleted and its properties cannot be c hanged. Constant is available only when you are creating an alias. You cannot change the option of an existing alias to Constant. -- Private: The alias is available only within the scope specified by t he Scope parameter. It is invisible in all other scopes. -- AllScope: The alias is copied to any new scopes that are created. To see the Options property of the aliases, type "get-alias | format-ta ble -property Name, Definition, Options -autosize". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the alias. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Scope <string> Specifies the scope in which this alias is valid. Valid values are "Glo bal", "Local", or "Script", or a number relative to the current scope ( 0 through the number of scopes, where 0 is the current scope and 1 is i ts parent). "Local" is the default. For more information, see about_Sco pes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Value <string> Specifies the name of the cmdlet or command element that is being alias ed. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None or System.Management.Automation.AliasInfo When you use the PassThru parameter, Set-Alias generates a System.Manag ement.Automation.AliasInfo object representing the alias. Otherwise, th is cmdlet does not generate any output. NOTES An alias is an alternate name or nickname for a cmdlet or command eleme nt. To run the cmdlet, you can use its full name or any valid alias. Fo r more information, see about_Aliases. To create a new alias, use Set-Alias or New-Alias. To delete an alias, use Remove-Item. A cmdlet can have multiple aliases, but an alias can only be associated with one cmdlet at a time. If you use set-alias to associate the alias with a different cmdlet, it is no longer associated with the original cmdlet. You can create an alias for a cmdlet, but you cannot create an alias fo r a command with parameters and values. For example, you can create an alias for Set-Location, but you cannot create an alias for "Set-Locatio n C:\Windows\System32". To create an alias for a command, create a func tion that includes the command, and then create an alias to the functio n. To save the aliases from a session and use them in a different session, add the set-alias command to your Windows PowerShell profile. Profiles do not exist by default. To create a profile in the path stored in the $profile variable, type "new-item -type file -force $profile". To see the value of the $profile variable, type "$profile". You can also save your aliases by using Export-Alias to copy the aliase s from the session to a file, and then use Import-Alias to add them to the alias list for a new session. You can also refer to Set-Alias by its built-in alias, "sal". For more information, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-alias -name list -value get-childitem Description ----------- This command creates the alias "list" for the Get-ChildItem cmdlet. After y ou create the alias, you can use "list" in place of "Get-ChildItem" at the command line and in scripts. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-alias list get-location Description ----------- This command associates the alias "list" with the Get-Location cmdlet. If " list" is an alias for another cmdlet, this command changes its association so that it now is the alias only for Get-Location. This command uses the same format as the command in the previous example, b ut it omits the optional parameter names, -Name and -Value. When you omit p arameter names, the values of those parameters must appear in the specified order in the command. In this case, the value of -Name ("list") must be th e first parameter and the value of -Value ("get-location") must be the seco nd parameter. -------------------------- EXAMPLE 3 -------------------------- C:\PS>set-alias scrub remove-item -option readonly -passthru | format-list Description ----------- This command associates the alias "scrub" with the Remove-Item cmdlet. It u ses the "ReadOnly" option to prevent the alias from being deleted or assign ed to another cmdlet. The PassThru parameter directs Windows PowerShell to pass an object that re presents the new alias through the pipeline to the Format-List cmdlet. If t he PassThru parameter were omitted, there would be no output from this cmdl et to display (in a list or otherwise). -------------------------- EXAMPLE 4 -------------------------- C:\PS>Set-Alias np c:\windows\notepad.exe Description ----------- This command associates the alias, "np", with the executable file for Notep ad. After the command completes, to open Notepad from the Windows PowerShel l command line, just type "np". This example demonstrates that you can create aliases for executable files and elements other than cmdlets. To make the command more generic, you can use the "Windir" environment vari able (${env:windir}) to represent the C\Windows directory. The generic vers ion of the command is "set-alias np ${env:windir}\notepad.exe". -------------------------- EXAMPLE 5 -------------------------- C:\PS>function CD32 {set-location c:\windows\system32} C:\PS>set-alias go cd32 Description ----------- These commands show how to assign an alias to a command with parameters, or even to a pipeline of many commands. You can create an alias for a cmdlet, but you cannot create an alias for a command that consists of a cmdlet and its parameters. However, if you place the command in a function or a script, then you can create a useful functi on or script name and you can create one or more aliases for the function o r script. In this example, the user wants to create an alias for the command "set-loc ation c:\windows\system32", where "set-location" is a cmdlet and "C:\Window s\System32" is the value of the Path parameter. To do this, the first command creates a function called "CD32" that contain s the Set-Location command. The second command creates the alias "go" for the CD32 function. Then, to r un the Set-Location command, the user can type either "CD32" or "go". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113390 Get-Alias New-Alias Export-Alias Import-Alias Set-AuthenticodeSignature NAME Set-AuthenticodeSignature SYNOPSIS Adds an Authenticode signature to a Windows PowerShell script or other file . SYNTAX Set-AuthenticodeSignature [-FilePath] <string[]> [-Certificate] <X509Certif icate2> [-Force] [-HashAlgorithm <string>] [-IncludeChain <string>] [-Times tampServer <string>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Set-AuthenticodeSignature cmdlet adds an Authenticode signature to any file that supports Subject Interface Package (SIP). In a Windows PowerShell script file, the signature takes the form of a bloc k of text that indicates the end of the instructions that are executed in t he script. If there is a signature in the file when this cmdlet runs, that signature is removed. PARAMETERS -Certificate <X509Certificate2> Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate. To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not vali d or does not have code-signing authority, the command fails. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -FilePath <string[]> Specifies the path to a file that is being signed. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to append a signature to a read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -HashAlgorithm <string> Specifies the hashing algorithm that Windows uses to compute the digita l signature for the file. The default is SHA1, which is the Windows def ault hashing algorithm. Files that are signed with a different hashing algorithm might not be r ecognized on other systems. Required? false Position? named Default value SHA1 Accept pipeline input? false Accept wildcard characters? false -IncludeChain <string> Determines which certificates in the certificate trust chain are includ ed in the digital signature. "NotRoot" is the default. Valid values are: -- Signer: Includes only the signer's certificate. -- NotRoot: Includes all of the certificates in the certificate chain, except for the root authority. --All: Includes all the certificates in the certificate chain. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -TimestampServer <string> Uses the specified time stamp server to add a time stamp to the signatu re. Type the URL of the time stamp server as a string. The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the cert ificate expires because users and programs can verify that the certific ate was valid at the time of signing. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains the file path to Set-AuthenticodeSi gnature. OUTPUTS System.Management.Automation.Signature NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$cert=Get-ChildItem -Path cert:\CurrentUser\my -CodeSigningCert C:\PS>Set-AuthenticodeSignature -FilePath PsTestInternet2.ps1 -certificate $cert Description ----------- These commands retrieve a code-signing certificate from the Windows PowerSh ell certificate provider and use it to sign a Windows PowerShell script. The first command uses the Get-ChildItem cmdlet and the Windows PowerShell certificate provider to get the certificates in the Cert:\CurrentUser\My su bdirectory of the certificate store. (The Cert: drive is the drive exposed by the certificate provider.) The CodeSigningCert parameter, which is suppo rted only by the certificate provider, limits the certificates retrieved to those with code-signing authority. The command stores the result in the $c ert variable. The second command uses the Set-AuthenticodeSignature cmdlet to sign the PS TestInternet2.ps1 script. It uses the FilePath parameter to specify the nam e of the script and the Certificate parameter to specify that the certifica te is stored in the $cert variable. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$cert = Get-PfxCertificate C:\Test\Mysign.pfx C:\PS>Set-AuthenticodeSignature -Filepath ServerProps.ps1 -Cert $cert Description ----------- These commands use the Get-PfxCertificate cmdlet to find a code signing cer tificate. Then, they use it to sign a Windows PowerShell script. The first command uses the Get-PfxCertificate cmdlet to find the C:\Test\My Sign.pfx certificate and store it in the $cert variable. The second command uses Set-AuthenticodeSignature to sign the script. The F ilePath parameter of Set-AuthenticodeSignature specifies the path to the sc ript file being signed and the Cert parameter passes the $cert variable con taining the certificate to Set-AuthenticodeSignature. If the certificate file is password protected, Windows PowerShell prompts y ou for the password. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Set-AuthenticodeSignature -filepath c:\scripts\Remodel.ps1 -certifica te $cert -IncludeChain All -TimeStampServer "http://timestamp.fabrikam.com/ scripts/timstamper.dll" Description ----------- This command adds a digital signature that includes the root authority in t he trust chain, and it is signed by a third-party timestamp server. The command uses the FilePath parameter to specify the script being signed and the Certificate parameter to specify the certificate that is saved in t he $cert variable. It uses the IncludeChain parameter to include all of the signatures in the trust chain (including the root authority). It also uses the TimeStampServer parameter to add a timestamp to the signature. This pr events the script from failing when the certificate expires. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113391 about_Signing about_Execution_Policies Get-AuthenticodeSignature Get-PfxCertificate Get-ExecutionPolicy Set-ExecutionPolicy Set-Content NAME Set-Content SYNOPSIS Writes or replaces the content in an item with new content. SYNTAX Set-Content [-LiteralPath] <string[]> [-Value] <Object[]> [-Credential <PSC redential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <st ring[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParamet ers>] Set-Content [-Path] <string[]> [-Value] <Object[]> [-Credential <PSCredenti al>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]> ] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Set-Content cmdlet is a string-processing cmdlet that writes or replace s the content in the specified item, such as a file. Whereas the Add-Conten t cmdlet appends content to a file, Set-Content replaces the existing conte nt. You can type the content in the command or send content through the pip eline to Set-Content. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to set the contents of a file, even if the file is re ad-only. Implementation varies from provider to provider. For more info rmation, see about_Providers. Even using the Force parameter, the cmdle t cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Changes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies the path to the item that will receive the content. Unlike Pa th, the value of LiteralPath is used exactly as it is typed. No charact ers are interpreted as wildcards. If the path includes escape character s, enclose it in single quotation marks. Single quotation marks tell Wi ndows PowerShell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the content. By default, this cmdlet doe s not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the item that will receive the content. Wildcards are permitted. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Value <Object[]> Specifies the new content for the item. Required? true Position? 2 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe an object that contains the new value for the item to Set- Content. OUTPUTS None or System.String When you use the Passthru parameter, Set-Content generates a System.Str ing object representing the content. Otherwise, this cmdlet does not ge nerate any output. NOTES You can also refer to Set-Content by its built-in alias, "sc". For more information, see about_Aliases. Set-Content is designed for string processing. If you pipe non-string o bjects to Set-Content, it converts the object to a string before writin g it. To write objects to files, use Out-File. The Set-Content cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-P sProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-content -path C:\Test1\test*.txt -value "Hello, World" Description ----------- This command replaces the contents of all files in the Test1 directory that have names beginning with "test" with "Hello, World". This example shows h ow to specify content by typing it in the command. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-date | set-content C:\Test1\date.csv Description ----------- This command creates a comma-separated variable-length (csv) file that cont ains only the current date and time. It uses the Get-Date cmdlet to get the current system date and time. The pipeline operator passes the result to S et-Content, which creates the file and writes the content. If the Test1 directory does not exist, the command fails, but if the file d oes not exist, the command will create it. -------------------------- EXAMPLE 3 -------------------------- C:\PS>(get-content Notice.txt) | foreach-object {$_ -replace "Warning", "Ca ution"} | set-content Notice.txt Description ----------- This command replaces all instances of "Warning" with "Caution" in the Noti ce.txt file. It uses the Get-Content cmdlet to get the content of Notice.txt. The pipeli ne operator sends the results to the ForEach-Object cmdlet, which applies t he expression to each line of content in Get-Content. The expression uses t he "$_" symbol to refer to the current item and the Replace parameter to sp ecify the text to be replaced. Another pipeline operator sends the changed content to Set-Content which re places the text in Notice.txt with the new content. The parentheses around the Get-Content command ensure that the Get operatio n is complete before the Set operation begins. Without them, the command wi ll fail because the two functions will be trying to access the same file. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113392 about_Providers Add-Content Get-Content Clear-Content Set-Date NAME Set-Date SYNOPSIS Changes the system time on the computer to a time that you specify. SYNTAX Set-Date [-Adjust] <TimeSpan> [-DisplayHint {Date | Time | DateTime}] [-Con firm] [-WhatIf] [<CommonParameters>] Set-Date [-Date] <DateTime> [-DisplayHint {Date | Time | DateTime}] [-Confi rm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Set-Date cmdlet changes the system date and time on the computer to a d ate and time that you specify. You can specify a new date and/or time by ty ping a string or by passing a DateTime or TimeSpan object to Set-Date. To s pecify a new date or time, use the Date parameter. To specify a change inte rval, use the Adjust parameter. PARAMETERS -Adjust <TimeSpan> Adds or subtracts the specified value from the current date and time. Y ou can type an adjustment in standard date and time format for your loc ale or use the Adjust parameter to pass a TimeSpan object from New-Time Span to Set-Date. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Date <DateTime> Changes the date and time to the specified values. You can type a new d ate in the short date format and a time in the standard time format for your locale. Or, you can pass a Date-Time object from Get-Date. If you specify a date, but not a time, Set-Date changes the time to mid night on the specified date. If you specify only a time, it does not ch ange the date. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -DisplayHint <DisplayHintType> Determines which elements of the date and time are displayed. Valid values are: -- date: displays only the date -- time: displays only the time -- datetime: displays the date and time This parameter affects only the display. It does not affect the DateTim e object that Get-Date retrieves. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.DateTime You can pipe a date to Set-Date. OUTPUTS System.DateTime Set-Date returns an object that represents the date that it set. NOTES Use this cmdlet cautiously. Changing the date and time on the computer. The change might prevent the computer from receiving system-wide event s and updates that are triggered by a date or time. Use the -WhatIf and -Confirm parameters to avoid errors. You can use standard .NET methods with the DateTime and TimeSpan object s used with Set-Date, such as AddDays, AddMonths and FromFileTime. For more information, see "DateTime Methods" and "TimeSpan Methods." -------------------------- EXAMPLE 1 -------------------------- C:\PS>Set-Date -Date (Get-Date).AddDays(3) Description ----------- This command adds three days to the current system date. It does not affect the time. The command uses the Date parameter to specify the date. It uses the Get-Date cmdlet to get the current date and time and applies the AddDa ys .NET method for DateTime objects with a value of 3 (days). -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-date -adjust -0:10:0 -displayHint time Description ----------- This command sets the current system time back by 10 minutes. It uses the A djust parameter to specify an interval of change and the time change (minus ten minutes) in standard time format for the locale. The DisplayHint param eter tells Windows PowerShell to display only the time, but it does not aff ect the DateTime object that Set-Date returns. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$t = get-date C:\PS>set-date -date $t Description ----------- These commands change the system date and time on the computer to the date and time saved in the variable $t. The first command gets the date and stor es it in $t. The second command uses the Date parameter to pass the DateTim e object in $t to the Set-Date cmdlet. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$90mins = new-timespan -minutes 90 C:\PS>set-date -adjust $90mins Description ----------- These commands advance the system time on the local computer by 90 minutes. The first command uses the New-Timespan cmdlet to create a TimeSpan object with a 90-minute interval, and then it saves the TimeSpan object in the $9 0mins variable. The second command uses the Adjust parameter of Set-Date to adjust the date by the value of the TimeSpan object in the $90mins variabl e. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113393 Get-Date New-TimeSpan Set-ExecutionPolicy NAME Set-ExecutionPolicy SYNOPSIS Changes the user preference for the Windows PowerShell execution policy. SYNTAX Set-ExecutionPolicy [-ExecutionPolicy] {Unrestricted | RemoteSigned | AllSi gned | Restricted | Default | Bypass | Undefined} [[-Scope] {Process | Curr entUser | LocalMachine | UserPolicy | MachinePolicy}] [-Force] [-Confirm] [ -WhatIf] [<CommonParameters>] DESCRIPTION The Set-ExecutionPolicy changes the user preference for the Windows PowerSh ell execution policy. To run this command on Windows Vista, Windows Server 2008, and later versio ns of Windows, you must start Windows PowerShell with the "Run as administr ator" option, even if you are a member of the Administrators group on the c omputer. The execution policy is part of the security strategy of Windows PowerShell . It determines whether you can load configuration files (including your Wi ndows PowerShell profile) and run scripts, and it determines which scripts, if any, must be digitally signed before they will run. For more information, see about_Execution_Policies. PARAMETERS -ExecutionPolicy <ExecutionPolicy> Specifies a new execution policy for the shell. The parameter name ("Na me") is optional. Valid values are: -- Restricted: Does not load configuration files or run scripts. "Restr icted" is the default. -- AllSigned: Requires that all scripts and configuration files be sign ed by a trusted publisher, including scripts that you write on the loca l computer. -- RemoteSigned: Requires that all scripts and configuration files down loaded from the Internet be signed by a trusted publisher. -- Unrestricted: Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs. -- Bypass: Nothing is blocked and there are no warnings or prompts. -- Undefined: Removes the currently assigned execution policy from the current scope. This parameter will not remove an execution policy that is set in a Group Policy scope. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Force [<SwitchParameter>] Suppresses all prompts. By default, Set-ExecutionPolicy displays a warn ing whenever you change the execution policy. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Scope <ExecutionPolicyScope> Specifies the scope of the execution policy. The default is LocalMachin e. Valid values are: -- Process: The execution policy affects only the current Windows Power Shell process. -- CurrentUser: The execution policy affects only the current user. -- LocalMachine: The execution policy affects all users of the computer . To remove an execution policy from a particular scope, set the executio n policy for that scope to Undefined. Required? false Position? 2 Default value LocalMachine Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS Microsoft.PowerShell.ExecutionPolicy, System.String You can pipe an execution policy object or a string that contains the n ame of an execution policy to Set-ExecutionPolicy. OUTPUTS None This cmdlet does not return any output. NOTES When you use Set-ExecutionPolicy, the new user preference is written to the registry and remains unchanged until you change it. However, if the "Turn on Script Execution" Group Policy is enabled for the computer or user, the user preference is written to the registry, b ut it is not effective, and Windows PowerShell displays a message expla ining the conflict. You cannot use Set-ExecutionPolicy to override a Gr oup Policy, even if the user preference is more restrictive than the po licy. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-executionpolicy remotesigned Description ----------- This command sets the user preference for the shell execution policy to Rem oteSigned. -------------------------- EXAMPLE 2 -------------------------- C:\PS>Set-ExecutionPolicy Restricted Set-ExecutionPolicy : Windows PowerShell updated your local preference succ essfully, but the setting is overridden by the group policy applied to your system. Due to the override, your shell will retain its current effective execution policy of "AllSigned". Contact your group policy administrator fo r more information. At line:1 char:20 + set-executionpolicy < restricted Description ----------- This command attempts to set the execution policy for the shell to "Restric ted." The "Restricted" setting is written to the registry, but because it c onflicts with a Group Policy, it is not effective, even though it is more r estrictive than the policy. -------------------------- EXAMPLE 3 -------------------------- C:\PS>invoke-command -computername Server01 -scriptblock {get-executionpoli cy} | set-executionpolicy -force Description ----------- This command gets the execution policy from a remote computer and applies t hat execution policy to the local computer. The command uses the Invoke-Command cmdlet to send the command to the remot e computer. Because you can pipe an ExecutionPolicy (Microsoft.PowerShell.E xecutionPolicy) object to Set-ExecutionPolicy, the Set-ExecutionPolicy comm and does not need an ExecutionPolicy parameter. The command does have a Force parameter, which suppresses the user prompt. -------------------------- EXAMPLE 4 -------------------------- C:\PS>set-executionpolicy -scope CurrentUser -executionPolicy AllSigned -fo rce C:\PS> get-executionpolicy -list Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser AllSigned LocalMachine RemoteSigned C:\PS> get-executionpolicy AllSigned Description ----------- This example shows how to set an execution policy for a particular scope. The first command uses the Set-ExecutionPolicy cmdlet to set an execution p olicy of AllSigned for the current user. It uses the Force parameter to sup press the user prompts. The second command uses the List parameter of Get-ExecutionPolicy to get th e execution policies set in each scope. The results show that the execution policy that is set for the current user differs from the execution policy set for all users of the computer. The third command uses the Get-ExecutionPolicy cmdlet without parameters to get the effective execution policy for the current user on the local compu ter. The result confirms that the execution policy that is set for the curr ent user takes precedence over the one set for all users. -------------------------- EXAMPLE 5 -------------------------- C:\PS>set-executionpolicy -scope CurrentUser -executionPolicy Undefined Description ----------- This command uses an execution policy value of Undefined to effectively rem ove the execution policy that is set for the current user scope. As a resul t, the execution policy that is set in Group Policy or in the LocalMachine (all users) scope is effective. If you set the execution policy in all scopes to Undefined and the Group Po licy is not set, the default execution policy, Restricted, is effective for all users of the computer. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113394 Get-ExecutionPolicy Set-AuthenticodeSignature Get-AuthenticodeSignature about_Execution_Policies about_Signing Set-Item NAME Set-Item SYNOPSIS Changes the value of an item to the value specified in the command. SYNTAX Set-Item [-LiteralPath] <string[]> [[-Value] <Object>] [-Credential <PSCred ential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <strin g[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters >] Set-Item [-Path] <string[]> [[-Value] <Object>] [-Credential <PSCredential> ] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [ -PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Set-Item cmdlet changes the value of an item, such as a variable or reg istry key, to the value specified in the command. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to set items that cannot otherwise be changed, such a s read-only alias or variables. The cmdlet cannot change constant alias es or variables. Implementation varies from provider to provider. For m ore information, see about_Providers. Even using the Force parameter, t he cmdlet cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Changes only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the location of the new items. Unlike Path, the val ue of LiteralPath is used exactly as it is typed. No characters are int erpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows Power Shell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Passes an object representing the item to the pipeline. By default, thi s cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies a path to the location of the new items. Wildcards are permit ted. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Value <Object> Specifies a new value for the item. Required? false Position? 2 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe an object that represents the new value of the item to Set -Item. OUTPUTS None or an object representing the new or changed item. When you use the Passthru parameter, Set-Item generates an object repre senting the item. Otherwise, this cmdlet does not generate any output. NOTES You can also refer to Set-Item by its built-in alias, "si". For more in formation, see about_Aliases. The Set-Item cmdlet is not supported by the Windows PowerShell FileSyst em provider. To change the values of items in the file system, use Set- Content. In the Registry drives, HKLM: and HKCU:, Set-Item changes the data in t he (Default) value of a registry key. To create and change the names of registry keys, use New-Item and Rename-Item. To change the names and d ata in registry values, use New-ItemProperty, Set-ItemProperty, and Ren ame-ItemProperty. The Set-Item cmdlet is designed to work with the data exposed by any pr ovider. To list the providers available in your session, type "Get-PsPr ovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-item -path alias:np -value c:\windows\notepad.exe Description ----------- This command creates an alias of "np" for Notepad. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-item -path env:UserRole -value Administrator Description ----------- This command uses the Set-Item cmdlet to change the value of the "UserRole" environment variable to "Administrator". -------------------------- EXAMPLE 3 -------------------------- C:\PS>set-item -path function:prompt -value {'PS '+ $(Get-Date -format t) + " " + $(Get-Location) + '> '} Description ----------- This command uses the Set-Item cmdlet to change the "prompt" function so th at it displays the time before the path. -------------------------- EXAMPLE 4 -------------------------- C:\PS>set-item -path function:prompt -options "AllScope,ReadOnly" Description ----------- This command sets the AllScope and ReadOnly options for the "prompt" functi on. This command uses the Options dynamic parameter of the Set-Item cmdlet. The Options parameter is available in Set-Item only when you use it with t he Alias or Function provider. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113395 about_Providers Get-Item New-Item Remove-Item Clear-Item Invoke-Item Rename-Item Move-Item Copy-Item Set-ItemProperty NAME Set-ItemProperty SYNOPSIS Creates or changes the value of a property of an item. SYNTAX Set-ItemProperty [-LiteralPath] <string[]> -InputObject <psobject> [-Creden tial <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-In clude <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<Comm onParameters>] Set-ItemProperty [-Path] <string[]> -InputObject <psobject> [-Credential <P SCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [<CommonParam eters>] Set-ItemProperty [-LiteralPath] <string[]> [-Name] <string> [-Value] <Objec t> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [- Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransact ion] [<CommonParameters>] Set-ItemProperty [-Path] <string[]> [-Name] <string> [-Value] <Object> [-Cr edential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Force] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [-UseTransaction] [ CommonParameters>] DESCRIPTION The Set-ItemProperty cmdlet changes the value of the property of the specif ied item. You can use the cmdlet to establish or change the properties of i tems. For example, you can use Set-ItemProperty to set the value of the IsR eadOnly property of a file object to true. You also use Set-ItemProperty to create and change registry values and data . For example, you can add a new registry entry to a key and establish or c hange its value. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one generated by the Get-Credential cmdlet. I f you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Specifies those items upon which the cmdlet is not to act, and includes all others. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to set a property on items that cannot otherwise be a ccessed by the user. Implementation varies from provider to provider. F or more information, see about_Providers. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Specifies only those items upon which the cmdlet will act, excluding al l others. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the object that has the properties that you want to change. E nter a variable that contains the object or a command that gets the obj ect. Required? true Position? named Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to the item property. The value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation ma rks. Single quotation marks tell Windows PowerShell not to interpret an y characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Name <string> Specifies the name of the property. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the item property. By default, this cmdl et does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string[]> Specifies the path to the items with the property to be set. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Value <Object> Specifies the value of the property. Required? true Position? 3 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe objects to Set-ItemProperty. OUTPUTS None or System.Management.Automation.PSCustomObject When you use the PassThru parameter, Set-ItemProperty generates a PSCus tomObject object that represents the item that was changed and its new property value. Otherwise, this cmdlet does not generate any output. NOTES The Set-ItemProperty cmdlet is designed to work with the data exposed b y any provider. To list the providers available in your session, type " Get-PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-itemproperty -path c:\GroupFiles\final.doc -name IsReadOnly -valu e $true Description ----------- This command sets the value of the IsReadOnly property of the final.doc fil e to true. The command uses the Set-ItemProperty cmdlet to change the value of the pro perty of the final.doc file. It uses the Path parameter to specify the file . It uses the Name parameter to specify the name of the property and the Va lue parameter to specify the new value. The $true automatic variable represents a value of TRUE. For more informati on, see about_Automatic_Variables. The file is a System.IO.FileInfo object and IsReadOnly is just one of its p roperties. To see all of the properties and methods of a FileInfo object, p ipe the file to the Get-Member cmdlet. For example, "final.doc | get-member ". -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-itemproperty -path HKLM:\Software\MyCompany -name NoOfEmployees - value 823 C:\PS>get-itemproperty -path HKLM:\Software\MyCompany PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\soft ware\mycompany PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\soft ware PSChildName : mycompany PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry NoOfLocations : 2 NoOfEmployees : 823 C:\PS>set-itemproperty -path HKLM:\Software\MyCompany -name NoOfEmployees - value 824 C:\PS>get-itemproperty -path HKLM:\Software\MyCompany PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\soft ware\mycompany PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\soft ware PSChildName : mycompany PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry NoOfLocations : 2 NoOfEmployees : 824 Description ----------- This example shows how to use Set-ItemProperty to create a new registry ent ry and to assign a value to the entry. It creates the NoOfEmployees entry i n the MyCompany key in HKLM\Software key and sets its value to 823. Because registry entries are considered to be properties of the registry ke ys (which are items), you use Set-ItemProperty to create registry entries, and to establish and change their values. The first command uses the Set-ItemProperty cmdlet to create the registry e ntry. It uses the Path parameter to specify the path to the HKLM: drive and the Software\MyCompany key. It uses the Name parameter to specify the entr y name and the Value parameter to specify a value. The second command uses the Get-ItemProperty cmdlet to see the new registry entry. If you use the Get-Item or Get-ChildItem cmdlets, the entries do no t appear because they are properties of a key, not items or child items. The third command changes the value of the NoOfEmployees entry to 824. You can also use the New-ItemProperty cmdlet to create the registry entry a nd its value and then use Set-ItemProperty to change the value. For more information about the HKLM: drive, type "get-help get-psdrive". Fo r more information about using Windows PowerShell to manage the registry, t ype "get-help registry". -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-childitem weekly.txt | set-itemproperty -name IsReadOnly -value $ true Description ----------- These commands show how to use a pipeline operator (|) to send an item to S et-ItemProperty. The first part of the command uses the Get-ChildItem cmdlet to get an objec t that represents the Weekly.txt file. The command uses a pipeline operator to send the file object to Set-ItemProperty. The Set-ItemProperty command uses the Name and Value parameters to specify the property and its new valu e. This command is equivalent to using the InputObject parameter to specify th e object that Get-ChildItem gets. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113396 about_Providers Get-ItemProperty New-ItemProperty Clear-ItemProperty Remove-ItemProperty Rename-ItemProperty Move-ItemProperty Copy-ItemProperty Set-Location NAME Set-Location SYNOPSIS Sets the current working location to a specified location. SYNTAX Set-Location [-LiteralPath] <string> [-PassThru] [-UseTransaction] [<Common Parameters>] Set-Location [[-Path] <string>] [-PassThru] [-UseTransaction] [<CommonParam eters>] Set-Location [-StackName <string>] [-PassThru] [-UseTransaction] [<CommonPa rameters>] DESCRIPTION The Set-Location cmdlet sets the working location to a specified location. That location could be a directory, a sub-directory, a registry location, o r another location stack. PARAMETERS -LiteralPath <string> Specifies a path to the location. The value of the LiteralPath paramete r is used exactly as it is typed. No characters are interpreted as wild cards. If the path includes escape characters, enclose it in single quo tation marks. Single quotation marks tell Windows PowerShell not to int erpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Passes an object representing the location to the pipeline. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> This parameter is used to specify the path to a new working location. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -StackName <string> The name of the stack to which the location is being set. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path (but not a literal path) to Set-Location. OUTPUTS None or System.Management.Automation.PathInfo When you use the PassThru parameter, Set-Location generates a System.Ma nagement.Automation.PathInfo object that represents the location. Other wise, this cmdlet does not generate any output. NOTES The Set-Location cmdlet is designed to work with the data exposed by an y provider. To list the providers available in your session, type "Get- PSProvider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-location HKLM: Description ----------- This will set the current location to the one specified; in this case, it i s the HKLM provider. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-location env: -passthru Path ---- Env:\ Description ----------- This will set the current location to the one specified; in this case, it i s the environment variable provider. -------------------------- EXAMPLE 3 -------------------------- C:\PS>set-location C: Description ----------- This will set the current location to the one specified; in this case, it i s the C: drive in the file system provider. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113397 about_Providers Get-Location Pop-Location Push-Location Set-PSBreakpoint NAME Set-PSBreakpoint SYNOPSIS Sets a breakpoint on a line, command, or variable. SYNTAX Set-PSBreakpoint -Command <string[]> [[-Script] <string[]>] [-Action <scrip tblock>] [<CommonParameters>] Set-PSBreakpoint [-Script] <string[]> [-Line] <Int32[]> [[-Column] <int>] [ -Action <scriptblock>] [<CommonParameters>] Set-PSBreakpoint -Variable <string[]> [[-Script] <string[]>] [-Mode {Read | Write | ReadWrite}] [-Action <scriptblock>] [<CommonParameters>] DESCRIPTION The Set-PSBreakpoint cmdlet sets a breakpoint in a script or in any command run in the current session. You can use Set-PSBreakpoint to set a breakpo int before executing a script or running a command, or during debugging, wh en stopped at another breakpoint. Note: Set-PSBreakpoint cannot set a breakpoint on a remote computer. To deb ug a script on a remote computer, copy the script to the local computer and then debug it locally. Each Set-PSBreakpoint command creates one of the following three types of b reakpoints: -- Line breakpoint: Sets breakpoints at particular line and column coord inates. -- Command breakpoint: Sets breakpoints on commands and functions. -- Variable breakpoint: Sets breakpoints on variables. You can set a breakpoint on multiple lines, commands, or variables in a sin gle Set-PSBreakpoint command, but each Set-PSBreakpoint command sets only o ne type of breakpoint. At a breakpoint, Windows PowerShell temporarily stops executing and gives c ontrol to the debugger. The command prompt changes to "DBG>", and a set of debugger commands become available for use. However, you can use the Action parameter to specify an alternate response, such as conditions for the bre akpoint or instructions to perform additional tasks such as logging or diag nostics. The Set-PSBreakpoint cmdlet is one of several cmdlets designed for debuggin g Windows PowerShell scripts. For more information about the Windows PowerS hell debugger, see about_Debuggers. PARAMETERS -Action <scriptblock> Specifies commands that run at each breakpoint instead of breaking. Ent er a script block that contains the commands. You can use this paramete r to set conditional breakpoints or to perform other tasks, such as tes ting or logging. If this parameter is omitted, or no action is specified, execution stop s at the breakpoint, and the debugger starts. When the Action parameter is used, the Action script block runs at each breakpoint. Execution does not stop unless the script block includes t he Break keyword. If you use the Continue keyword in the script block, execution resumes until the next breakpoint. For more information, see about_Script_Blocks, about_Break, and about_C ontinue. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Column <int> Specifies the column number of the column in the script file on which e xecution stops. Enter only one column number. The default is column 1. The Column value is used with the value of the Line parameter to specif y the breakpoint. If the Line parameter specifies multiple lines, the C olumn parameter sets a breakpoint at the specified column on each of th e specified lines. Windows PowerShell stops executing before the statem ent or expression that includes the character at the specified line and column position. Columns are counted from the top left margin beginning with column numb er 1 (not 0). If you specify a column that does not exist in the script , an error is not declared, but the breakpoint is never executed. Required? false Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false -Command <string[]> Sets a command breakpoint. Enter command names, such as "Get-Process" o r function names. Wildcards are permitted. Execution stops just before each instance of each command is executed. If the command is a function, execution stops each time the function is called and at each BEGIN, PROCESS, and END section. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? true -Line <Int32[]> Sets a line breakpoint in a script. Enter one or more line numbers, sep arated by commas. Windows PowerShell stops immediately before executing the statement that begins on each of the specified lines. Lines are counted from the top left margin of the script file beginning with line number 1 (not 0). If you specify a blank line, execution sto ps before the next non-blank line. If the line is out of range, the bre akpoint is never hit. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Mode <VariableAccessMode> Determines the mode of access that triggers variable breakpoints. The d efault is Write. This parameter is valid only when the Variable parameter is used in the command. The mode applies to all breakpoints set in the command. Valid values are: -- Write: Stops execution immediately before a new value is written to the variable. -- Read: Stops execution when the variable is read, that is, when its value is accessed, either to be assigned, displayed, or used. In read m ode, execution does not stop when the value of the variable changes. -- ReadWrite: Stops execution when the variable is read or written. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Script <string[]> Sets a breakpoint in each of the specified script files. Enter the path s and file names of one or more script files. If the files are in the c urrent directory, you can omit the path. Wildcards are permitted. By default, variable breakpoints and command breakpoints are set on any command that runs in the current session. This parameter is required o nly when setting a line breakpoint. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? true -Variable <string[]> Sets a variable breakpoint. Enter a comma-separated list of variables w ithout dollar signs ($). Use the Mode parameters to determine the mode of access that triggers t he breakpoints. The default mode, Write, stops execution just before a new value is written to the variable. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to Set-PSBreakpoint. OUTPUTS Breakpoint object (System.Management.Automation.LineBreakpoint, System.Mana gement.Automation.VariableBreakpoint, System.Management.Automation.CommandB reakpoint) Set-PSBreakpoint returns an object that represents each breakpoint that it sets. NOTES Set-PSBreakpoint cannot set a breakpoint on a remote computer. To debug a script on a remote computer, copy the script to the local computer a nd then debug it locally. When you set a breakpoint on more than one line, command, or variable, Set-PSBreakpoint generates a breakpoint object for each entry. When setting a breakpoint on a function or variable at the command prom pt, you can set the breakpoint before or after you create the function or variable. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-psbreakpoint -script sample.ps1 -line 5 Column : 0 Line : 5 Action : Enabled : True HitCount : 0 Id : 0 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Description ----------- This command sets a breakpoint at line 5 in the Sample.ps1 script. As a res ult, when the script runs, execution stops immediately before line 5 would execute. When you set a new breakpoint by line number, the Set-PSBreakpoint cmdlet g enerates a line breakpoint object (System.Management.Automation.LineBreakpo int) that includes the breakpoint ID and hit count, as shown in the followi ng sample output. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-psbreakpoint -command Increment -script sample.ps1 Command : Increment Action : Enabled : True HitCount : 0 Id : 1 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Description ----------- This command creates a command breakpoint on the Increment function in the Sample.ps1 cmdlet. The script stops executing immediately before each call to the specified function. The result is a command breakpoint object. Before the script runs, the valu e of the HitCount property is 0. -------------------------- EXAMPLE 3 -------------------------- C:\PS>set-psbreakpoint -script sample.ps1 -variable Server -Mode ReadWrite Description ----------- This command sets a breakpoint on the Server variable in the Sample.ps1 scr ipt. It uses the Mode parameter with a value of ReadWrite to stop execution when the value of the variable is read and just before the value changes. -------------------------- EXAMPLE 4 -------------------------- C:\PS>set-psbreakpoint -script Sample.ps1 -command "write*" Description ----------- This command sets a breakpoint on every command in the Sample.ps1 script th at begins with "write", such as "write-host". -------------------------- EXAMPLE 5 -------------------------- C:\PS>set-psbreakpoint -script test.ps1 -command DiskTest ` -action { (if $disk -gt 2) { break } } Description ----------- This command stops execution at the DiskTest function in the Test.ps1 scrip t only when the value of the $disk variable is greater than 2. It uses the Set-PSBreakpoint cmdlet to set a command breakpoint on the Disk Test function. The value of the action is a script block that tests the val ue of the $disk variable in the function. The action uses the BREAK keyword to stop execution if the condition is met . The alternative (and the default) is CONTINUE. -------------------------- EXAMPLE 6 -------------------------- C:\PS>set-psbreakpoint -command checkpoint-computer Id : 0 Command : checkpoint-computer Enabled : True HitCount : 0 Action : C:\PS> function CheckLog { >> get-eventlog -log Application | >> where {($_.source -like "TestApp") -and ($_.Message -like "*failed*")} >>} >> C:\PS> Checklog DEBUG: Hit breakpoint(s) DEBUG: Function breakpoint on 'prompt:Checklog' C:\PS>>> Description ----------- This command sets a breakpoint on the CheckLog function. Because the comman d does not specify a script, the breakpoint is set on anything that runs in the current session. The debugger breaks when the function is called, not when it is declared. -------------------------- EXAMPLE 7 -------------------------- C:\PS>set-psbreakpoint -script sample.ps1 -line 1, 14, 19 -column 2 -action {&(log.ps1)} Column : 2 Line : 1 Action : Enabled : True HitCount : 0 Id : 6 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Column : 2 Line : 14 Action : Enabled : True HitCount : 0 Id : 7 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Column : 2 Line : 19 Action : Enabled : True HitCount : 0 Id : 8 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Description ----------- This command sets three line breakpoints in the Sample.ps1 script. It sets one breakpoint at column 2 on each of the lines specified in the script. Th e action specified in the Action parameter applies to all breakpoints. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113449 about_Debuggers Get-PSBreakpoint Enable-PSBreakpoint Disable-PSBreakpoint Remove-PSBreakpoint Get-PSCallStack Set-PSDebug NAME Set-PSDebug SYNOPSIS Turns script debugging features on and off, sets the trace level, and toggl es strict mode. SYNTAX Set-PSDebug [-Off] [<CommonParameters>] Set-PSDebug [-Step] [-Strict] [-Trace <int>] [<CommonParameters>] DESCRIPTION The Set-PSDebug cmdlet turns script debugging features on and off, sets the trace level, and toggles strict mode. When the Trace parameter is set to 1, each line of script is traced as it i s executed. When the parameter is set to 2, variable assignments, function calls, and script calls are also traced. If the Step parameter is specified , you are prompted before each line of the script is executed. PARAMETERS -Off [<SwitchParameter>] Turns off all script debugging features. Note: A "set-strictmode -off" command disables the verification set by a "set-psdebug -strict" command. For more information, see Set-StrictMo de. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Step [<SwitchParameter>] Turns on script stepping. Before each line is run, the user is prompted to stop, continue, or enter a new interpreter level to inspect the sta te of the script. Note: Specifying the Step parameter automatically sets a Trace level of 1. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Strict [<SwitchParameter>] Specifies that the interpreter should throw an exception if a variable is referenced before a value is assigned to the variable. Note: A "set-strictmode -off" command disables the verification set by a "set-psdebug -strict" command. For more information, see Set-StrictMo de. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Trace <int> Specifies the trace level: 0 - Turn script tracing off 1 - Trace script lines as they are executed 2 - Trace script lines, variable assignments, function calls, and scri pts. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not return any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-psdebug -trace 2; foreach ($i in 1..3) {$i} DEBUG: 1+ Set-PsDebug -trace 2; foreach ($i in 1..3) {$i} DEBUG: 1+ Set-PsDebug -trace 2; foreach ($i in 1..3) {$i} 1 DEBUG: 1+ Set-PsDebug -trace 2; foreach ($i in 1..3) {$i} 2 DEBUG: 1+ Set-PsDebug -trace 2; foreach ($i in 1..3) {$i} 3 Description ----------- This command sets the trace level to 2, and then runs a script that display s the numbers 1, 2, and 3. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-psdebug -step; foreach ($i in 1..3) {$i} DEBUG: 1+ Set-PsDebug -step; foreach ($i in 1..3) {$i} Continue with this operation? 1+ Set-PsDebug -step; foreach ($i in 1..3) {$i} [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):a DEBUG: 1+ Set-PsDebug -step; foreach ($i in 1..3) {$i} 1 2 3 Description ----------- This command turns on stepping and then runs a script that displays the numbers 1, 2, and 3. -------------------------- EXAMPLE 3 -------------------------- C:\PS>set-psdebug -off; foreach ($i in 1..3) {$i} 1 2 3 Description ----------- This command turns off all debugging features, and then runs a script that displays the numbers 1, 2, and 3. -------------------------- EXAMPLE 4 -------------------------- C:\PS>set-psdebug -strict; $NewVar The variable $NewVar cannot be retrieved because it has not been set yet. At line:1 char:28 + Set-PsDebug -strict;$NewVar Description ----------- This command puts the interpreter in strict mode, and attempts to access a variable that has not yet been set. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113398 about_Debuggers Debug-Process Set-PSBreakpoint Set-StrictMode Write-Debug Set-PSSessionConfiguration NAME Set-PSSessionConfiguration SYNOPSIS Changes the properties of a registered session configuration. SYNTAX Set-PSSessionConfiguration [-AssemblyName] <string> [-ConfigurationTypeName ] <string> [-Name] <string> [-ApplicationBase <string>] [-Force] [-MaximumR eceivedDataSizePerCommandMB <double>] [-MaximumReceivedObjectSizeMB <double >] [-NoServiceRestart] [-SecurityDescriptorSDDL <string>] [-ShowSecurityDes criptorUI] [-StartupScript <string>] [-ThreadApartmentState {STA | MTA | Un known}] [-ThreadOptions {Default | UseNewThread | ReuseThread | UseCurrentT hread}] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Set-PSSessionConfiguration cmdlet changes the properties of the registe red session configurations on the local computer. This is an advanced cmdle t that is designed to be used by system administrators to manage customized session configurations for their users. Use the Name parameter to identify the configuration that you want to chang e. Use the other parameters to specify new values for the properties of the session configuration. To delete a property value from the configuration ( and use the default value), enter an empty string ("") or a value of $null for the corresponding parameter. To see the properties of a session configuration, use the Get-PSSessionConf iguration cmdlet or the WS-Management Provider. For more information about the WS-Management Provider, type "get-help wsman". PARAMETERS -ApplicationBase <string> Changes the path to the assembly file (*.dll) that is specified in the value of the AssemblyName parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -AssemblyName <string> Specifies a different assembly file for the configuration. Enter the pa th (optional) and file name of an assembly (.dll) file that defines the configuration type. If you enter only the name, you can enter the path in the value of the ApplicationBase parameter. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -ConfigurationTypeName <string> Specifies a different configuration type for the configuration. The typ e that you specify must implement the System.Management.Automation.Remo ting.PSSessionConfiguration class. If you enter "$null" or an empty string, the DefaultRemotePowerShellCon figuration class is used for the session configuration. Required? true Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Suppresses all user prompts, and restarts the WinRM service without pro mpting. Restarting the service makes the configuration change effective . To prevent a restart and suppress the restart prompt, use the NoService Restart parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -MaximumReceivedDataSizePerCommandMB <double> Changes the limit on the amount of data that can be sent to this comput er in any single remote command. Enter the data size in megabytes (MB). The default is 50 MB. If a data size limit is defined in the configuration type that is speci fied in the ConfigurationTypeName parameter, the limit in the configura tion type is used and the value of this parameter is ignored. Required? false Position? named Default value 50 Accept pipeline input? false Accept wildcard characters? false -MaximumReceivedObjectSizeMB <double> Changes the limits on the amount of data that can be sent to this compu ter in any single object. Enter the data size in megabytes (MB). The de fault is 10 MB. If an object size limit is defined in the configuration type that is sp ecified in the ConfigurationTypeName parameter, the limit in the config uration type is used and the value of this parameter is ignored. Required? false Position? named Default value 10 Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies the name of the session configuration that you want to change . You cannot use this parameter to change the name of the session configu ration. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -NoServiceRestart [<SwitchParameter>] Does not restart the WinRM service, and suppresses the prompt to restar t the service. By default, when you enter a Set-PSSessionConfiguration command, you ar e prompted to restart the WinRM service to make the new session configu ration effective. Until the WinRM service is restarted, the new sessio n configuration is not effective. To restart the WinRM service without prompting, use the Force parameter . To restart the WinRM service manually, use the Restart-Service cmdlet . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SecurityDescriptorSDDL <string> Specifies a different Security Descriptor Definition Language (SDDL) st ring for the configuration. This string determines the permissions that are required to use the new session configuration. To use a session configuration in a session, us ers must have at least "Execute(Invoke)" permission for the configurati on. To use the default security descriptor for the configuration, enter an empty string ("") or a value of $null. The default is the root SDDL in the WSMan: drive. If the security descriptor is complex, consider using the ShowSecurityD escriptorUI parameter instead of this one. You cannot use both paramete rs in the same command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ShowSecurityDescriptorUI [<SwitchParameter>] Displays a property sheet that helps you to create a new SDDL for the s ession configuration. The property sheet appears after you enter the Se t-PSSessionConfiguration command and then restart the WinRM service. When setting the permissions to the configuration, remember that users must have at least "Execute(Invoke)" permission to use the session conf iguration in a session. You cannot use the SecurityDescriptorSDDL parameter and this parameter in the same command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -StartupScript <string> Adds or changes the startup script for the configuration. Enter the ful ly qualified path to a Windows PowerShell script. The specified script runs in the new session that uses the session configuration. To delete a startup script from a session configuration, enter an empty string ("") or a value of $null. You can use a startup script to further configure the user's session. I f the script generates an error (even a non-terminating error), the ses sion is not created and the user's New-PSSession command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ThreadApartmentState <ApartmentState> Changes the apartment state setting for the threads in the session. Val id values are STA, MTA and Unknown. Unknown is the default. Required? false Position? named Default value ApartmentState.Unknown Accept pipeline input? false Accept wildcard characters? false -ThreadOptions <PSThreadOptions> Changes the thread options setting in the configuration. This setting d efines how threads are created and used when a command is executed in t he session. Valid values are Default, ReuseThread, UseCurrentThread, an d UseNewThread. UseCurrentThread is the default. Required? false Position? named Default value PSThreadOptions.UserCurrentThread Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS Microsoft.WSMan.Management.WSManConfigLeafElement NOTES To run this cmdlet on Windows Vista, Windows Server 2008, and later ver sions of Windows, you must open Windows PowerShell with the "Run as adm inistrator" option. The Set-PSSessionConfiguration cmdlet does not change the configuration name and the WS-Management provider does not support the Rename-Item c mdlet. To change the name of a configuration, use the Unregister-PSSess ionConfiguration cmdlet to delete the configuration and then use the Re gister-PSSessionConfiguration cmdlet to create and register a new sessi on configuration. You can use the Set-PSSessionConfiguration cmdlet to change the default Microsoft.PowerShell and Microsoft.PowerShell32 session configurations . They are not protected. To revert to the original version of a defaul t session configuration, use the Unregister-PSSessionConfiguration cmdl et to delete the default session configuration and then use the Enable- PSRemoting cmdlet to restore it. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-pssessionconfiguration -name MaintenanceShell -threadApartmentSta te STA Description ----------- This command changes the thread apartment state in the MaintenanceShell con figuration to STA. The change is effective when you restart the WinRM servi ce. -------------------------- EXAMPLE 2 -------------------------- C:\PS>register-pssessionconfiguration -name AdminShell -assemblyName c:\she lls\AdminShell.dll -configurationType AdminClass C:\PS> set-pssessionconfiguration -name AdminShell -startupScript AdminConf ig.ps1 C:\PS> set-pssessionconfiguration -name AdminShell -startupScript $null Description ----------- This example shows how to create and then change a session configuration. The first command uses the Register-PSSessionConfiguration cmdlet to create the AdminShell configuration. The second command uses the Set-PSSessionConfiguration cmdlet to add the Ad minConfig.ps1 script to the configuration. The change is effective when you restart WinRM. The third command removes the AdminConfig.ps1 script from the configuration . It uses the Set-PSSessionConfiguration cmdlet with a value of $null for t he StartupScript parameter. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Set-PSSessionConfiguration -name foo -MaximumReceivedObjectSizeMB 20 WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin\foo\Init ializationParameters ParamName ParamValue --------- ---------- psmaximumreceivedobjectsizemb 20 "Restart WinRM service" WinRM service need to be restarted to make the changes effective. Do you wa nt to run the command "restart-service winrm"? [Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y Description ----------- This example show sample output from the Set-PSSessionConfiguration cmdlet. The Set-PSSessionConfiguration command in this example increases the value of the MaximumReceivedObjectSizeMB property to 20. The Set-PSSessionConfiguration command returns a Microsoft.WSMan.Management .WSManConfigLeafElement object that shows the parameter name and new value. It also prompts you to restart the WinRM service. The Set-PSSessionConfigur ation change is not effective until the WinRM service is restarted. -------------------------- EXAMPLE 4 -------------------------- C:\PS>set-pssessionconfiguration -name MaintenanceShell -startupScript c:\p s-test\Maintenance.ps1 WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin\Maintena nceShell\InitializationParameters ParamName ParamValue --------- ---------- startupscript c:\ps-test\Mainte... "Restart WinRM service" WinRM service need to be restarted to make the changes effective. Do you wa nt to run the command "restart-service winrm"? [Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y C:\PS> get-pssessionConfiguration maintenanceshell | format-list -property * xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/PluginC onfiguration Name : MaintenanceShell Filename : %windir%\system32\pwrshplugin.dll SDKVersion : 1 XmlRenderingType : text lang : en-US PSVersion : 2.0 startupscript : c:\ps-test\Maintenance.ps1 ResourceUri : http://schemas.microsoft.com/powershell/MaintenanceShell SupportsOptions : true ExactMatch : true Capability : {Shell} Permission : C:\PS> dir wsman:\localhost\plugin\MaintenanceShell\InitializationParameter s ParamName ParamValue --------- ---------- PSVersion 2.0 startupscript c:\ps-test\Maintenance.ps1 Description ----------- This command shows different ways of viewing the results of a Set-PSSession Configuration command. The first command uses the Set-PSSessionConfiguration cmdlet to change the startup script in the MaintenanceShell configuration to Maintenance.ps1. Th e output of this command shows the change and prompts you to restart the Wi nRM service. The response is "y" (yes). The second command uses the Get-PSSessionConfiguration cmdlet to get the Ma intenanceShell session configuration. The command uses a pipeline operator (|) to send the results of the command to the Format-List cmdlet, which dis plays all of the properties of the session configuration object in a list. The third command uses the WS-Management provider to view the initializatio n parameters for the MaintenanceShell configuration. The command uses the G et-ChildItem cmdlet (alias = dir) to get the child items in the Initializat ionParameters node for the MaintenanceShell plug-in. For more information about the WS-Management provider, type "get-help wsman ". RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144307 about_Session_Configurations Disable-PSSessionConfiguration Enable-PSSessionConfiguration Get-PSSessionConfiguration Register-PSSessionConfiguration Unregister-PSSessionConfiguration WS-Management Provider Set-Service NAME Set-Service SYNOPSIS Starts, stops, and suspends a service, and changes its properties. SYNTAX Set-Service [-Name] <string> [-Description <string>] [-DisplayName <string> ] [-PassThru] [-StartupType {Automatic | Manual | Disabled}] [-Status <stri ng>] [-ComputerName <string[]>] [-Confirm] [-WhatIf] [<CommonParameters>] Set-Service [-Description <string>] [-DisplayName <string>] [-InputObject ServiceController>] [-PassThru] [-StartupType {Automatic | Manual | Disable d}] [-Status <string>] [-ComputerName <string[]>] [-Confirm] [-WhatIf] [<Co mmonParameters>] DESCRIPTION The Set-Service cmdlet changes the properties of a local or remote service, including the status, description, display name, and start mode. You can u se this cmdlet to start, stop, or suspend (pause) a service. To identify th e service, enter its service name or submit a service object, or pipe a ser vice name or service object to Set-Service. PARAMETERS -ComputerName <string[]> Specifies one or more computers. The default is the local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Set-Service even if your computer is no t configured to run remote commands. Required? false Position? named Default value local computer Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Description <string> Specifies a new description for the service. The service description appears in Services in Computer Management. Des cription is not a property of the ServiceController object that Get-Ser vice gets. To see the service description, use Get-WmiObject to get a W in32_Service object that represents the service. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -DisplayName <string> Specifies a new display name for the service. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ServiceController> Specifies a ServiceController object that represents the service to be changed. Enter a variable that contains the object, or type a command o r expression that gets the object, such as a Get-Service command. You c an also pipe a service object to Set-Service. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string> Specifies the service name of the service to be changed. Wildcards are not permitted. You can also pipe a service name to Set-Service. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns objects that represent the services that were changed. By defau lt, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -StartupType <ServiceStartMode> Changes the start mode of the service. Valid values for StartupType are : -- Automatic: Start when the system starts. -- Manual: Starts only when started by a user or program. -- Disabled: Cannot be started. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Status <string> Starts, stops, or suspends (pauses) the services. Valid values are: -- Running: Starts the service. -- Stopped: Stops the service. -- Paused: Suspends the service. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.ServiceProcess.ServiceController, System.String You can pipe a service object or a string that contains a service name to Set-Service. OUTPUTS None This cmdlet does not return any objects. NOTES To use Set-Service on Windows Vista and later versions of Windows, star t Windows PowerShell with the "Run as administrator" option. Set-Service can control services only when the current user has permiss ion to do so. If a command does not work correctly, you might not have the required permissions. To find the service names and display names of the services on your sys tem, type "get-service". The service names appear in the Name column an d the display names appear in the DisplayName column. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-service -name lanmanworkstation -DisplayName "LanMan Workstation" Description ----------- This command changes the display name of the lanmanworkstation service to " LanMan Workstation". (The default is "Workstation".) -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-wmiobject win32_service -filter "name = 'SysmonLog'" ExitCode : 0 Name : SysmonLog ProcessId : 0 StartMode : Manual State : Stopped Status : OK C:\PS> set-service sysmonlog -startuptype automatic C:\PS> get-wmiobject win32_service -filter "name = 'SysmonLog'" ExitCode : 0 Name : SysmonLog ProcessId : 0 StartMode : Auto State : Stopped Status : OK C:\PS> get-wmiobject win32_service | format-table Name, StartMode -auto Name StartMode ---- --------- AdtAgent Auto Alerter Disabled ALG Manual AppMgmt Manual ... Description ----------- These commands get the startup type of the Performance Logs and Alerts (Sys monLog) service, set the start mode to automatic, and then display the resu lt of the change. These commands use the Get-WmiObject cmdlet to get the Win32_Service object for the service, because the ServiceController object that Get-Service ret urns does not include the start mode. The first command uses the Get-WmiObject cmdlet to get the Windows Manageme nt Instrumentation (WMI) object that represents the SysmonLog service. The default output of this command displays the start mode of the service. The second command uses Set-Service to change the start mode to automatic. Then, the first command is repeated to display the change. The final command displays the start mode of all services on the computer. -------------------------- EXAMPLE 3 -------------------------- C:\PS>set-service -name Schedule -computername S1 -description "Configures and schedules tasks." C:\PS> get-wmiobject win32_service -computername s1 | where-object {$_.Name -eq "Schedule"} | format-list Name, Description Description ----------- These commands change the description of the Task Scheduler service on the S1 remote computer and then display the result. These commands use the Get-WmiObject cmdlet to get the Win32_Service object for the service, because the ServiceController object that Get-Service ret urns does not include the service description. The first command uses a Set-Service command to change the description. It identifies the service by using the service name of the service, "Schedule ". The second command uses the Get-WmiObject cmdlet to get an instance of the WMI Win32_Service that represents the Task Scheduler service. The first ele ment in the command gets all instances of the Win32_service class. The pipeline operator (|) passes the result to the Where-Object cmdlet, whi ch selects instances with a value of "Schedule" in the Name property. Another pipeline operator sends the result to the Format-List cmdlet, which formats the output as a list with only the Name and Description properties . -------------------------- EXAMPLE 4 -------------------------- C:\PS>set-service winrm -status Running -passthru -computername Server02 Description ----------- This command starts the WinRM service on the Server02 computer. The command uses the Status parameter to specify the desired status ("running") and th e PassThru parameter to direct Set-Service to return an object that represe nts the WinRM service. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-service schedule -computername S1, S2 | set-service -status pause d Description ----------- This command suspends the Schedule service on the S1 and S2 remote computer s. It uses the Get-Service cmdlet to get the service. A pipeline operator ( |) sends the service to the Set-Service cmdlet, which changes its status to "Paused". -------------------------- EXAMPLE 6 -------------------------- C:\PS>$s = get-service schedule C:\PS> set-service -inputobject $s -status stopped Description ----------- These commands stop the Schedule service on the local computer. The first command uses the Get-Service cmdlet to get the Schedule service. The command saves the service in the $s variable. The second command uses the Set-Service cmdlet to change the status of the Schedule service to "Stopped". It uses the InputObject parameter to submit the service stored in the $s variable, and it uses the Status parameter to specify the desired status. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113399 Get-Service Start-Service Stop-Service Restart-Service Resume-Service Suspend-Service New-Service Set-StrictMode NAME Set-StrictMode SYNOPSIS Establishes and enforces coding rules in expressions, scripts, and script b locks. SYNTAX Set-StrictMode -Off [<CommonParameters>] Set-StrictMode -Version <Version> [<CommonParameters>] DESCRIPTION The Set-StrictMode cmdlet configures strict mode for the current scope (and all child scopes) and turns it on and off. When strict mode is on, Windows PowerShell generates a terminating error when the content of an expression , script, or script block violates basic best-practice coding rules. Use the Version parameter to determine which coding rules are enforced. Unlike the Set-PSDebug cmdlet, Set-StrictMode affects only the current scop e and its child scopes, so you can use it in a script or function without a ffecting the global scope. When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $null, depending on type. References to non -existent properties return $null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted. PARAMETERS -Off [<SwitchParameter>] Turns strict mode off. This parameter also turns off "Set-PSDebug -Stri ct". Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Version <Version> Specifies the conditions that cause an error in strict mode. This param eter is required. The valid values are "1.0", "2.0", and "Latest". The following list sho ws the effect of each value. 1.0 -- Prohibits references to uninitialized variables, except for uninitia lized variables in strings. 2.0 -- Prohibits references to uninitialized variables (including uninitial ized variables in strings). -- Prohibits references to non-existent properties of an object. -- Prohibits function calls that use the syntax for calling methods. -- Prohibits a variable without a name (${}). Latest: --Selects the latest (most strict) version available. Use this value t o assure that scripts use the strictest available version, even when ne w versions are added to Windows PowerShell. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not return any output. NOTES Set-StrictMode is similar to the Strict parameter of Set-PSDebug. "Set- Strictmode -version 1" is equivalent to "Set-PSDebug -strict", except t hat Set-PSDebug is effective in all scopes. Set-StrictMode is effective only in the scope in which it is set and in its child scopes. For more information about scopes in Windows PowerShell, see about_Scopes. -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-strictmode -version 1.0 C:\PS> $a -gt 5 False The variable $a cannot be retrieved because it has not been set yet. At line:1 char:3 + $a < -gt 5 + CategoryInfo : InvalidOperation: (a:Token) [], RuntimeExcept ion + FullyQualifiedErrorId : VariableIsUndefined Description ----------- This command turns strict mode on and sets it to version 1.0. As a result, attempts to reference variables that are not initialized will fail. The sample output shows the effect of version 1.0 strict mode. -------------------------- EXAMPLE 2 -------------------------- C:\PS># set-strictmode -version 2.0 # Strict mode is off by default. C:\PS> function add ($a, $b) {$a + $b} C:\PS> add 3 4 7 C:\PS> add(3,4) 3 4 C:\PS> set-strictmode -version 2.0 C:\PS> add(3,4) The function or command was called like a method. Parameters should be sepa rated by spaces, as described in 'Get-Help about_Parameter.' At line:1 char:4 + add < (3,4) + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : StrictModeFunctionCallWithParens C:\PS> set-strictmode -off C:\PS> $string = "This is a string". C:\PS> $string.Month C:\PS> C:\PS> set-strictmode -version 2.0 C:\PS> $string = "This is a string". C:\PS> $string.Month Property 'month' cannot be found on this object; make sure it exists. At line:1 char:9 + $string. < month + CategoryInfo : InvalidOperation: (.:OperatorToken) [], Runti meException + FullyQualifiedErrorId : PropertyNotFoundStrict Description ----------- This command turns strict mode on and sets it to version 2.0. As a result, Windows PowerShell throws an error if you use method syntax (parentheses an d commas) for a function call or reference uninitialized variables or non-e xistent properties. The sample output shows the effect of version 2.0 strict mode. Without version 2.0 strict mode, the "(3,4)" value is interpreted as a sing le array object to which nothing is added. With version 2.0 strict mode, it is correctly interpreted as faulty syntax for submitting two values. Without version 2.0, the reference to the non-existent Month property of a string returns only null. With version 2.0, it is interpreted correctly as a reference error. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113450 about_Debuggers about_Scopes Set-PSDebug Set-TraceSource NAME Set-TraceSource SYNOPSIS Configures, starts, and stops a trace of Windows PowerShell components. SYNTAX Set-TraceSource [[-Option] {None | Constructor | Dispose | Finalizer | Meth od | Property | Delegates | Events | Exception | Lock | Error | Errors | Wa rning | Verbose | WriteLine | Data | Scope | ExecutionFlow | Assert | All}] [-Debugger] [-FilePath <string>] [-Force] [-ListenerOption {None | Logical OperationStack | DateTime | Timestamp | ProcessId | ThreadId | Callstack}] [-PassThru] [-PSHost] [-Name] <string[]> [<CommonParameters>] Set-TraceSource [-RemoveListener <string[]>] [-Name] <string[]> [<CommonPar ameters>] Set-TraceSource [-RemoveFileListener <string[]>] [-Name] <string[]> [<Commo nParameters>] DESCRIPTION The Set-TraceSource cmdlet configures, starts, and stops a trace of a Windo ws PowerShell component. You can use it to specify which components will be traced and where the tracing output is sent. PARAMETERS -Debugger [<SwitchParameter>] Sends the trace output to the debugger. You can view the output in any user-mode or kernel mode debugger or in Microsoft Visual Studio. This p arameter also selects the default trace listener. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -FilePath <string> Sends the trace output to the specified file. This parameter also selec ts the file trace listener. If you use this parameter to start the trac e, use the RemoveFileListener parameter to stop the trace. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to overwrite a read-only file. Use with the FilePath parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ListenerOption <TraceOptions> Adds optional data to the prefix of each trace message in the output. T he valid values are "None", "LogicalOperationStack", "DateTime", "Times tamp", "ProcessId", "ThreadId", and "Callstack". "None" is the default. To specify multiple options, separate them with commas, but with no spa ces, and enclose them in quotation marks, such as "ProcessID,ThreadID". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Determines which components are traced. Enter the name of the trace sou rce of each component. Wildcards are permitted. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Option <PSTraceSourceOptions> Determines the type of events that are traced. The valid values are: "None", "Constructor", "Dispose", "Finalizer", "M ethod", "Property", "Delegates", "Events", "Exception", "Lock", "Error" , "Errors", "Warning", "Verbose", "WriteLine", "Data", "Scope", "Execut ionFlow", "Assert", and "All". "All" is the default. The following values are combinations of other values: -- ExecutionFlow: (Constructor, Dispose, Finalizer, Method, Delegates, Events, and Scope) -- Data: (Constructor, Dispose, Finalizer, Property, Verbose, and Write Line) -- Errors: (Error and Exception). To specify multiple options, separate them with commas, but with no spa ces, and enclose them in quotation marks, such as "Constructor,Dispose" . Required? false Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the trace session. By default, this cmdl et does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PSHost [<SwitchParameter>] Sends the trace output to the Windows PowerShell host. This parameter a lso selects the PSHost trace listener. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -RemoveFileListener <string[]> Stops the trace by removing the file trace listener associated with the specified file. Enter the path and file name of the trace output file. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -RemoveListener <string[]> Stops the trace by removing the trace listener. Use the following values with RemoveListener: --To remove PSHost (console), type "Host". --To remove Debugger, type "Debug". --To remove all trace listeners, type "*". To remove the file trace listener, use the RemoveFileListener parameter . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a name to Set-TraceSource. OUTPUTS None or System.Management.Automation.PSTraceSource When you use the PassThru parameter, Set-TraceSource generates a System .Management.Automation.PSTraceSource object representing the trace sess ion. Otherwise, this cmdlet does not generate any output. NOTES Tracing is a method that developers use to debug and refine programs. W hen tracing, the program generates detailed messages about each step in its internal processing. The Windows PowerShell tracing cmdlets are designed to help Windows Pow erShell developers, but they are available to all users. They let you m onitor nearly every aspect of the functionality of Windows PowerShell. A "trace source" is the part of each Windows PowerShell component that manages tracing and generates trace messages for the component. To trac e a component, you identify its trace source. A "trace listener" receives the output of the trace and displays it to the user. You can elect to send the trace data to a user-mode or kernel -mode debugger, to the console, to a file, or to a custom listener deri ved from the System.Diagnostics.TraceListener class. To start a trace, use the Name parameter to specify a trace source (the component to be traced) and the FilePath, Debugger, or PSHost paramete rs to specify a listener (a destination for the output). Use the Option s parameter to determine the types of events that are traced and the Li stenerOptions parameter to configure the trace output. To change the configuration of a trace, enter a Set-TraceSource command as you would to start a trace. Windows PowerShell recognizes that the trace source is already being traced. It stops the trace, adds the new configuration, and starts or restarts the trace. To stop a trace, use the RemoveListener parameter. To stop a trace that uses the file listener (a trace started by using the -FilePath paramet er), use the RemoveFileListener parameter. When you remove the listener , the trace stops. To determine which components can be traced, use Get-TraceSource. The t race sources for each module are loaded automatically when the componen t is in use, and they appear in the output of Get-TraceSource. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Set-TraceSource -Name Parameterbinding -Option ExecutionFlow -PSHost ' -ListenerOption "ProcessID,TimeStamp" Description ----------- This command starts tracing for the ParameterBinding component of Windows P owerShell. It uses the Name parameter to specify the trace source, the Opti on parameter to select the ExecutionFlow trace events, and the PSHost param eter to select the Windows PowerShell host listener, which sends the output to the console. The ListenerOption parameter adds the "ProcessID" and "Tim eStamp" values to the trace message prefix. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-tracesource -name ParameterBinding -RemoveListener Host Description ----------- This command stops the trace of the ParameterBinding component of Windows P owerShell. It uses the Name parameter to identify the component that was be ing traced and the RemoveListener parameter to identify the trace listener. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113400 Get-TraceSource Trace-Command Set-PSDebug Set-Variable NAME Set-Variable SYNOPSIS Sets the value of a variable. Creates the variable if one with the requeste d name does not exist. SYNTAX Set-Variable [-Name] <string[]> [[-Value] <Object>] [-Description <string>] [-Exclude <string[]>] [-Force] [-Include <string[]>] [-Option {None | Read Only | Constant | Private | AllScope}] [-PassThru] [-Scope <string>] [-Visi bility {Public | Private}] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Set-Variable cmdlet assigns a value to a specified variable or changes the current value. If the variable does not exist, the cmdlet creates it. PARAMETERS -Description <string> Specifies the description of the variable. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows you to create a variable with the same name as an existing read- only variable, or to change the value of a read-only variable. By default, you can overwrite a variable, unless the variable has an op tion value of "ReadOnly" or "Constant". For more information, see the O ption parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Changes only the specified items. The value of this parameter qualifies the Name parameter. Enter a name or name pattern, such as "c*". Wildca rds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Specifies the variable name. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Option <ScopedItemOptions> Changes the value of the Options property of the variable. Valid values are: -- None: Sets no options. ("None" is the default.) -- ReadOnly: The properties of the variable cannot be changed, except b y using the Force parameter. You can use Remove-Variable to delete the variable. -- Constant: The variable cannot be deleted and its properties cannot b e changed. "Constant" is available only when you are creating an alias. You cannot change the option of an existing variable to "Constant". -- Private: The variable is available only within the scope specified b y the Scope parameter. It is inherited by child scopes. -- AllScope: The variable is copied to any new scopes that are created. To see the Options property of the variables, type "get-variable| forma t-table -property name, options -autosize". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the new variable. By default, this cmdle t does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Scope <string> Determines the scope of the variable. Valid values are "Global", "Local ", or "Script", or a number relative to the current scope (0 through th e number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Value <Object> Specifies the value of the variable. Required? false Position? 2 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Visibility <SessionStateEntryVisibility> Determines whether the variable is visible outside of the session in wh ich it was created. This parameter is designed for use in scripts and commands that will be delivered to other users. Valid values are: -- Public: The variable is visible. ("Public" is the default.) -- Private: The variable is not visible. When a variable is private, it does not appear in lists of variables, s uch as those returned by Get-Variable, or in displays of the Variable: drive. Commands to read or change the value of a private variable retur n an error. However, the user can run commands that use a private varia ble if the commands were written in the session in which the variable w as defined. Required? false Position? named Default value Public Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe an object that represents the value of the variable to Set -Variable. OUTPUTS None or System.Management.Automation.PSVariable When you use the PassThru parameter, Set-Variable generates a System.Ma nagement.Automation.PSVariable object representing the new or changed v ariable. Otherwise, this cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-variable -name desc -value "A description" C:\PS>get-variable -name desc Description ----------- These commands set the value of the "desc" variable to "A description", and then get the value of the variable. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-variable -name processes -value (Get-Process) -option constant -s cope global -description "All processes" -passthru | format-list -property * Description ----------- This command creates a global, read-only variable that contains all process es on the system, and then it displays all properties of the variable. The command uses the Set-Variable cmdlet to create the variable. It uses th e PassThru parameter to create an object representing the new variable, and it uses the pipeline operator (|) to pass the object to the Format-List cm dlet. It uses the Property parameter of Format-List with a value of all (*) to display all properties of the newly created variable. The value, "(Get-Process)", is enclosed in parentheses to ensure that it is executed before being stored in the variable. Otherwise, the variable cont ains the words "Get-Process". -------------------------- EXAMPLE 3 -------------------------- C:\PS># set-variable -name counter -visibility private C:\PS> new-variable -name counter -visibility public -value 26 C:\PS> $counter 26 C:\PS> get-variable c* Name Value ---- ----- Culture en-US ConsoleFileName ConfirmPreference High CommandLineParameters {} Counter 26 C:\PS> set-variable -name counter -visibility private C:\PS> get-variable c* Name Value ---- ----- Culture en-US ConsoleFileName ConfirmPreference High CommandLineParameters {} C:\PS> $counter "Cannot access the variable '$counter' because it is a private variable" C:\PS> .\use-counter.ps1 Commands completed successfully. Description ----------- This command shows how to change the visibility of a variable to "Private". This variable can be read and changed by scripts with the required permiss ions, but it is not visible to the user. The sample output shows the difference in the behavior of public and privat e variables. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113401 Get-Variable New-Variable Remove-Variable Clear-Variable Set-WmiInstance NAME Set-WmiInstance SYNOPSIS Creates or updates an instance of an existing Windows Management Instrument ation (WMI) class. SYNTAX Set-WmiInstance [-Class] <string> [[-Arguments] <hashtable>] [-Authenticati on {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPriv acy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Creden tial <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anon ymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {None | UpdateOnly | CreateOnly | UpdateOrCrea te}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] Set-WmiInstance [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Com puterName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [ -Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [ -Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {None | UpdateOn ly | CreateOnly | UpdateOrCreate}] [-ThrottleLimit <int>] [-Confirm] [-What If] [<CommonParameters>] Set-WmiInstance -InputObject <ManagementObject> [-Arguments <hashtable>] [- AsJob] [-PutType {None | UpdateOnly | CreateOnly | UpdateOrCreate}] [-Throt tleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] Set-WmiInstance -Path <string> [-Arguments <hashtable>] [-Authentication {D efault | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-ComputerName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Locale <string>] [-Namespace <stri ng>] [-AsJob] [-PutType {None | UpdateOnly | CreateOnly | UpdateOrCreate}] [-ThrottleLimit <int>] [-Confirm] [-WhatIf] [<CommonParameters>] Set-WmiInstance [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Com puterName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [ -Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [ -Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {None | UpdateOn ly | CreateOnly | UpdateOrCreate}] [-ThrottleLimit <int>] [-Confirm] [-What If] [<CommonParameters>] Set-WmiInstance [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrity | PacketPrivacy | Unchanged}] [-Authority <string>] [-Com puterName <string[]>] [-Credential <PSCredential>] [-EnableAllPrivileges] [ -Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [ -Locale <string>] [-Namespace <string>] [-AsJob] [-PutType {None | UpdateOn ly | CreateOnly | UpdateOrCreate}] [-ThrottleLimit <int>] [-Confirm] [-What If] [<CommonParameters>] DESCRIPTION The Set-WmiInstance cmdlet creates or updates an instance of an existing WM I class. The created or updated instance is written to the WMI repository. PARAMETERS -Arguments <hashtable> Specifies the name of the property to be changed and the new value for that property. The name and value must be in a name-value pair. The na me-value pair is passed on the command-line as a hash table. For examp le: -argument @{Setting1=1; Setting2=5; Setting3="test"}. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -AsJob [<SwitchParameter>] Runs the command as a background job. Use this parameter to run command s that take a long time to finish. When you use the AsJob parameter, the command returns an object that re presents the background job and then displays the command prompt. You c an continue to work in the session while the job finishes. If Set-WmiOb ject is used against a remote computer, the job is created on the local computer, and the results from remote computers are automatically retu rned to the local computer. To manage the job, use the cmdlets that con tain the Job noun (the Job cmdlets). To get the job results, use the Re ceive-Job cmdlet. Note: To use this parameter with remote computers, the local and remote computers must be configured for remoting. Additionally, you must star t Windows PowerShell by using the "Run as administrator" option in Wind ows Vista and later versions of Windows,. For more information, see abo ut_Remote_Requirements. For more information about Windows PowerShell background jobs, see abo ut_Jobs and about_Remote_Jobs. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationLevel> Specifies the authentication level to be used with the WMI connection. Valid values are: -1: Unchanged 0: Default 1: None (No authentication in performed.) 2: Connect (Authentication is performed only when the client establishe s a relationship with the application.) 3: Call (Authentication is performed only at the beginning of each call when the application receives the request.) 4: Packet (Authentication is performed on all the data that is received from the client.) 5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.) 6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.) Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authority <string> Specifies the authority to use to authenticate the WMI connection. You can specify standard NTLM or Kerberos authentication. To use NTLM, set the authority setting to ntlmdomain:<DomainName>, where <DomainName> id entifies a valid NTLM domain name. To use Kerberos, specify kerberos:<D omainName>\<ServerName>". You cannot include the authority setting when you connect to the local computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Class <string> Specifies the name of a WMI class. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name. You can set the value of this parameter by piping the value to the parameter. This parameter does not rely on Windows PowerShell remoting, which uses WS-Management ). You can use the ComputerName parameter of Get-WmiObje ct even if your computer is not configured to run WS-Management remote commands. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or User@Contoso.com. Or, enter a PSCredential object, su ch as an object that is returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -EnableAllPrivileges [<SwitchParameter>] Enables all the privileges of the current user before the command makes the WMI call . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Impersonation <ImpersonationLevel> Specifies the impersonation level to use. Valid values are: 0: Default (Reads the local registry for the default impersonation leve l, which is usually set to "3: Impersonate".) 1: Anonymous (Hides the credentials of the caller.) 2: Identify (Allows objects to query the credentials of the caller.) 3: Impersonate (Allows objects to use the credentials of the caller.) 4: Delegate (Allows objects to permit other objects to use the credenti als of the caller.) Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ManagementObject> Specifies a ManagementObject object to use as input. When this paramete r is used, all other parameters ,except the Arguments parameter, are ig nored. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Locale <string> Specifies the preferred locale for WMI objects. The Locale parameter is specified in an array in the MS_<LCID> format in the preferred order. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Namespace <string> When used with the Class parameter, this parameter specifies the WMI re pository namespace where the referenced WMI class is located. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies a WMI object path to the instance that you want to create or update. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PutType <PutType> Indicates whether the WMI instance should be created or updated. Valid values are: UpdateOnly: Updates an existing WMI instance. CreateOnly: Creates a new WMI instance. UpdateOrCreate: Updates the WMI instance if it exists or creates a new instance if an instance does not exist. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Allows the user to specify a throttling value for the number of WMI ope rations that can be executed simultaneously. This parameter is used tog ether with the AsJob parameter. The throttle limit applies only to the current command, not to the session or to the computer. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept input. OUTPUTS None This cmdlet does not generate output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>Set-WMIInstance -class Win32_WMISetting -argument @{LoggingLevel=2} __GENUS : 2 __CLASS : Win32_WMISetting __SUPERCLASS : CIM_Setting __DYNASTY : CIM_Setting __RELPATH : Win32_WMISetting=@ __PROPERTY_COUNT : 27 __DERIVATION : {CIM_Setting} __SERVER : SYSTEM01 __NAMESPACE : root\cimv2 __PATH : \\SYSTEM01\root\cimv2:Win32_WMISetting=@ ASPScriptDefaultNamespace : \\root\cimv2 ASPScriptEnabled : False AutorecoverMofs : {%windir%\system32\wbem\cimwin32.mof, %win dir%\system32\wbem\ncprov.mof, %windir%\syst em32\wbem\wmipcima.mof, %windir%\system32\ wbem\secrcw32.mof...} AutoStartWin9X : BackupInterval : BackupLastTime : BuildVersion : 6001.18000 Caption : DatabaseDirectory : C:\Windows\system32\wbem\repository DatabaseMaxSize : Description : EnableAnonWin9xConnections : EnableEvents : False EnableStartupHeapPreallocation : False HighThresholdOnClientObjects : HighThresholdOnEvents : 20000000 InstallationDirectory : C:\Windows\system32\wbem LastStartupHeapPreallocation : LoggingDirectory : C:\Windows\system32\wbem\Logs\ LoggingLevel : 2 LowThresholdOnClientObjects : LowThresholdOnEvents : 10000000 MaxLogFileSize : 65536 MaxWaitOnClientObjects : MaxWaitOnEvents : 2000 MofSelfInstallDirectory : SettingID : Description ----------- This command sets the WMI logging level to 2. The command passes the proper ty to be set and the value (together considered a value pair) in the argume nt parameter. The parameter takes a hash table that is defined by the @{pro perty = value} construction. Theclass information that is returned reflects the new value. -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-wmiinstance -class win32_environment -argument @{Name="testvar";V ariableValue="testvalue";UserName="<SYSTEM>"} __GENUS : 2 __CLASS : Win32_Environment __SUPERCLASS : CIM_SystemResource __DYNASTY : CIM_ManagedSystemElement __RELPATH : Win32_Environment.Name="testvar",UserName="<SYSTEM>" __PROPERTY_COUNT : 8 __DERIVATION : {CIM_SystemResource, CIM_LogicalElement, CIM_ManagedSyst emElement} __SERVER : SYSTEM01 __NAMESPACE : root\cimv2 __PATH : \\SYSTEM01\root\cimv2:Win32_Environment.Name="testvar",U serName="<SYSTEM>" Caption : <SYSTEM>\testvar Description : <SYSTEM>\testvar InstallDate : Name : testvar Status : OK SystemVariable : True UserName : <SYSTEM> VariableValue : testvalue Description ----------- This command creates the testvar environment variable that has the value " testvalue". It does this by creating a new instance of the Win32_Environmen t WMI class. Note that this operation requires appropriate credentials and that you may need to restart Windows PowerShell to see the new environment variable. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Set-WMIInstance -class Win32_WMISetting -argument @{LoggingLevel=2} - computername system01, system02, system03 __GENUS : 2 __CLASS : Win32_WMISetting __SUPERCLASS : CIM_Setting __DYNASTY : CIM_Setting __RELPATH : Win32_WMISetting=@ __PROPERTY_COUNT : 27 __DERIVATION : {CIM_Setting} __SERVER : SYSTEM01 __NAMESPACE : root\cimv2 __PATH : \\SYSTEM01\root\cimv2:Win32_WMISetting=@ ASPScriptDefaultNamespace : \\root\cimv2 ASPScriptEnabled : False AutorecoverMofs : {%windir%\system32\wbem\cimwin32.mof, %win dir%\system32\wbem\ncprov.mof, %windir%\syst em32\wbem\wmipcima.mof, %windir%\system32\ wbem\secrcw32.mof...} AutoStartWin9X : BackupInterval : BackupLastTime : BuildVersion : 6001.18000 Caption : DatabaseDirectory : C:\Windows\system32\wbem\repository DatabaseMaxSize : Description : EnableAnonWin9xConnections : EnableEvents : False EnableStartupHeapPreallocation : False HighThresholdOnClientObjects : HighThresholdOnEvents : 20000000 InstallationDirectory : C:\Windows\system32\wbem LastStartupHeapPreallocation : LoggingDirectory : C:\Windows\system32\wbem\Logs\ LoggingLevel : 2 LowThresholdOnClientObjects : LowThresholdOnEvents : 10000000 MaxLogFileSize : 65536 MaxWaitOnClientObjects : MaxWaitOnEvents : 2000 MofSelfInstallDirectory : SettingID : ... Description ----------- This command sets the WMI logging level to 2. The command passes the proper ty to be set and the value (together considered a value pair) in the argume nt parameter. The parameter takes a hash table that is defined by the @{pro perty = value} construction. The returned class information reflects the ne w value. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113402 Get-WmiObject Invoke-WmiMethod Remove-WmiObject Get-WSManInstance Invoke-WSManAction New-WSManInstance Remove-WSManInstance Set-WSManInstance NAME Set-WSManInstance SYNOPSIS Modifies the management information that is related to a resource. SYNTAX Set-WSManInstance [-ApplicationName <string>] [-ComputerName <string>] [-Fr agment <string>] [-Port <int>] [-UseSSL] -ResourceURI <Uri> [[-SelectorSet] <hashtable>] [-Authentication <AuthenticationMechanism>] [-Credential <PSC redential>] [-Dialect <Uri>] [-FilePath <File>] [-SessionOption <hashtable> ] [-ValueSet <hashtable>] [<CommonParameters>] Set-WSManInstance [-ConnectionURI <Uri>] [-Fragment <string>] -ResourceURI <Uri> [[-SelectorSet] <hashtable>] [-Authentication <AuthenticationMechanis m>] [-Credential <PSCredential>] [-Dialect <Uri>] [-FilePath <File>] [-Sess ionOption <hashtable>] [-ValueSet <hashtable>] [<CommonParameters>] DESCRIPTION The Set-WSManInstance cmdlet modifies the management information that is re lated to a resource. This cmdlet uses the WinRM connection/transport layer to modify the informa tion. PARAMETERS -ApplicationName <string> Specifies the application name in the connection. The default value of the ApplicationName parameter is "WSMAN". The complete identifier for t he remote endpoint is in the following format: <transport>://<server>:<port>/ For example: http://server01:8080/WSMAN Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is desi gned to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hos ts Web Services for Management (WS-Management ) for efficiency. Required? false Position? named Default value wsman Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationMechanism> Specifies the authentication mechanism to be used at the server. Possib le values are: - Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - Default : Use the authentication method implemented by the WS-Managem ent protocol. This is the default. - Digest: Digest is a challenge-response scheme that uses a server-spec ified data string for the challenge. - Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates. - Negotiate: Negotiate is a challenge-response scheme that negotiates w ith the server or proxy to determine the scheme to use for authenticati on. For example, this parameter value allows negotiation to determine w hether the Kerberos protocol or NTLM is used. - CredSSP: Use Credential Security Service Provider (CredSSP) authentic ation, which allows the user to delegate credentials. This option is de signed for commands that run on one remote computer but collect data fr om or run additional commands on other remote computers. Caution: CredSSP delegates the user's credentials from the local comput er to a remote computer. This practice increases the security risk of t he remote operation. If the remote computer is compromised, when creden tials are passed to it, the credentials can be used to control the netw ork session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name must be used. You can pipe a v alue for this parameter to the cmdlet. Required? false Position? named Default value localhost Accept pipeline input? false Accept wildcard characters? false -ConnectionURI <Uri> Specifies the connection endpoint. The format of this string is: <Transport>://<Server>:<Port>/ The following string is a properly formatted value for this parameter: http://Server01:8080/WSMAN The URI must be fully qualified . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or "User@Domain.com". Or, enter a PSCredential object, s uch as one returned by the Get-Credential cmdlet. When you type a user name, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Dialect <Uri> Specifies the dialect to use in the filter predicate. This can be any d ialect that is supported by the remote service. The following aliases c an be used for the dialect URI: - WQL: http://schemas.microsoft.com/wbem/wsman/1/WQL - Selector: http://schemas.microsoft.com/wbem/wsman/1/wsman/SelectorFil ter - Association: http://schemas.dmtf.org/wbem/wsman/1/cimbinding/associat ionFilter Required? false Position? named Default value http://schemas.microsoft.com/wbem/wsman/1/ WQL Accept pipeline input? false Accept wildcard characters? false -FilePath <File> Specifies the path of a file that is used to update a management resour ce. You specify the management resource by using the ResourceURI parame ter and the SelectorSet parameter . For example, the following command uses the FilePath parameter: invoke-wsmanaction -action stopservice -resourceuri wmicimv2/Win32_Serv ice -SelectorSet @{Name="spooler"} -FilePath:c:\input.xml -authenticati on default This command calls the StopService method on the Spooler service by usi ng input from a file. The file, Input.xml, contains the following conte nt: <p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1 /wmi/root/cimv2/Win32_Service"/> Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Fragment <string> Specifies a section inside the instance that is to be updated or retrie ved for the specified operation. For example, to get the status of a sp ooler service, specify "-Fragment Status". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -OptionSet <hashtable> Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shel ls because they are service specific. Any number of options can be sp ecified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: -OptionSet @{a=1;b=2;c=3} Required? Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Port <int> Specifies the port to use when the client connects to the WinRM service . When the transport is HTTP, the default port is 80. When the transpor t is HTTPS, the default port is 443. When you use HTTPS as the transpor t, the value of the ComputerName parameter must match the server's cert ificate common name (CN). However, if the SkipCNCheck parameter is spec ified as part of the SessionOption parameter, then the certificate comm on name of the server does not have to match the host name of the serve r. The SkipCNCheck parameter should be used only for trusted machines. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ResourceURI <Uri> Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, suc h as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Log icalDisk http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSenso r Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SelectorSet <hashtable> Specifies a set of value pairs that are used to select particular manag ement resource instances. The SelectorSet parameter is used when more t han one instance of the resource exists. The value of the SelectorSet p arameter must be a hash table. The following example shows how to enter a value for this parameter: -SelectorSet @{Name="WinRM";ID="yyy"} Required? false Position? 2 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -SessionOption <hashtable> Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the New-WSManSessionOpt ion cmdlet. For more information about the options that are available, see New-WSManSessionOption. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseSSL [<SwitchParameter>] Specifies that the Secure Sockets Layer (SSL) protocol should be used t o establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is trans mitted over the network. The UseSSL parameter lets you specify the addi tional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter , the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ValueSet <hashtable> Specifies a hash table that helps modify a management resource. You spe cify the management resource by using the ResourceURI parameter and the SelectorSet parameter. The value of the ValueSet parameter must be a h ash table. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>set-wsmaninstance -resourceuri winrm/config/listener -selectorset @{a ddress="*";transport="https"} -valueset @{Enabled="false"} cfg : http://schemas.microsoft.com/wbem/wsman/1/config/li stener xsi : http://www.w3.org/2001/XMLSchema-instance lang : en-US Address : * Transport : HTTPS Port : 443 Hostname : Enabled : false URLPrefix : wsman CertificateThumbprint : ListeningOn : {127.0.0.1, 172.30.168.171, ::1, 2001:4898:0:fff:0: 5efe:172.30.168.171...} Description ----------- This command disables the https listener on the local computer. Important: The ValueSet parameter is case-sensitive when matching the prope rties specified. For example, using the above command. This fails: -ValueSet @{enabled="False"} This succeeds: -ValueSet @{Enabled="False"} -------------------------- EXAMPLE 2 -------------------------- C:\PS>set-wsmaninstance -resourceuri winrm/config -ValueSet @{MaxEnvelopeSi zekb = "200"} cfg : http://schemas.microsoft.com/wbem/wsman/1/config lang : en-US MaxEnvelopeSizekb : 200 MaxTimeoutms : 60000 MaxBatchItems : 32000 MaxProviderRequests : 4294967295 Client : Client Service : Service Winrs : Winrs Description ----------- This command sets the MaxEnvelopeSizekb value to 200 on the local computer. Important: The ValueSet parameter is case-sensitive when matching the prope rties specified. For example, using the above command. This fails: -ValueSet @{MaxEnvelopeSizeKB ="200"} This succeeds: -ValueSet @{MaxEnvelopeSizekb ="200"} -------------------------- EXAMPLE 3 -------------------------- C:\PS>set-wsmaninstance -resourceuri winrm/config/listener -computername SE RVER02 -selectorset @{address="*";transport="https"} -valueset @{Enabled="f alse"} cfg : http://schemas.microsoft.com/wbem/wsman/1/config/li stener xsi : http://www.w3.org/2001/XMLSchema-instance lang : en-US Address : * Transport : HTTPS Port : 443 Hostname : Enabled : false URLPrefix : wsman CertificateThumbprint : ListeningOn : {127.0.0.1, 172.30.168.172, ::1, 2001:4898:0:fff:0: 5efe:172.30.168.172...} Description ----------- This command disables the https listener on the remote computer SERVER02. Important: The ValueSet parameter is case-sensitive when matching the prope rties specified. For example, using the above command. This fails: -ValueSet @{enabled="False"} This succeeds: -ValueSet @{Enabled="False"} RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141458 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManQuickConfig Test-WSMan Set-WSManQuickConfig NAME Set-WSManQuickConfig SYNOPSIS Configures the local computer for remote management. SYNTAX Set-WSManQuickConfig [-UseSSL] [<CommonParameters>] DESCRIPTION The Set-WSManQuickConfig cmdlet configures the computer to receive Windows PowerShell remote commands that are sent by using the Web Services for Mana gement (WS-Management) technology. The cmdlet performs the following: 1. Checks whether the WinRM service is running. If the WinRM service is not running, the service is started. 2. Sets the WinRM service startup type to automatic. 3. Creates a listener to accept requests on any IP address. By default, the transport is HTTP. 4. Enables a firewall exception for WinRM traffic . To run this cmdlet in Windows Vista, Windows Server 2008, and later version s of Windows, you must start Windows PowerShell with the "Run as administra tor" option. PARAMETERS -UseSSL [<SwitchParameter>] Specifies that the Secure Sockets Layer (SSL) protocol should be used t o establish a connnection to the remote computer. By default, SSL is no t used. WS-Management encrypts all Windows PowerShell content transmitted over the network. The UseSSL parameter lets you specify that the additional protection of using HTTPS instead of HTTP should be used. If you specif y this parameter, but SSL is not available on the port used for the con nection, the command fails. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>Set-WSManQuickConfig Description ----------- This command sets the required configuration to enable remote management of the local computer. By default, this command creates a WS-Management liste ner on HTTP. -------------------------- EXAMPLE 2 -------------------------- C:\PS>Set-WSManQuickConfig -UseSSL Description ----------- The command sets the required configuration to enable remote management of the local computer. The UseSSL parameter makes the command create a WS-Mana gement listener on HTTPS. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=141463 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-PSRemoting Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-PSSession New-WSManInstance New-WSManSessionOption Test-WSMan Show-EventLog NAME Show-EventLog SYNOPSIS Displays the event logs of the local or a remote computer in Event Viewer. SYNTAX Show-EventLog [[-ComputerName] <string>] [<CommonParameters>] DESCRIPTION The Show-EventLog cmdlet opens Event Viewer on the local computer and displ ays in it all of the classic event logs on the local computer or a remote c omputer. To open Event Viewer on Windows Vista and later versions of Windows, the cu rrent user must be a member of the Administrators group on the local comput er. The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinE vent. PARAMETERS -ComputerName <string> Specifies a remote computer. Show-EventLog displays the event logs from the specified computer in Event Viewer on the local computer. The defa ult is the local computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qu alified domain name of a remote computer. This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Get-EventLog even if your computer is n ot configured to run remote commands. Required? false Position? 1 Default value . Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not generate any output. NOTES The Windows PowerShell command prompt returns as soon as Event Viewer o pens. You can work in the current session while Event Viewer is open. Because this cmdlet requires a user interface, it does not work on Serv er Core installations of Windows Server. -------------------------- EXAMPLE 1 -------------------------- C:\PS>show-eventlog Description ----------- This command opens Event Viewer and displays in it the classic event logs o n the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>show-eventlog -computername Server01 Description ----------- This command opens Event Viewer and displays in it the classic event logs o n the Server01 computer. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135257 Clear-EventLog Get-EventLog Limit-EventLog New-EventLog Remove-EventLog Write-EventLog Get-WinEvent Sort-Object NAME Sort-Object SYNOPSIS Sorts objects by property values. SYNTAX Sort-Object [[-Property] <Object[]>] [-CaseSensitive] [-Culture <string>] [ -Descending] [-InputObject <psobject>] [-Unique] [<CommonParameters>] DESCRIPTION The Sort-Object cmdlet sorts objects in ascending or descending order based on the values of properties of the object. You can specify a single property or multiple properties (for a multi-key s ort), and you can select a case-sensitive or case-insensitive sort. You can also direct Sort-Object to display only the objects with a unique value fo r a particular property. PARAMETERS -CaseSensitive [<SwitchParameter>] Indicates that the sort should be case sensitive. By default, sorting i s not case sensitive. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Culture <string> Specifies the cultural configuration to use when sorting. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Descending [<SwitchParameter>] Sorts the objects in descending order. The default is ascending order. The Descending parameter applies to all properties. To sort by some pro perties in ascending order and others in descending order, you must specify their property values by using a hash table. For details, see the examples. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be sorted. When you use the InputObject parameter to submit a collection of items, Sort-Object receives one object that represents the collection. Becaus e one object cannot be sorted, Sort-Object returns the entire collectio n unchanged. To sort objects, pipe them to Sort-Object. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Property <Object[]> Specifies the properties to use when sorting. Objects are sorted based on the values of these properties. Enter the names of the properties. W ildcards are permitted. If you specify multiple properties, the objects are first sorted by the first property. If more than one object has the same value for the fir st property, those objects are sorted by the second property. This proc ess continues until there are no more specified properties or no groups of objects. If you do not specify properties, the cmdlet sorts based on default pro perties for the object type. The value of the Property parameter can be a new calculated property. T o create a calculated, property, use a hash table. Valid keys are: -- Expression <string> or <script block> -- Ascending <Boolean> -- Descending <Boolean> Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? true -Unique [<SwitchParameter>] Eliminates duplicates and returns only the unique members of the collec tion. You can use this parameter instead of using the Get-Unique cmdlet . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe the objects to be sorted to Sort-Object. OUTPUTS System.Management.Automation.PSObject Sort-Object returns the sorted objects. NOTES Sort-Object sorts objects based on the properties that you specify or t he default sort properties for objects of that type. If an object does not have one of the specified properties, the propert y value for that object is interpreted by the cmdlet as NULL and is pla ced at the end of the sort order. When sorting objects, Sort-Object uses the Compare method for each prop erty. If a property does not implement IComparable, the cmdlet converts the property value to a string and uses the Compare method for System. String. The Sort-Object cmdlet sorts objects in ascending or descending order b ased on the values of properties of the object. If you sort on a property whose value is an enumeration, Sort-Object so rts the enumeration values in numeric order; it does not sort the enume ration member names. For example, if you sort services by status, servi ces with a status of "Stopped" appear before services with a status of "Running", because the value of Status is a ServiceControllerStatus enu meration, in which "Stopped" has a value of 1 and "Running" has a value of 4. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-childitem | sort-object Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 9/13/2005 4:24 PM 0 0 -a--- 9/6/2005 4:19 PM 12 a.csv -a--- 9/21/2005 3:49 PM 529 a.Ps -a--- 8/22/2005 4:14 PM 22 a.pl -a--- 9/27/2005 10:33 AM 24 a.txt -a--- 9/15/2005 10:31 AM 398 a.vbs -a--- 7/21/2005 12:39 PM 37066 a.xml -a--- 8/28/2005 11:30 PM 5412 a.xslt -a--- 10/25/2005 1:59 PM 125 AdamTravel.txt -a--- 7/21/2005 9:49 AM 59 add2Num.Ps -a--- 8/29/2005 5:42 PM 7111 add-content.xml -a--- 9/21/2005 12:46 PM 8771 aliens.Ps -a--- 8/10/2005 2:10 PM 798 array.xml -a--- 8/4/2004 5:00 AM 110 AUTORUN.INF -a--- 9/6/2005 4:20 PM 245 b.csv ... Description ----------- This command sorts the subdirectories and files in the current directory. B ecause no properties are specified, the files and directories are sorted in ascending alphabetical order by their default sort property, Name. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-childitem | sort-object -property length Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 12/3/2006 5:35 PM 2 pref.txt -a--- 9/6/2006 3:33 PM 15 count.txt -a--- 7/26/2006 10:01 AM 30 filenoext -a--- 8/18/2006 9:02 AM 52 temp.ps1 -a--- 8/18/2006 9:02 AM 52 temp.msh -a--- 9/6/2006 3:33 PM 56 fivewords.txt -a--- 7/26/2006 9:28 AM 80 date.csv -a--- 7/29/2006 7:15 PM 84 test2.txt -a--- 7/29/2006 7:15 PM 84 test.ps1 Description ----------- This command displays the files in the current directory in ascending order by file length. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-process | sort-object -property WS | select-object -last 5 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 1105 25 44236 18932 197 93.81 2032 iexplore 2526 66 37668 36836 221 393.27 868 svchost 974 19 22844 45928 371 88.39 3952 WINWORD 1371 22 42192 61872 323 75.75 1584 INFOPATH 2145 58 93088 70680 619 396.69 3908 OUTLOOK Description ----------- This command displays the five processes on the computer with the greatest memory use based on the size of their working sets. The command uses the Get-Process cmdlet to get a list of processes. It uses a pipeline operator (|) to send the results to the Sort-Object cmdlet, whi ch sorts the objects in working-set order. Another pipeline operator sends the results to the Select-Object, which dis plays only the last five items in the list. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-history | sort-object -descending Id CommandLine -- ----------- 51 get-history | sort -descending 50 get-history | sort -descending 49 get-history | sort -descending 48 get-history | sort -descending 47 get-history | sort -descending 46 get-history | sort -descending 45 get-history | sort -descending 44 cd $pshome 43 get-childitem | sort-object 42 gci *.txt Description ----------- This command sorts HistoryInfo objects using the Id property as the default key. -------------------------- EXAMPLE 5 -------------------------- C:\PS>C:\PS> get-service | sort-object -property ` @{Expression="Status";Descending=$true}, ` @{Expression="DisplayName";Descending=$false} Status Name DisplayName ------ ---- ----------- Running ALG Application Layer Gateway Service Running Ati HotKey Poller Ati HotKey Poller Running wuauserv Automatic Updates Running BITS Background Intelligent Transfer Ser... Running Client for NFS Client for NFS ... Stopped clr_optimizatio... .NET Runtime Optimization Service v... Stopped Alerter Alerter Stopped AppMgmt Application Management Stopped aspnet_state ASP.NET State Service Stopped ATI Smart ATI Smart Stopped ClipSrv ClipBook Description ----------- This command displays the services on the computer in descending Status ord er and ascending DisplayName order. The command uses the Get-Service cmdlet to get the services on the computer . It uses a pipeline operator (|) to send services to the Sort-Object cmdle t. To sort one property in ascending order and another property in descending order, the command uses a hash table for the value of the Property paramete r. The hash table uses an Expression key to specify the property name and a n Ascending or Descending key to specify the sort order. The resulting display, which sorts the Status values in descending order, l ists properties with a Status value of "Running" before those with a Status value of "Stopped". When sorted in ascending order, "Stopped" appears befo re "Running", because Status is an enumerated property in which the value o f "Stopped" (1) is less than the value of "Running" (4). -------------------------- EXAMPLE 6 -------------------------- C:\PS>get-childitem *.txt | sort-object -property @{Expression={$_.LastWrit eTime - $_.CreationTime}; Ascending=$false} | Format-Table LastWriteTime, C reationTime LastWriteTime CreationTime ------------- ------------ 2/21/2006 10:22:20 AM 10/3/2005 4:19:40 PM 2/27/2006 8:14:24 AM 2/23/2006 10:41:08 PM 2/24/2006 1:26:19 PM 2/23/2006 11:23:36 PM 1/5/2006 12:01:35 PM 1/5/2006 11:35:30 AM 2/24/2006 9:25:40 AM 2/24/2006 9:22:24 AM 2/24/2006 9:40:01 AM 2/24/2006 9:39:41 AM 2/21/2006 10:21:30 AM 2/21/2006 10:21:30 AM Description ----------- This command sorts text files in descending order by the time span between CreationTime and LastWriteTime. -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-content servers.txt localhost test01 server01 server02 localhost server01 C:\PS> get-content servers.txt | sort-object -unique localhost server01 server02 test01 Description ----------- These commands sort the names of servers in a text file. The second command uses the Sort-Object cmdlet with the Unique parameter to return a sorted l ist without duplicates. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113403 Group-Object Split-Path NAME Split-Path SYNOPSIS Returns the specified part of a path. SYNTAX Split-Path [-IsAbsolute] [-Path] <string[]> [-Credential <PSCredential>] [- LiteralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>] Split-Path [-Leaf] [-Path] <string[]> [-Credential <PSCredential>] [-Litera lPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>] Split-Path [-NoQualifier] [-Path] <string[]> [-Credential <PSCredential>] [ -LiteralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>] Split-Path [-Parent] [-Path] <string[]> [-Credential <PSCredential>] [-Lite ralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>] Split-Path [[-Qualifier]] [-Path] <string[]> [-Credential <PSCredential>] [ -LiteralPath <string[]>] [-Resolve] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Split-Path cmdlet returns only the specified part of a path, such as th e parent directory, a child directory, or a file name. It also can display the items that are referenced by the split path and tell whether the path i s relative or absolute. You can use this cmdlet to display or submit only a selected part of a path . PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PS Credential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -IsAbsolute [<SwitchParameter>] Returns TRUE if the path is absolute and FALSE if it is relative. An ab solute path has a length greater than zero and does not use a dot ( . ) to indicate the current path. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Leaf [<SwitchParameter>] Returns only the last item or container in the path. For example, in th e path "C:\Test\Logs\Pass1.log", it returns only "Pass1.log". Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -LiteralPath <string[]> Specifies the paths to be split. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildca rds. If the path includes escape characters, enclose it in single quota tion marks. Single quotation marks tell Windows PowerShell not to inter pret any characters as escape sequences. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -NoQualifier [<SwitchParameter>] Returns the path without the qualifier. For the FileSystem or registry providers, the qualifier is the drive of the provider path, such as C: or HKCU:. For example, in the path "C:\Test\Logs\Pass1.log", it return s only "\Test\Logs\Pass1.log". Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Parent [<SwitchParameter>] Returns only the parent containers of the item or of the container spec ified by the path. For example, in the path "C:\Test\Logs\Pass1.log", i t returns "C:\Test\Logs". The Parent parameter is the default split loc ation parameter. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies the paths to be split. Wildcards are permitted. If the path i ncludes spaces, enclose it in quotation marks. You can also pipe a path to Split-Path. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Qualifier [<SwitchParameter>] Returns only the qualifier of the specified path. For the FileSystem or registry providers, the qualifier is the drive of the provider path, s uch as C: or HKCU:. Required? false Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Resolve [<SwitchParameter>] Displays the items that are referenced by the resulting split path inst ead of displaying the path elements. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path to Split-Path. OUTPUTS System.String The Split-Path cmdlet returns text strings. When you use the Resolve pa rameter, Split-Path returns a string that describes the location of the items; it does not return objects that represent the items, such as a FileInfo or RegistryKey object. NOTES The split location parameters (Qualifier, Parent, Leaf, and NoQualifier ) are exclusive. You can use only one in each command. The cmdlets that contain the Path noun (the Path cmdlets) manipulate pa th names and return the names in a concise format that all Windows Powe rShell providers can interpret. They are designed for use in programs a nd scripts where you want to display all or part of a path name in a pa rticular format. Use them like you would use Dirname, Normpath, Realpat h, Join, or other path manipulators. You can use the Path cmdlets with several providers, including the File System, Registry, and Certificate providers. The Split-Path cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type "Get-PS Provider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>split-path "HKCU:\Software\Microsoft" -qualifier HKCU: Description ----------- This command returns only the qualifier (the drive) of the path. -------------------------- EXAMPLE 2 -------------------------- C:\PS>split-path "C:\Test\Logs\*.log" -leaf -resolve Pass1.log Pass2.log ... Description ----------- This command displays the files that are referenced by the split path. Beca use this path is split to the last item (the "leaf"), only the file names o f the paths are displayed. The Resolve parameter tells Split-Path to display the items that the split path references, instead of displaying the split path. Like all Split-Path commands, this command returns strings. It does not ret urn FileInfo Objects representing the files. -------------------------- EXAMPLE 3 -------------------------- C:\PS>split-path "C:\WINDOWS\system32\WindowsPowerShell\V1.0\about_*.txt" C:\WINDOWS\system32\WindowsPowerShell\V1.0 Description ----------- This command returns only the parent containers of the path. Because it doe s not include any parameters to specify the split, Split-Path uses the spli t location default, which is Parent. -------------------------- EXAMPLE 4 -------------------------- C:\PS>split-path ".\My Pictures\*.jpg" -IsAbsolute False Description ----------- This command determines whether the path is relative or absolute. In this c ase, because the path is relative to the current directory, which is repres ented by a dot (.), it returns FALSE ($false). -------------------------- EXAMPLE 5 -------------------------- C:\PS>set-location (split-path $profile) PS C:\Documents and Settings\juneb\My Documents\WindowsPowerShell> Description ----------- This command changes your location to the directory that contains the Windo ws PowerShell profile. The command in parentheses uses the Split-Path cmdlet to return only the pa rent of the path stored in the built-in $Profile variable. (The Parent para meter is the default split location parameter, so you can omit it from the command.) The parentheses direct Windows PowerShell to execute the command first. This is a handy way to navigate to a directory with a long path name . -------------------------- EXAMPLE 6 -------------------------- C:\PS>'C:\Documents and Settings\User01\My Documents\My Pictures' | split-p ath C:\Documents and Settings\User01\My Documents Description ----------- This command uses a pipeline operator (|) to send a path to the Split-Path cmdlet. The path is enclosed in quotation marks to indicate that it is a si ngle token. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113404 about_Providers Test-Path Convert-Path Resolve-Path Join-Path Start-Job NAME Start-Job SYNOPSIS Starts a Windows PowerShell background job. SYNTAX Start-Job [-ScriptBlock] <scriptblock> [[-InitializationScript] <scriptbloc k>] [-ArgumentList <Object[]>] [-Authentication {Default | Basic | Negotiat e | NegotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-Crede ntial <PSCredential>] [-InputObject <psobject>] [-Name <string>] [-RunAs32] [<CommonParameters>] Start-Job [[-FilePath] <string>] [[-InitializationScript] <scriptblock>] [- ArgumentList <Object[]>] [-Authentication {Default | Basic | Negotiate | Ne gotiateWithImplicitCredential | Credssp | Digest | Kerberos}] [-Credential <PSCredential>] [-InputObject <psobject>] [-Name <string>] [-RunAs32] [ monParameters>] DESCRIPTION The Start-Job cmdlet starts a Windows PowerShell background job on the loca l computer. A Windows PowerShell background job runs a command "in the background" with out interacting with the current session. When you start a background job, a job object is returned immediately, even if the job takes an extended tim e to complete. You can continue to work in the session without interruption while the job runs. The job object contains useful information about the job, but it does not c ontain the job results. When the job completes, use the Receive-Job cmdlet to get the results of the job. For more information about background jobs, see about_Jobs. To run a background job on a remote computer, use the AsJob parameter that is available on many cmdlets, or use the Invoke-Command cmdlet to run a Sta rt-Job command on the remote computer. For more information, see about_Rem ote_Jobs. PARAMETERS -ArgumentList <Object[]> Specifies the arguments (parameter values) for the script that is speci fied by the FilePath parameter. Because all of the values that follow the ArgumentList parameter name a re interpreted as being values of ArgumentList, the ArgumentList parame ter should be the last parameter in the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationMechanism> Specifies the mechanism that is used to authenticate the user's credent ials. Valid values are Default, Basic, Credssp, Digest, Kerberos, Neg otiate, and NegotiateWithImplicitCredential. The default value is Defa ult. CredSSP authentication is available only in Windows Vista, Windows Serv er 2008, and later versions of Windows. For information about the values of this parameter, see the description of the System.Management.Automation.Runspaces.AuthenticationMechanism enumeration in MSDN. CAUTION: Credential Security Service Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the r emote computer is compromised, the credentials that are passed to it ca n be used to control the network session. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one from the Get-Credential cmdlet. Required? false Position? named Default value Current user Accept pipeline input? false Accept wildcard characters? false -FilePath <string> Runs the specified local script as a background job. Enter the path and file name of the script or pipe a script path to Start-Job. The script must reside on the local computer or in a directory that the local com puter can access. When you use this parameter, Windows PowerShell converts the contents o f the specified script file to a script block and runs the script block as a background job. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -InitializationScript <scriptblock> Specifies commands that run before the job starts. Enclose the commands in braces ( { } ) to create a script block. Use this parameter to prepare the session in which the job runs. For ex ample, you can use it to add functions, snap-ins, and modules to the se ssion. Required? false Position? 2 Default value None Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies input to the command. Enter a variable that contains the obje cts, or type a command or expression that generates the objects. In the value of the ScriptBlock parameter, use the $input automatic var iable to represent the input objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string> Specifies a friendly name for the new job. You can use the name to iden tify the job to other job cmdlets, such as Stop-Job. The default friendly name is Job#, where "#" is an ordinal number that is incremented for each job. Required? false Position? named Default value Job<number> Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -RunAs32 [<SwitchParameter>] Runs the job in a 32-bit process. Use this parameter to force the job to run in a 32-bit process on a 64- bit operating system. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -ScriptBlock <scriptblock> Specifies the commands to run in the background job. Enclose the comman ds in braces ( { } ) to create a script block. This parameter is requir ed. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a file path to Start-Job. OUTPUTS System.Management.Automation.RemotingJob Start-Job returns an object that represents the job that it started. NOTES To run in the background, Start-Job runs in its own session within the current session. When you use the Invoke-Command cmdlet to run a Start- Job command in a session on a remote computer, Start-Job runs in a sess ion within the remote session. -------------------------- EXAMPLE 1 -------------------------- C:\PS>start-job -scriptblock {get-process} C:\PS> start-job -command "get-process" Id Name State HasMoreData Location Command --- ---- ----- ----------- -------- ------- 1 Job1 Running True localhost get-process Description ----------- This command starts a background job that runs a Get-Process command. The c ommand returns a job object with information about the job. The command pro mpt returns immediately so that you can work in the session while the job r uns in the background. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$jobWRM = invoke-command -computerName (get-content servers.txt) -scr iptblock {get-service winrm} -jobname WinRM -throttlelimit 16 -AsJob Description ----------- This command uses the Invoke-Command cmdlet and its AsJob parameter to star t a background job that runs a "get-service winrm" command on numerous comp uters. Because the command is running on a server with substantial network traffic, the command uses the ThrottleLimit parameter of Invoke-Command to limit the number of concurrent commands to 16. The command uses the ComputerName parameter to specify the computers on whi ch the job runs. The value of the ComputerName parameter is a Get-Content c ommand that gets the text in the Servers.txt file, a file of computer names in a domain. The command uses the ScriptBlock parameter to specify the command and the J obName parameter to specify a friendly name for the job. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$j = start-job -scriptblock {get-eventlog -log system} -credential do main01\user01 C:\PS> $j | format-list -property * HasMoreData : True StatusMessage : Location : localhost Command : get-eventlog -log system JobStateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : 2d9d775f-63e0-4d48-b4bc-c05d0e177f34 Id : 1 Name : Job1 ChildJobs : {Job2} Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} StateChanged : C:\PS> $j.JobStateInfo.state Completed C:\PS> $results = receive-job -job $j C:\PS> $results Index Time Type Source EventID Message ----- ---- ---- ------ ------- ------- 84366 Feb 18 19:20 Information Service Control M... 7036 The descripti on... 84365 Feb 18 19:16 Information Service Control M... 7036 The descripti on... 84364 Feb 18 19:10 Information Service Control M... 7036 The descripti on... ... Description ----------- These commands manage a background job that gets all of the events from the System log in Event Viewer. The job runs on the local computer. The first command uses the Start-Job cmdlet to start the job. It uses the C redential parameter to specify the user account of a user who has permissio n to run the job on the computer. Then it saves the job object that Start-J ob returns in the $j variable. At this point, you can resume your other work while the job completes. The second command uses a pipeline operator (|) to pass the job object in $ j to the Format-List cmdlet. The Format-List command uses the Property para meter with a value of all (*) to display all of the properties of the job o bject in a list. The third command displays the value of the JobStateInfo property. This con tains the status of the job. The fourth command uses the Receive-Job cmdlet to get the results of the jo b. It stores the results in the $results variable. The final command displays the contents of the $results variable. -------------------------- EXAMPLE 4 -------------------------- C:\PS>start-job -filepath c:\scripts\sample.ps1 Description ----------- This command runs the Sample.ps1 script as a background job. -------------------------- EXAMPLE 5 -------------------------- C:\PS>start-job -name WinRm -scriptblock {get-process winrm} Description ----------- This command runs a background job that gets the WinRM process on the local computer. The command uses the ScriptBlock parameter to specify the comman d that runs in the background job. It uses the Name parameter to specify a friendly name for the new job. -------------------------- EXAMPLE 6 -------------------------- C:\PS>start-job -name GetMappingFiles -initializationScript {import-module MapFunctions} -scriptblock {Get-Map -name * | set-content D:\Maps.tif} -run As32 Description ----------- This command starts a job that collects a large amount of data and saves it in a .tif file. The command uses the InitializationScript parameter to run a script block that imports a required module. It also uses the RunAs32 pa rameter to run the job in a 32-bit process even if the computer has a 64-bi t operating system. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113405 about_Jobs about_Job_Details about_Remote_Jobs Get-Job Receive-Job Wait-Job Stop-Job Remove-Job Invoke-Command Start-Process NAME Start-Process SYNOPSIS Starts one or more processes on the local computer. SYNTAX Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-Credentia l <PSCredential>] [-LoadUserProfile] [-NoNewWindow] [-PassThru] [-RedirectS tandardError <string>] [-RedirectStandardInput <string>] [-RedirectStandard Output <string>] [-UseNewEnvironment] [-Wait] [-WorkingDirectory <string>] [<CommonParameters>] Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-PassThru] [-Verb <string>] [-Wait] [-WindowStyle {Normal | Hidden | Minimized | Maxi mized}] [-WorkingDirectory <string>] [<CommonParameters>] DESCRIPTION Starts one or more processes on the local computer. To specify the program that runs in the process, enter an executable file or script file, or a fi le that can be opened by using a program on the computer. If you specify a non-executable file, Start-Process starts the program that is associated wi th the file, much like the Invoke-Item cmdlet. You can use the parameters of Start-Process to specify options, such as loa ding a user profile, starting the process in a new window, or using alterna te credentials. PARAMETERS -ArgumentList <string[]> Specifies parameters or parameter values to use when starting the proce ss. The parameter name ("Arguments") is optional. Required? false Position? 2 Default value None Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Ty pe a user-name, such as "User01" or "Domain01\User01", or enter a PSCre dential object, such as one from the Get-Credential cmdlet. By default, the cmdlet uses the credentials of the current user. Required? false Position? named Default value Current user. Accept pipeline input? false Accept wildcard characters? false -FilePath <string> Specifies the path (optional) and file name of the program that runs in the process. Enter the name of an executable file or of a document, su ch as a .txt or .doc file, that is associated with a program on the com puter. This parameter is required. If you specify only a file name, use the WorkingDirectory parameter to specify the path. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -LoadUserProfile [<SwitchParameter>] Loads the Windows user profile stored in the HKEY_USERS registry key fo r the current user. The default value is FALSE. This parameter does not affect the Windows PowerShell profiles. (See ab out_Profiles.) Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -NoNewWindow [<SwitchParameter>] Prevents the process from running in a new window. By default, the proc ess runs in a new window. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns a process object for each process that the cmdlet started. By d efault, this cmdlet does not generate any output. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -RedirectStandardError <string> Sends any errors generated by the process to a file that you specify. E nter the path and file name. By default, the errors are displayed in th e console. Required? false Position? named Default value Errors are displayed in the console Accept pipeline input? false Accept wildcard characters? false -RedirectStandardInput <string> Reads input from the specified file. Enter the path and file name of th e input file. By default, the process gets its input from the keyboard. Required? false Position? named Default value Keyboard Accept pipeline input? false Accept wildcard characters? false -RedirectStandardOutput <string> Sends the output generated by the process to a file that you specify. E nter the path and file name. By default, the output is displayed in the console. Required? false Position? named Default value FALSE Accept pipeline input? false Accept wildcard characters? false -UseNewEnvironment [<SwitchParameter>] Use new environment variables specified for the process. By default, th e started process runs with the environment variables specified for the computer and user. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Verb <string> Specifies a verb to be used when starting the process, such as Edit, Op en, or Print. Each file type has a set of verbs that you can use. To find the verbs t hat can be used with the process, use the Verbs property of the object. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Wait [<SwitchParameter>] Waits for the specified process to complete before accepting more input . This parameter suppresses the command prompt or retains the window un til the process completes. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -WindowStyle <ProcessWindowStyle> Specifies the state of the windows used for the process. Valid values a re Normal, Hidden, Minimized, and Maximized. The default value is Norma l. Required? false Position? named Default value Normal Accept pipeline input? false Accept wildcard characters? false -WorkingDirectory <string> Specifies the location of the executable file or document that runs in the process. The default is the current directory. Required? false Position? named Default value Current directory Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to Start-Process. OUTPUTS None or System.Diagnostics.Process When you use the PassThru parameter, Start-Process generates a System.D iagnostics.Process. Otherwise, this cmdlet does not return any output. NOTES This cmdlet is implemented by using the Start method of the System.Diag nostics,Process class. For more information about this method, see "Pro cess.Start Method" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=143602. -------------------------- EXAMPLE 1 -------------------------- C:\PS>start-process sort.exe Description ----------- This command starts a process that uses the Sort.exe file in the current di rectory. The command uses all of the default values, including the default window style, working directory, and credentials. -------------------------- EXAMPLE 2 -------------------------- C:\PS>start-process myfile.txt -workingdirectory "C:\PS-Test" -verb Print Description ----------- This command starts a process that prints the C:\PS-Test\MyFile.txt file. -------------------------- EXAMPLE 3 -------------------------- C:\PS>start-process Sort.exe -RedirectStandardInput Testsort.txt -RedirectS tandardOutput Sorted.txt -RedirectStandardError SortError.txt -UseNewEnviro nment Description ----------- This command starts a process that sorts items in the Testsort.txt file and returns the sorted items in the Sorted.txt files. Any errors are written t o the SortError.txt file. The UseNewEnvironment parameter specifies that the process runs with its ow n environment variables. -------------------------- EXAMPLE 4 -------------------------- C:\PS>start-process notepad -wait -windowstyle Maximized Description ----------- This command starts the Notepad process. It maximizes the window and retain s the window until the process completes. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135261 Start-Service Get-Process Stop-Process Wait-Process Debug-Process Start-Service NAME Start-Service SYNOPSIS Starts one or more stopped services. SYNTAX Start-Service [-Name] <string[]> [-Exclude <string[]>] [-Include <string[]> ] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Start-Service -DisplayName <string[]> [-Exclude <string[]>] [-Include <stri ng[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Start-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [- Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Start-Service cmdlet sends a start message to the Windows Service Contr oller for each of the specified services. If a service is already running, the message is ignored without error. You can specify the services by their service names or display names, or you can use the InputObject parameter t o supply a service object representing the services that you want to start. PARAMETERS -DisplayName <string[]> Specifies the display names of the services to be started. Wildcards ar e permitted. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Starts only the specified services. The value of this parameter qualifi es the Name parameter. Enter a name element or pattern, such as "s*". W ildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ServiceController[]> Specifies ServiceController objects representing the services to be sta rted. Enter a variable that contains the objects, or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the service names for the service to be started. The parameter name is optional. You can use "-Name" or its alias, "-Ser viceName", or you can omit the parameter name. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the service. By default, this cmdlet doe s not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.ServiceProcess.ServiceController, System.String You can pipe objects that represent the services or strings that contai n the service names to Start-Service. OUTPUTS None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Start-Service generates a System.S erviceProcess.ServiceController object representing the service. Otherw ise, this cmdlet does not generate any output. NOTES You can also refer to Start-Service by its built-in alias, "sasv". For more information, see about_Aliases. Start-Service can control services only when the current user has permi ssion to do so. If a command does not work correctly, you might not hav e the required permissions. To find the service names and display names of the services on your sys tem, type "get-service". The service names appear in the Name column, a nd the display names appear in the DisplayName column. You can start only the services that have a start type of "Manual" or " Automatic". You cannot start the services with a start type of "Disable d". If a Start-Service command fails with the message "Cannot start ser vice <service-name> on computer," use a Get-WmiObject command to find t he start type of the service and, if necessary, use a Set-Service comma nd to change the start type of the service. Some services, such as Performance Logs and Alerts (SysmonLog) stop aut omatically if they have no work to do. When Windows PowerShell starts a service that stops itself almost immediately, it displays the followin g message: "Service <display-name> start failed." -------------------------- EXAMPLE 1 -------------------------- C:\PS>start-service -name eventlog Description ----------- This command starts the EventLog service on the local computer. It uses the Name parameter to identify the service by its service name. -------------------------- EXAMPLE 2 -------------------------- C:\PS>start-service -displayname *remote* -whatif Description ----------- This command tells what would happen if you started the services with a dis play name that includes "remote". It uses the DisplayName parameter to spec ify the services by their display name instead of by their service name. An d, it uses the WhatIf parameter to tell what would happen if the command we re executed instead of executing the command. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$s = get-service wmi C:\PS>start-service -InputObject $s -passthru | format-list >> services.txt Description ----------- These commands start the Windows Management Instrumentation (WMI) service o n the computer and add a record of the action to the services.txt file. The first command uses the Get-Service cmdlet to get an object representing th e WMI service and store it in the $s variable. The second command uses the Start-Service cmdlet to start the WMI service. It identifies the service by using the InputObject parameter to pass the $s variable containing the WMI service object to Start-Service. Then, it uses the PassThru parameter to create an object that represents the starting of the service. Without this parameter, Start-Service does not create any out put. The pipeline operator (|) passes the object that Start-Service creates to t he Format-List cmdlet, which formats the object as a list of its properties . The append redirection operator (>>) redirects the output to the services .txt file, where it is added to the end of the existing file. -------------------------- EXAMPLE 4 -------------------------- C:\PS># start-service Description ----------- This series of commands shows how to start a service when the start type of the service is "Disabled". The first command, which uses the Start-Service cmdlet to start the Telnet service (tlntsvr), fails. C:\PS>start-service tlntsvr Start-Service : Service 'Telnet (TlntSvr)' cannot be started due to the following error: Cannot start service TlntSvr on computer '.'. At line:1 char:14 + start-service < tlntsvr The second command uses the Get-WmiObject cmdlet to get the Tlntsvr service . This command retrieves an object with the start type property in the Star tMode field. The resulting display reveals that the start type of the Tlnts vr service is "Disabled". C:\PS> get-wmiobject win32_service | where-object {$_.Name -eq "tlntsvr"} ExitCode : 0 Name : TlntSvr ProcessId : 0 StartMode : Disabled State : Stopped Status : OK The next command uses the Set-Service cmdlet to change the start type of th e Tlntsvr service to "Manual". C:\PS> set-service tlntsvr -startuptype manual Now, we can resubmit the Start-Service command. This time, the command succ eeds. C:\PS> start-service tlntsvr To verify that the command succeeded, use Get-Service. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113406 Get-Service Suspend-Service Stop-Service Restart-Service Resume-Service Set-Service New-Service Start-Sleep NAME Start-Sleep SYNOPSIS Suspends the activity in a script or session for the specified period of ti me. SYNTAX Start-Sleep -Milliseconds <int> [<CommonParameters>] Start-Sleep [-Seconds] <int> [<CommonParameters>] DESCRIPTION The Start-Sleep cmdlet suspends the activity in a script or session for the specified period of time. You can use it for many tasks, such as waiting f or an operation to complete or pausing before repeating an operation. PARAMETERS -Milliseconds <int> Specifies how long the resource sleeps in milliseconds. The parameter c an be abbreviated as "-m". Required? true Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Seconds <int> Specifies how long the resource sleeps in seconds. You can omit the par ameter name ("Seconds"), or you can abbreviate it as "-s". Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Int32 You can pipe the number of seconds to Start-Sleep. OUTPUTS None This cmdlet does not return any output. NOTES You can also refer to Start-Sleep by its built-in alias, "sleep". For m ore information, see about_Aliases. -------------------------- EXAMPLE 1 -------------------------- C:\PS>Start-Sleep -s 15 Description ----------- This command makes all commands in the session sleep for 15 seconds. -------------------------- EXAMPLE 2 -------------------------- C:\PS>Start-Sleep -m 500 Description ----------- This command makes all the commands in the session sleep for one-half of a second (500 milliseconds). RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113407 Start-Transaction NAME Start-Transaction SYNOPSIS Starts a transaction. SYNTAX Start-Transaction [-Independent] [-RollbackPreference {Error | TerminatingE rror | Never}] [-Timeout <int>] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Start-Transaction cmdlet starts a transaction, which is a series of com mands that are managed as a unit. A transaction can be completed ("committe d"), or it can be completely undone ("rolled back") so that any data change d by the transaction is restored to its original state. Because the command s in a transaction are managed as a unit, either all commands are committed or all commands are rolled back. By default, transactions are rolled back automatically if any command in th e transaction generates an error, but you can use the RollbackPreference pa rameter to change this behavior. The cmdlets used in a transaction must be designed to support transactions. Cmdlets that support transactions have a UseTransaction parameter. To perf orm transactions in a provider, the provider must support transactions. The Windows PowerShell Registry provider in Windows Vista and later versions o f Windows supports transactions. You can also use the Microsoft.PowerShell. Commands.Management.TransactedString class to include expressions in transa ctions on any version of Windows that supports Windows PowerShell. Other Wi ndows PowerShell providers can also support transactions. Only one transaction can be active at a time. If you start a new, independe nt transaction while a transaction is in progress (neither completed nor un done), the new transaction becomes the active transaction, and you must com mit or roll back the new transaction before making any changes to the origi nal transaction. The Start-Transaction cmdlet is one of a set of cmdlets that support the tr ansactions feature in Windows PowerShell. For more information, see about_T ransactions. PARAMETERS -Independent [<SwitchParameter>] Starts a transaction that is independent of any transactions in progres s. By default, if you use Start-Transaction while another transaction i s in progress, a new subscriber is added to the transaction in progress . This parameter has an effect only when a transaction is already in pr ogress in the session. By default, if you use Start-Transaction while a transaction is in prog ress, the existing transaction object is reused and the subscriber coun t is incremented. The effect is much like joining the original transact ion. An Undo-Transaction command rolls back the entire the transaction. To complete the transaction, you must enter a Complete-Transaction com mand for each subscriber. Because most transactions that are in progres s at the same time are related, the default is sufficient for most uses . If you use the Independent parameter, a new transaction is created that can be completed or undone without affecting the original transaction. However, because only one transaction can be active at a time, you mus t complete or roll back the new transaction before resuming work on the original transaction. Required? false Position? named Default value Reuse the original transaction object. Accept pipeline input? false Accept wildcard characters? false -RollbackPreference <RollbackSeverity> Specifies the conditions under which a transaction is automatically rol led back. The default value is "Error". Valid values are: -- Error: The transaction is rolled back automatically if a terminatin g or non-terminating error occurs. "Error" is the default. -- Terminating error: The transaction is rolled back automatically if a terminating error occurs. -- Never: The transaction is never rolled back automatically. Required? false Position? named Default value Error Accept pipeline input? false Accept wildcard characters? false -Timeout <int> Specifies the maximum time, in minutes, that the transaction is active. When the time-out expires, the transaction is automatically rolled bac k. By default, there is no time-out for transactions that are started at t he command line. When transactions are started by a script, the default time-out is 30 minutes. Required? false Position? named Default value No timeout (infinite) Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>cd hkcu:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item MyCompany -UseTransaction PS HKCU:\software> new-itemproperty MyCompany -name MyKey -value 123 -UseTr ansaction PS HKCU:\software> undo-transaction Description ----------- These commands start and then roll back a transaction. Because the transact ion is rolled back, no changes are made to the registry. -------------------------- EXAMPLE 2 -------------------------- C:\PS>cd hkcu:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item MyCompany -UseTransaction PS HKCU:\software> new-itemproperty MyCompany -name MyKey -value 123 -UseTr ansaction PS HKCU:\software> complete-transaction Description ----------- These commands start and then complete a transaction. No changes are made t o the registry until the Complete-Transaction command is used. -------------------------- EXAMPLE 3 -------------------------- C:\PS>cd HKCU:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item -path NoPath -name MyCompany -UseTransaction PS HKCU:\software> new-item -path . -name MyCompany -UseTransaction PS HKCU:\software> start-transaction -RollbackPreference never PS HKCU:\software> new-item -path NoPath -name MyCompany -UseTransaction PS HKCU:\software> new-item -path . -name MyCompany -UseTransaction # Start-Transaction (-rollbackpreference error) PS HKCU:\software> start-transaction PS HKCU:\software> new-item -path NoPath -Name MyCompany -UseTransaction New-Item : The registry key at the specified path does not exist. At line:1 char:9 + new-item < -path NoPath -Name MyCompany -UseTransaction PS HKCU:\software> new-item -path . -name MyCompany -UseTransaction New-Item : Cannot use transaction. The transaction has been rolled back or has timed out. At line:1 char:9 + new-item < -path . -name MyCompany -UseTransaction # Start-Transaction (-rollbackpreference never) PS HKCU:\software> start-transaction -RollbackPreference never PS HKCU:\software> new-item -path NoPath -name MyCompany -UseTransaction New-Item : The registry key at the specified path does not exist. At line:1 char:9 + new-item < -path NoPath -name MyCompany -UseTransaction PS HKCU:\software> new-item -path . -name MyCompany -UseTransaction Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 0 0 MyCompany {} PS HKCU:\Software> complete-transaction # Succeeds Description ----------- This example demonstrates the effect of changing the RollbackPreference par ameter value. In the first set of commands, the Start-Transaction command does not use th e RollbackPreference parameter. As a result, the default value ("Error") is used. When an error occurs in a transaction command (the specified path do es not exist), the transaction is automatically rolled back. In the second set of commands, the Start-Transaction command uses the Rollb ackPreference parameter with a value of "Never". As a result, when an error occurs in a transaction command, the transaction is still active and can b e completed successfully. Because most transactions must be performed without error, the default valu e of the RollbackPreference parameter is typically preferred. -------------------------- EXAMPLE 4 -------------------------- C:\PS>cd HKCU:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item MyCompany -UseTransaction PS HKCU:\software> start-transaction PS HKCU:\software> get-transaction PS HKCU:\software> new-item MyCompany2 -UseTransaction PS HKCU:\software> complete-transaction PS HKCU:\software> complete-transaction PS HKCU:\Software> Get-Transaction RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 2 Active Description ----------- This example shows the effect of using the Start-Transaction command while a transaction is in progress. The effect is much like joining the transacti on in progress. Although this is a simplified command, this scenario commonly occurs when t he transaction involves running a script that includes a complete transacti on. The first Start-Transaction command starts the transaction. The first New-I tem command is part of the transaction. The second Start-Transaction command adds a new subscriber to the transacti on. The Get-Transaction command now returns a transaction with a subscriber count of 2. The second New-Item command is part of the same transaction. No changes are made to the registry until the entire transaction is complet ed. To complete the transaction, you must enter two Complete-Transaction co mmands, one for each subscriber. If you were to roll back the transaction a t any point, the entire transaction would be rolled back for both subscribe rs. -------------------------- EXAMPLE 5 -------------------------- C:\PS>cd HKCU:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item MyCompany -UseTransaction PS HKCU:\software> start-transaction -independent PS HKCU:\software> get-transaction PS HKCU:\software> undo-transaction PS HKCU:\software> new-itemproperty -path MyCompany -name MyKey -value 123 -UseTransaction PS HKCU:\software> complete-transaction PS HKCU:\software> dir my* PS HKCU:\Software> get-transaction RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active PS HKCU:\software> undo-transaction PS HKCU:\software> new-itemproperty -path MyCompany -name MyKey -value 123 -UseTransaction MyKey ----- 123 PS HKCU:\software> complete-transaction PS HKCU:\software> dir my* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 0 1 MyCompany {MyKey} Description ----------- This example shows the effect of using the Independent parameter of Start-T ransaction to start a transaction while another transaction is in progress. In this case, the new transaction is rolled back without affecting the ori ginal transaction. Although the transactions are logically independent, because only one trans action can be active at a time, you must roll back or commit the newest tra nsaction before resuming work on the original transaction. The first set of commands starts a transaction. The New-Item command is par t of the first transaction. In the second set of commands, the Start-Transaction command uses the Indep endent parameter. The Get-Transaction command that follows shows the transa ction object for the active transaction (the newest one). The subscriber co unt is equal to 1, showing that the transactions are unrelated. When the active transaction is rolled back by using an Undo-Transaction com mand, the original transaction becomes active again. The New-ItemProperty command, which is part of the original transaction, co mpletes without error, and the original transaction can be completed by usi ng the Complete-Transaction command. As a result, the registry is changed. -------------------------- EXAMPLE 6 -------------------------- C:\PS>cd hkcu:\software PS HKCU:\software> start-transaction PS HKCU:\software> new-item MyCompany1 -UseTransaction PS HKCU:\software> new-item MyCompany2 PS HKCU:\software> new-item MyCompany3 -UseTransaction PS HKCU:\software> dir my* PS HKCU:\software> complete-transaction PS HKCU:\software> dir my* PS HKCU:\Software> dir my* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 0 0 MyCompany2 {} PS HKCU:\Software> complete-transaction PS HKCU:\Software> dir my* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 0 0 MyCompany1 {} 0 0 MyCompany2 {} 0 0 MyCompany3 {} Description ----------- This example demonstrates that commands that are submitted while a transact ion is in progress can be included in the transaction or not included. Only commands that use the UseTransaction parameter are part of the transaction . The first and third New-Item commands use the UseTransaction parameter. The se commands are part of the transaction. Because the second New-Item comman d does not use the UseTransaction parameter, it is not part of the transact ion. The first "dir" command shows the effect. The second New-Item command is co mpleted immediately, but the first and third New-Item commands are not effe ctive until the transaction is committed. The Complete-Transaction command commits the transaction. As a result, the second "dir" command shows that all of the new items are added to the regis try. -------------------------- EXAMPLE 7 -------------------------- C:\PS>start-transaction -timeout 2 # Wait two minutes... C:\PS> get-transaction C:\PS> new-item HKCU:\Software\MyCompany -UseTransaction C:\PS> start-transaction -timeout 2 # Wait two minutes... C:\PS>> get-transaction RollbackPreference SubscriberCount Status ------------------ --------------- ----------- Error 1 RolledBack C:\PS> new-item HKCU:\Software\MyCompany -UseTransaction New-Item : Cannot use transaction. The transaction has been rolled back or has timed out. At line:1 char:9 + new-item < MyCompany -UseTransaction Description ----------- This command uses the Timeout parameter of Start-Transaction to start a tra nsaction that must be completed within two minutes. If the transaction is n ot complete when the timeout expires, it is rolled back automatically. When the timeout expires, you are not notified, but the Status property of the transaction object is set to RolledBack and commands that use the UseTr ansaction parameter fail. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135262 about_Transactions Get-Transaction Complete-Transaction Undo-Transaction Use-Transaction Start-Transcript NAME Start-Transcript SYNOPSIS Creates a record of all or part of a Windows PowerShell session in a text f ile. SYNTAX Start-Transcript [[-Path] <string>] [-Append] [-Force] [-NoClobber] [-Confi rm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Start-Transcript cmdlet creates a record of all or part of a Windows Po werShell session in a text file. The transcript includes all command that t he user types and all output that appears on the console. PARAMETERS -Append [<SwitchParameter>] Adds the new transcript to the end of an existing file. Use the Path pa rameter to specify the file. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to append the transcript to an existing read-only fil e. When used on a read-only file, the cmdlet changes the file permissio n to read-write. Even using the Force parameter, the cmdlet cannot over ride security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -NoClobber [<SwitchParameter>] Will not overwrite (replace the contents) of an existing file. By defau lt, if a transcript file exists in the specified path, Start-Transcript overwrites the file without warning. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Path <string> Specifies a location for the transcript file. Enter a path to a .txt fi le. Wildcards are not permitted. If you do not specify a path, Start-Transcript uses the path in the val ue of the $Transcript global variable. If you have not created this var iable, Start-Transcript stores the transcripts in the $Home\My Document s directory as \PowerShell_transcript.<time-stamp>.txt files. If any of the directories in the path do not exist, the command fails. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe objects to this cmdlet. OUTPUTS System.String Start-Transcript returns a string that contains a confirmation message and the path to the output file. NOTES To stop a transcript, use the Stop-Transcript cmdlet. To record an entire session, add the Start-Transcript command to your p rofile. For more information, see about_Profiles. -------------------------- EXAMPLE 1 -------------------------- C:\PS>start-transcript Description ----------- This command starts a transcript in the default file location. -------------------------- EXAMPLE 2 -------------------------- C:\PS>start-transcript -path c:\transcripts\transcript0.txt -noclobber Description ----------- This command starts a transcript in the Transcript0.txt file in C:\transcri pts. The NoClobber parameter prevents any existing files from being overwri tten. If the Transcript0.txt file already exists, the command fails. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113408 Stop-Transcript Stop-Computer NAME Stop-Computer SYNOPSIS Stops (shuts down) local and remote computers. SYNTAX Stop-Computer [[-ComputerName] <string[]>] [[-Credential] <PSCredential>] [ -AsJob] [-Authentication {Default | None | Connect | Call | Packet | Packet Integrity | PacketPrivacy | Unchanged}] [-Force] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-ThrottleLimit <int>] [-C onfirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Stop-Computer cmdlet shuts down computers remotely. It can also shut do wn the local computer. You can use the parameters of Stop-Computer to run the shutdown operations as a background job, to specify the authentication levels and alternate cre dentials, to limit the concurrent connections that are created to run the c ommand, and to force an immediate shut down. This cmdlet does not require Windows PowerShell remoting unless you use the AsJob parameter. PARAMETERS -AsJob [<SwitchParameter>] Runs the command as a background job. Note: To use this parameter, the local and remote computers must be con figured for remoting and, on Windows Vista and later versions of Window s, you must open Windows PowerShell with the "Run as administrator" opt ion. For more information, see about_Remote_Requirements". When you use the AsJob parameter, the command immediately returns an ob ject that represents the background job. You can continue to work in th e session while the job completes. The job is created on the local comp uter and the results from remote computers are automatically returned t o the local computer. To manage the job, use the Job cmdlets. To get th e job results, use the Receive-Job cmdlet. For more information about Windows PowerShell background jobs, see abou t_Jobs and see about_Remote_Jobs. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationLevel> Specifies the authentication level that is used for the WMI connection . (Stop-Computer uses WMI.) The default value is Packet. Valid values are: Unchanged: The authentication level is the same as the previous c ommand. Default: Windows Authentication. None: No COM authentication. Connect: Connect-level COM authentication. Call: Call-level COM authentication. Packet: Packet-level COM authentication. PacketIntegrity: Packet Integrity-level COM authentication. PacketPrivacy: Packet Privacy-level COM authentication. Required? false Position? named Default value 4 Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Stops the specified computers. The default is the local computer. Type the NETBIOS name, IP address, or fully qualified domain name of on e or more computers in a comma-separated list. To specify the local com puter, type the computername or "localhost". This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter even if your computer is not configured to run remote commands. Required? false Position? 1 Default value . Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a PSC redential object, such as one from the Get-Credential cmdlet. Required? false Position? 2 Default value Current user Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Forces an immediate shut down of the computers. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Impersonation <ImpersonationLevel> Specifies the impersonation level to use when calling WMI. (Stop-Comput er uses WMI.) The default value is "Impersonate". Valid values are: Default: Default impersonation. Anonymous: Hides the identity of the caller. Identify: Allows objects to query the credentials of the caller. Impersonate: Allows objects to use the credentials of the caller. Required? false Position? named Default value Impersonate Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Specifies the maximum number of concurrent connections that can be esta blished to run this command. If you omit this parameter or enter a valu e of 0, the default value, 32, is used. The throttle limit applies only to the current command, not to the sess ion or to the computer. Required? false Position? named Default value 32 Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None or System.Management.Automation.RemotingJob When you use the AsJob parameter, the cmdlet returns a job object (Syst em.Management.Automation.RemotingJob). Otherwise, it does not generate any output. NOTES This cmdlet uses the Win32Shutdown method of the Win32_OperatingSystem WMI class. -------------------------- EXAMPLE 1 -------------------------- C:\PS>stop-computer Description ----------- This command shuts down the local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>stop-computer -computername Server01, Server02, localhost Description ----------- This command stops two remote computers, Server01 and Server02, and the loc al computer, identified as "localhost". -------------------------- EXAMPLE 3 -------------------------- C:\PS>$j = stop-computer -computername Server01, Server02 -asjob C:\PS> $results = $j | receive-job C:\PS> $results Description ----------- These commands run a Stop-Computer command as a background job on two remot e computers, and then get the results. The first command uses the AsJob parameter to run the command as a backgrou nd job. The command saves the resulting job object in the $j variable. The second command uses a pipeline operator to send the job object in $j to the Receive-Job cmdlet, which gets the job results. The command saves the results in the $results variable. The third command displays the result saved in the $results variable. Because the AsJob parameter creates the job on the local computer and autom atically returns the results to the local computer, you can run the Receive -Job command as a local command. -------------------------- EXAMPLE 4 -------------------------- C:\PS>stop-computer -comp Server01 -impersonation anonymous -authentication PacketIntegrity Description ----------- This command restarts the Server01 remote computer. The command uses custom ized impersonation and authentication settings. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$s = get-content domain01.txt C:\PS> $c = get-credential domain01\admin01 C:\PS> stop-computer -computername $s -force -throttlelimit 10 -credential $c Description ----------- These commands force an immediate shut down of all of the computers in Doma in01. The first command gets a list of computers in the domain and saves it in th e $s variable. The second command gets the credentials of a domain administrator and saves them in the $c variable. The third command shuts down the computers. It uses ComputerName parameter to submit the list of computers in the $s variable, the Force parameter to force an immediate shutdown, and the Credential parameter to submit the cre dentials saved in the $c variable. It also uses the ThrottleLimit parameter to limit the command to 10 concurrent connections. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135263 Add-Computer Checkpoint-Computer Remove-Computer Restart-Computer Restore-Computer Test-Connection Stop-Job NAME Stop-Job SYNOPSIS Stops a Windows PowerShell background job. SYNTAX Stop-Job [[-InstanceId] <Guid[]>] [-PassThru] [-Confirm] [-WhatIf] [<Common Parameters>] Stop-Job [-Job] <Job[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters >] Stop-Job [[-Name] <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonPara meters>] Stop-Job [-Id] <Int32[]> [-PassThru] [-Confirm] [-WhatIf] [<CommonParameter s>] Stop-Job [-State {NotStarted | Running | Completed | Failed | Stopped | Blo cked}] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Stop-Job cmdlet stops Windows PowerShell background jobs that are in pr ogress. You can use this cmdlet to stop all jobs or stop selected jobs base d on their name, ID, instance ID, or state, or by passing a job object to S top-Job. You can use Stop-Job to stop jobs that were started by using Start-Job or t he AsJob parameter of Invoke-Command. When you stop a background job, Windo ws PowerShell completes all tasks that are pending in that job queue and th en ends the job. No new tasks are added to the queue after this command is submitted. This cmdlet does not delete background jobs. To delete a job, use Remove-Jo b. PARAMETERS -Id <Int32[]> Stops jobs with the specified IDs. The default is all jobs in the curre nt session. The ID is an integer that uniquely identifies the job within the curren t session. It is easier to remember and type than the InstanceId, but i t is unique only within the current session. You can type one or more I Ds (separated by commas). To find the ID of a job, type "Get-Job" witho ut parameters. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InstanceId <Guid[]> Stops only jobs with the specified instance IDs. The default is all job s. An instance ID is a GUID that uniquely identifies the job on the comput er. To find the instance ID of a job, use Get-Job. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Job <Job[]> Specifies the jobs to be stopped. Enter a variable that contains the jo bs or a command that gets the jobs. You can also use a pipeline operato r to submit jobs to the Stop-Job cmdlet. By default, Stop-Job deletes a ll jobs that were started in the current session. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Name <string[]> Stops only the jobs with the specified friendly names. Enter the job na mes in a comma-separated list or use wildcard characters (*) to enter a job name pattern. By default, Stop-Job stops all jobs created in the c urrent session. Because the friendly name is not guaranteed to be unique, use the WhatI f and Confirm parameters when stopping jobs by name. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true -PassThru [<SwitchParameter>] Returns an object representing the new background job. By default, this cmdlet does not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -State <JobState> Stops only jobs within the specified state. Valid values are NotStarted , Running, Completed, Stopped, Failed, and Blocked. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.RemotingJob You can pipe a job object to Stop-Job. OUTPUTS None or System.Management.Automation.RemotingJob When you use the PassThru parameter, Stop-Job returns a job object. Oth erwise, this cmdlet does not generate any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$s = new-pssession -computername Server01 -credential domain01\admin0 2 C:\PS> $j = invoke-command -session $s -scriptblock {start-job -scriptblock {get-eventlog system}} C:\PS> invoke-command -session $s -scriptblock {param($j) stop-job -job $j} -ArgumentList $j Description ----------- This example shows how to use the Stop-Job cmdlet to stop a job that is run ning on a remote computer. Because the job was started by using Invoke-Command to run a Start-Job comm and remotely, the job object is stored on the remote computer, and you must use another Invoke-Command command to run a Stop-Job command remotely. For more information about remote background jobs, see about_Remote_Jobs. The first command creates a Windows PowerShell session (PSSession) on the S erver01 computer and saves the session object in the $s variable. The comma nd uses the credentials of a domain administrator. The second command uses the Invoke-Command cmdlet to run a Start-Job comman d in the session. The command in the job gets all of the events in the Syst em event log. The resulting job object is stored in the $j variable. The third command stops the job. It uses the Invoke-Command cmdlet to run a Stop-Job command in the PSSession on Server01. Because the job objects are stored in $j, which is a variable on the local computer, the command uses the "param" keyword to declare the local variables in the command, and it u ses the ArgumentList parameter to supply values for the variables. When the command completes, the job is stopped and the PSSession in $s is a vailable for use. -------------------------- EXAMPLE 2 -------------------------- C:\PS>stop-job -state failed Description ----------- This command stops all jobs with a State value of "Failed". -------------------------- EXAMPLE 3 -------------------------- C:\PS>stop-job -name job1 Description ----------- This command stops the Job1 background job. -------------------------- EXAMPLE 4 -------------------------- C:\PS>stop-job -id 1, 3, 4 Description ----------- This command stops three jobs. It identifies them by their IDs. -------------------------- EXAMPLE 5 -------------------------- C:\PS>get-job | stop-job Description ----------- This command stops all the background jobs in the current session. -------------------------- EXAMPLE 6 -------------------------- C:\PS>stop-job -state blocked Description ----------- This command stops all the jobs with a job status of "Blocked". -------------------------- EXAMPLE 7 -------------------------- C:\PS>get-job | format-table ID, Name, Command, @{Label="State";Expression= {$_.jobstateinfo.state}}, I nstanceID -auto Id Name Command State InstanceId -- ---- ------- ----- ---------- 1 Job1 start-service schedule Running 05abb67a-2932-4bd5-b331-c0254b8d9146 3 Job3 start-service schedule Running c03cbd45-19f3-4558-ba94-ebe41b68ad03 5 Job5 get-service s* Blocked e3bbfed1-9c53-401a-a2c3-a8db34336adf C:\PS> stop-job -instanceid e3bbfed1-9c53-401a-a2c3-a8db34336adf Description ----------- These commands show how to stop a job based on its instance ID. The first command uses a Get-Job command to get the jobs in the current ses sion. The command uses a pipeline operator (|) to send the jobs to a Format -Table command, which displays a table of the specified properties of each job. The table includes the Instance ID of each job. It uses a calculated p roperty to display the job state. The second command uses a Stop-Job command with the InstanceID parameter to stop a selected job. -------------------------- EXAMPLE 8 -------------------------- C:\PS>$j = invoke-command -computername Server01 -scriptblock {get-eventlog system} -asjob C:\PS> $j | stop-job -passthru Id Name State HasMoreData Location Command -- ---- ---- ----------- -------- ------- 5 Job5 Stopped True judithh-tablet get-eventlog syst em Description ----------- This example shows how to use the Stop-Job cmdlet to stop a job that is run ning on a remote computer. Because the job was started by using the AsJob parameter of Invoke-Command, the job object is located on the local computer, even though the job runs on the remote computer. As such, you can use a local Stop-Job command to st op the job. The first command uses the Invoke-Command cmdlet to start a background job on the Server01 computer. The command uses the AsJob parameter to run the r emote command as a background job. This command returns a job object, which is the same job object that Start- Job returns. The command saves the job object in the $j variable. The second command uses a pipeline operator to send the job in the $j varia ble to Stop-Job. The command uses the PassThru parameter to direct Stop-Job to return a job object. The job object display confirms that the State of the job is "Stopped". For more information about remote background jobs, see about_Remote_Jobs. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113413 about_Jobs about_Job_Details about_Remote_Jobs Start-Job Get-Job Receive-Job Wait-Job Remove-Job Invoke-Command Stop-Process NAME Stop-Process SYNOPSIS Stops one or more running processes. SYNTAX Stop-Process [-Id] <Int32[]> [-Force] [-PassThru] [-Confirm] [-WhatIf] [<Co mmonParameters>] Stop-Process -InputObject <Process[]> [-Force] [-PassThru] [-Confirm] [-Wha tIf] [<CommonParameters>] Stop-Process -Name <string[]> [-Force] [-PassThru] [-Confirm] [-WhatIf] [<C ommonParameters>] DESCRIPTION The Stop-Process cmdlet stops one or more running processes. You can specif y a process by process name or process ID (PID), or pass a process object t o Stop-Process. Stop-Process works only on processes running on the local computer. On Windows Vista and later versions of Windows, to stop a process that is n ot owned by the current user, you must start Windows PowerShell with the "R un as administrator" option. Also, you are prompted for confirmation unles s you use the Force parameter. PARAMETERS -Force [<SwitchParameter>] Stops the specified processes without prompting for confirmation. By de fault, Stop-Process prompts for confirmation before stopping any proces s that is not owned by the current user. To find the owner of a process, use the Get-WmiMethod cmdlet to get a W in32_Process object that represents the process, and then use the GetOw ner method of the object. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Id <Int32[]> Specifies the process IDs of the processes to be stopped. To specify mu ltiple IDs, use commas to separate the IDs. To find the PID of a proces s, type "get-process". The parameter name ("Id") is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InputObject <Process[]> Stops the processes represented by the specified process objects. Enter a variable that contains the objects, or type a command or expression that gets the objects. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the process names of the processes to be stopped. You can typ e multiple process names (separated by commas) or use wildcard characte rs. Required? true Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the process. By default, this cmdlet doe s not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Diagnostics.Process You can pipe a process object to Stop-Process. OUTPUTS None or System.Diagnostics.Process When you use the PassThru parameter, Stop-Process returns a System.Diag nostics.Process object that represents the stopped process. Otherwise, this cmdlet does not generate any output. NOTES You can also refer to Stop-Process by its built-in aliases, "kill" and "spps". For more information, see about_Aliases. You can also use the properties and methods of the Windows Management I nstrumentation (WMI) Win32_Process object in Windows PowerShell. For mo re information, see Get-WmiObject and the WMI SDK. When stopping processes, be aware that stopping a process can stop proc ess and services that depend on the process. In an extreme case, stoppi ng a process can stop Windows. -------------------------- EXAMPLE 1 -------------------------- C:\PS>stop-process -name notepad Description ----------- This command stops all instances of the Notepad process on the computer. (E ach instance of Notepad runs in its own process.) It uses the Name paramete r to specify the processes, all of which have the same name. If you were to use the ID parameter to stop the same processes, you would have to list th e process IDs of each instance of Notepad. -------------------------- EXAMPLE 2 -------------------------- C:\PS>stop-process -id 3952 -confirm -passthru Confirm Are you sure you want to perform this action? Performing operation "Stop-Process" on Target "notepad (3952)". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):y Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 41 2 996 3212 31 3952 notepad Description ----------- This command stops a particular instance of the Notepad process. It uses th e process ID, 3952, to identify the process. The Confirm parameter directs Windows PowerShell to prompt the user before stopping the process. Because the prompt includes the process name, as well as its ID, this is best pract ice. The PassThru parameter passes the process object to the formatter for display. Without this parameter, there would be no display after a Stop-Pro cess command. -------------------------- EXAMPLE 3 -------------------------- C:\PS>calc c:\PS>$p = get-process calc c:\PS>stop-process -inputobject $p c:\PS>get-process | where-object {$_.HasExited} Description ----------- This series of commands starts and stops the Calc process and then detects processes that have stopped. The first command ("calc") starts an instance of the calculator. The second command ("$p = get-process calc"), uses the Get-Process cmdlet to get an o bject representing the Calc process and store it in the $p variable. The th ird command ("stop-process -inputobject $p") uses the Stop-Process cmdlet t o stop the Calc process. It uses the InputObject parameter to pass the obje ct to Stop-Process. The last command gets all of the processes on the computer that were runnin g but that are now stopped. It uses the Get-Process cmdlet to get all of th e processes on the computer. The pipeline operator (|) passes the results t o the Where-Object cmdlet, which selects the ones where the value of the Ha sExited property is TRUE. HasExited is just one property of process objects . To find all the properties, type "get-process | get-member". -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-process lsass | stop-process Stop-Process : Cannot stop process 'lsass (596)' because of the following e rror: Access is denied At line:1 char:34 + get-process lsass | stop-process [ADMIN]: C:\PS> get-process lsass | stop-process Warning Are you sure you want to perform this action? Performing operation 'Stop-Process' on Target 'lsass(596)' [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (defa ult is "Y"): [ADMIN]: C:\PS> get-process lsass | stop-process -force [ADMIN]: C:\PS> Description ----------- These commands show the effect of using the Force parameter to stop a proce ss that is not owned by the user. The first command uses the Get-Process cmdlet to get the Lsass process. A p ipeline operator sends the process to the Stop-Process cmdlet to stop it. A s shown in the sample output, the first command fails with an "Access denie d" message, because this process can be stopped only by a member of the Adm inistrator's group on the computer. When Windows PowerShell is opened with the "Run as administrator" option, a nd the command is repeated, Windows PowerShell prompts you for confirmation . The second command uses the Force parameter to suppress the prompt. As a re sult, the process is stopped without confirmation. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113412 Get-Process Start-Process Stop-Process Wait-Process Debug-Process Stop-Service NAME Stop-Service SYNOPSIS Stops one or more running services. SYNTAX Stop-Service [-Name] <string[]> [-Exclude <string[]>] [-Force] [-Include <s tring[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Stop-Service -DisplayName <string[]> [-Exclude <string[]>] [-Force] [-Inclu de <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Stop-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [-F orce] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParame ters>] DESCRIPTION The Stop-Service cmdlet sends a stop message to the Windows Service Control ler for each of the specified services. You can specify the services by the ir service names or display names, or you can use the InputObject parameter to pass a service object representing the services that you want to stop. PARAMETERS -DisplayName <string[]> Specifies the display names of the services to be stopped. Wildcards ar e permitted. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to stop a service even if that service has dependent services. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Stops only the specified services. The value of this parameter qualifie s the Name parameter. Enter a name element or pattern, such as "s*". Wi ldcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ServiceController[]> Specifies ServiceController objects representing the services to be sto pped. Enter a variable that contains the objects, or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the service names of the services to be stopped. Wildcards ar e permitted. The parameter name is optional. You can use "Name" or its alias, "Servi ceName", or you can omit the parameter name. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the service. By default, this cmdlet doe s not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.ServiceProcess.ServiceController or System.String You can pipe a service object or a string that contains the name of a s ervice to Stop-Service. OUTPUTS None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Stop-Service generates a System.Se rviceProcess.ServiceController object representing the service. Otherwi se, this cmdlet does not generate any output. NOTES You can also refer to Stop-Service by its built-in alias, "spsv". For m ore information, see about_Aliases. Stop-Service can control services only when the current user has permis sion to do so. If a command does not work correctly, you might not have the required permissions. To find the service names and display names of the services on your sys tem, type "get-service". The service names appear in the Name column an d the display names appear in the DisplayName column. -------------------------- EXAMPLE 1 -------------------------- C:\PS>stop-service sysmonlog Description ----------- This command stops the Performance Logs and Alerts (SysmonLog) service on t he local computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-service -displayname telnet | stop-service Description ----------- This command stops the Telnet service on the local computer. The command us es the Get-Service cmdlet to get an object representing the Telnet service. The pipeline operator (|) pipes the object to the Stop-Service cmdlet, whi ch stops the service. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-service iisadmin | format-list -property name, dependentservices C:PS>stop-service iisadmin -force -confirm Description ----------- The Stop-Service command stops the IISAdmin service on the local computer. Because stopping this service also stops the services that depend on the II SAdmin service, it is best to precede the Stop-Service command with a comma nd that lists the services that depend on the IISAdmin service. The first command lists the services that depend on IISAdmin. It uses the G et-Service cmdlet to get an object representing the IISAdmin service. The p ipeline operator (|) passes the result to the Format-List cmdlet. The comma nd uses the Property parameter of Format-List to list only the Name and Dep endentServices properties of the service. The second command stops the IISAdmin service. The Force parameter is requi red to stop a service that has dependent services. The command uses the Con firm parameter to request confirmation from the user before stopping each s ervice. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113414 Get-Service Suspend-Service Start-Service Restart-Service Resume-Service Set-Service New-Service Stop-Transcript NAME Stop-Transcript SYNOPSIS Stops a transcript. SYNTAX Stop-Transcript [<CommonParameters>] DESCRIPTION The Stop-Transcript cmdlet stops a transcript that was started by using the Start-Transcript cmdlet. You can also stop a transcript by ending the sess ion. PARAMETERS <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.String Stop-Transcript returns a string that contains a status message and the path to the output file. NOTES If a transcript has not been started, the command fails. -------------------------- EXAMPLE 1 -------------------------- C:\PS>stop-transcript Description ----------- This command stops any running transcripts. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113415 Start-Transcript Suspend-Service NAME Suspend-Service SYNOPSIS Suspends (pauses) one or more running services. SYNTAX Suspend-Service [-Name] <string[]> [-Exclude <string[]>] [-Include <string[ ]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Suspend-Service -DisplayName <string[]> [-Exclude <string[]>] [-Include <st ring[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] Suspend-Service [-InputObject <ServiceController[]>] [-Exclude <string[]>] [-Include <string[]>] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Suspend-Service cmdlet sends a suspend message to the Windows Service C ontroller for each of the specified services. While suspended, the service is still running, but its action is halted until resumed, such as by using Resume-Service. You can specify the services by their service names or disp lay names, or you can use the InputObject parameter to pass a service objec t representing the services that you want to suspend. PARAMETERS -DisplayName <string[]> Specifies the display names of the services to be suspended. Wildcards are permitted. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Exclude <string[]> Omits the specified services. The value of this parameter qualifies the Name parameter. Enter a name element or pattern, such as "s*". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Suspends only the specified services. The value of this parameter quali fies the Name parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <ServiceController[]> Specifies ServiceController objects representing the services to be sus pended. Enter a variable that contains the objects, or type a command o r expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the service names of the services to be suspended. Wildcards are permitted. The parameter name is optional. You can use "Name" or its alias, "Servi ceName", or you can omit the parameter name. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PassThru [<SwitchParameter>] Returns an object representing the service. By default, this cmdlet doe s not generate any output. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.ServiceProcess.ServiceController or System.String You can pipe a service object or a string that contains a service name to Suspend-Service. OUTPUTS None or System.ServiceProcess.ServiceController When you use the PassThru parameter, Suspend-Service generates a System .ServiceProcess.ServiceController object representing the service. Othe rwise, this cmdlet does not generate any output. NOTES Suspend-Service can control services only when the current user has per mission to do so. If a command does not work correctly, you might not h ave the required permissions. Also, Suspend-Service can suspend only services that support being susp ended and resumed. To determine whether a particular service can be sus pended, use the Get-Service cmdlet with the CanPauseAndContinue propert y. For example, "get-service wmi | format-list name, canpauseandcontinu e". To find all services on the computer that can be suspended, type "g et-service | where-object {$_.canpauseandcontinue -eq "True"}". To find the service names and display names of the services on your sys tem, type "get-service". The service names appear in the Name column, a nd the display names appear in the DisplayName column. -------------------------- EXAMPLE 1 -------------------------- C:\PS>suspend-service -displayname "Telnet" Description ----------- This command suspends the Telnet service (Tlntsvr) service on the local com puter. -------------------------- EXAMPLE 2 -------------------------- C:\PS>suspend-service -name lanman* -whatif Description ----------- This command tells what would happen if you suspended the services that hav e a service name that begins with "lanman". To suspend the services, rerun the command without the WhatIf parameter. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-service schedule | suspend-service Description ----------- This command uses the Get-Service cmdlet to get an object that represents t he Task Scheduler (Schedule) service on the computer. The pipeline operator (|) passes the result to the Suspend-Service cmdlet, which suspends the se rvice. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-service | where-object {$_.canpauseandcontinue -eq "True"} | susp end-service -confirm Description ----------- This command suspends all of the services on the computer that can be suspe nded. It uses the Get-Service cmdlet to get objects representing the servic es on the computer. The pipeline operator (|) passes the results to the Whe re-Object cmdlet, which selects only the services that have a value of "Tru e" for the CanPauseAndContinue property. Another pipeline operator passes t he results to the Suspend-Service cmdlet. The Confirm parameter prompts you for confirmation before suspending each of the services. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113416 Get-Service Start-Service Stop-Service Restart-Service Resume-Service Set-Service New-Service TabExpansion TabExpansion [[-line] <Object>] [[-lastWord] <Object>] Tee-Object NAME Tee-Object SYNOPSIS Saves command output in a file or variable, and displays it in the console. SYNTAX Tee-Object [-FilePath] <string> [-InputObject <psobject>] [<CommonParameter s>] Tee-Object -Variable <string> [-InputObject <psobject>] [<CommonParameters> ] DESCRIPTION The Tee-Object cmdlet sends the output of a command in two directions (like the letter "T"). It stores the output in a file or variable and also sends it down the pipeline. If Tee-Object is the last command in the pipeline, t he command output is displayed in the console. PARAMETERS -FilePath <string> Specifies the file where the cmdlet stores the object. Accepts wildcard s that resolve to a single file. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the object input to the cmdlet. Enter a variable that contain s the objects or type a command or expression that gets the objects. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Variable <string> Assigns a reference to the input objects to the specified variable. Required? true Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe objects to be redirected to Tee-Object. OUTPUTS System.Management.Automation.PSObject Tee-Object returns the object that it redirected. NOTES You can also use the Out-File cmdlet or the redirection operator, both of which save the output in a file but do not send it down the pipeline . Tee-Object uses Unicode encoding when it writes to files. As a result, the output might not be formatted properly in files with a different en coding. To specify the encoding, use the Out-File cmdlet. -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-process | tee-object -filepath C:\Test1\testfile2.txt Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 83 4 2300 4520 39 0.30 4032 00THotkey 272 6 1400 3944 34 0.06 3088 alg 81 3 804 3284 21 2.45 148 ApntEx 81 4 2008 5808 38 0.75 3684 Apoint ... Description ----------- This command gets a list of the processes running on the computer and sends the result to a file. Because a second path is not specified, the result w ill be displayed in the console. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-process notepad | tee-object -variable proc | select-object proce ssname,handles ProcessName Handles ----------- ------- notepad 43 notepad 37 notepad 38 notepad 38 Description ----------- This command gets a list of the processes running on the computer and sends the result to a variable named "proc". It then pipes the resulting objects along to Select-Object, which selects the ProcessName and Handles property . Note that the $proc variable includes the default information returned by Get-Process. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113417 about_Redirection Select-Object Test-ComputerSecureChannel NAME Test-ComputerSecureChannel SYNOPSIS Tests and repairs the secure channel between the local computer and its dom ain. SYNTAX Test-ComputerSecureChannel [-Repair] [-Server <string>] [-Confirm] [-WhatIf ] [<CommonParameters>] DESCRIPTION The Test-ComputerSecureChannel cmdlet verifies that the secure channel betw een the local computer and its domain is working correctly by checking the status of its trust relationships. If a connection fails, you can use the R epair parameter to try to restore it. Test-ComputerSecureChannel returns "True" if the secure channel is working correctly and "False" if it is not. This result lets you use the cmdlet in conditional statements in functions and scripts. To get more detailed test results, use the Verbose parameter. This cmdlet works much like NetDom.exe. Both NetDom and Test-ComputerSecure Channel use the NetLogon service to perform the actions. PARAMETERS -Repair [<SwitchParameter>] Removes and then rebuilds the secure channel established by the NetLogo n service. Use this parameter to try to restore a connection that has f ailed the test (returned "False".) To use this parameter, the current user must be a member of the Adminis trators group on the local computer. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Server <string> Uses the specified domain controller to run the command. If this parame ter is omitted, Test-ComputerSecureChannel selects a default domain con troller for the operation. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Boolean The cmdlet returns "True" when the connection is working correctly and "False" when it is not. NOTES To run a Test-ComputerSecureChannel command on Windows Vista and later versions of Windows, open Windows PowerShell with the "Run as administr ator" option. Test-ComputerSecureChannel is implemented by using the I_NetLogonContr ol2 function, which controls various aspects of the Netlogon service. -------------------------- EXAMPLE 1 -------------------------- C:\PS>test-computersecurechannel True Description ----------- This command tests the secure channel between the local computer and the do main to which it is joined. -------------------------- EXAMPLE 2 -------------------------- C:\PS>test-computersecurechannel -server DCName.fabrikam.com True Description ----------- This command specifies a preferred domain controller for the test. -------------------------- EXAMPLE 3 -------------------------- C:\PS>Test-ComputerSecureChannel -repair True Description ----------- This command resets the secure channel between the local computer and its d omain. -------------------------- EXAMPLE 4 -------------------------- C:\PS>test-computerSecureChannel -verbose VERBOSE: Performing operation "Test-ComputerSecureChannel" on Target "SERVE R01". True VERBOSE: "The secure channel between 'SERVER01' and 'net.fabrikam.com' is a live and working correctly." Description ----------- This command uses the Verbose common parameter to request detailed messages about the operation. For more information about the Verbose parameter, see about_CommonParameters. -------------------------- EXAMPLE 5 -------------------------- C:\PS>set-alias tcsc test-computersecurechannel if ((tcsc)) {write-host "Connection failed. Reconnect and retry."} else { &(.\get-servers.ps1) } Description ----------- This example shows how to use Test-ComputerSecureChannel to test a connecti on before running a script that requires the connection. The first command uses the Set-Alias cmdlet to create an alias for the cmdl et name. This saves space and prevents typing errors. The If statement checks the value that Test-ComputerSecureChannel returns b efore running a script. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=137749 Checkpoint-Computer Restart-Computer Stop-Computer Reset-ComputerMachinePassword Test-Connection NAME Test-Connection SYNOPSIS Sends ICMP echo request packets ("pings") to one or more computers. SYNTAX Test-Connection [-ComputerName] <string[]> [[-Source] <string[]>] [-AsJob] [-Authentication {Default | None | Connect | Call | Packet | PacketIntegrit y | PacketPrivacy | Unchanged}] [-BufferSize <int>] [-Count <int>] [-Creden tial <PSCredential>] [-Delay <int>] [-Impersonation {Default | Anonymous | Identify | Impersonate | Delegate}] [-Quiet] [-ThrottleLimit <int>] [-TimeT oLive <int>] [<CommonParameters>] DESCRIPTION The Test-Connection cmdlet sends Internet Control Message Protocol (ICMP) e cho request packets ("pings") to one or more remote computers and returns t he echo response replies. You can use this cmdlet to determine whether a pa rticular computer can be contacted across an Internet Protocol (IP) network . You can use the parameters of Test-Connection to specify both the sending a nd receiving computers, to run the command as a background job, to set a ti meout and number of pings, and to configure the connection and authenticati on. Unlike the traditional "ping" command, Test-Connection returns a Win32_Ping Status object that you can investigate in Windows PowerShell, but you can u se the Quiet parameter to force it to return only a Boolean value. PARAMETERS -AsJob [<SwitchParameter>] Runs the command as a background job. Note: To use this parameter, the local and remote computers must be con figured for remoting and, on Windows Vista and later versions of Window s, you must open Windows PowerShell with the "Run as administrator" opt ion. For more information, see about_Remote_Requirements. When you use the AsJob parameter, the command immediately returns an ob ject that represents the background job. You can continue to work in th e session while the job completes. The job is created on the local comp uter and the results from remote computers are automatically returned t o the local computer. To get the job results, use the Receive-Job cmdle t. For more information about Windows PowerShell background jobs, see abou t_Jobs and about_Remote_Jobs. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Authentication <AuthenticationLevel> Specifies the authentication level that is used for the WMI connection . (Test-Connection uses WMI.) Valid values are: Unchanged: The authentication level is the same as the previous c ommand. Default: Windows Authentication. None: No COM authentication. Connect: Connect-level COM authentication. Call: Call-level COM authentication. Packet: Packet-level COM authentication. PacketIntegrity: Packet Integrity-level COM authentication. PacketPrivacy: Packet Privacy-level COM authentication. Required? false Position? named Default value 4 Accept pipeline input? false Accept wildcard characters? false -BufferSize <int> Specifies the size, in bytes, of the buffer sent with this command. The default value is 32. Required? false Position? named Default value 32 Accept pipeline input? false Accept wildcard characters? false -ComputerName <string[]> Specifies the computers to ping. Type the computer names or type IP add resses in IPv4 or IPv6 format. Wildcard characters are not permitted. T his parameter is required. This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter even if your computer is not configured to run remote commands. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Count <int> Specifies the number of echo requests to send. The default value is 4. Required? false Position? named Default value 4 Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Ty pe a user name, such as "User01" or "Domain01\User01", or enter a PSCre dential object, such as one from the Get-Credential cmdlet. Required? false Position? named Default value Current user Accept pipeline input? false Accept wildcard characters? false -Delay <int> Specifies the interval between pings, in seconds. Required? false Position? named Default value 1 (second) Accept pipeline input? false Accept wildcard characters? false -Impersonation <ImpersonationLevel> Specifies the impersonation level to use when calling WMI. (Test-Connec tion uses WMI.) The default value is "Impersonate". Valid values are: Default: Default impersonation. Anonymous: Hides the identity of the caller. Identify: Allows objects to query the credentials of the caller. Impersonate: Allows objects to use the credentials of the caller. Required? false Position? named Default value 3 Accept pipeline input? false Accept wildcard characters? false -Quiet [<SwitchParameter>] Suppresses all errors and returns $True if any pings succeeded and $Fal se if all failed. Required? false Position? named Default value False Accept pipeline input? false Accept wildcard characters? false -Source <string[]> Specifies the names of the computers where the ping originates. Enter a comma-separated list of computer names. The default is the local compu ter. Required? false Position? 2 Default value Local computer Accept pipeline input? false Accept wildcard characters? false -ThrottleLimit <int> Specifies the maximum number of concurrent connections that can be esta blished to run this command. If you omit this parameter or enter a valu e of 0, the default value, 32, is used. The throttle limit applies only to the current command, not to the sess ion or to the computer. Required? false Position? named Default value 32 Accept pipeline input? false Accept wildcard characters? false -TimeToLive <int> Specifies the maximum time, in seconds, that each echo request packet ( "pings") is active. The default value is 80 (seconds). The alias of the TimeToLive parameter is TTL. Required? false Position? named Default value 80 Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Management.ManagementObject#root\cimv2\Win32_PingStatus, System.Mana gement.Automation.RemotingJob, System.Boolean When you use the AsJob parameter, the cmdlet returns a job object. When you use the Quiet parameter, it returns a Boolean. Otherwise, this cmd let returns a Win32_PingStatus object for each ping. NOTES This cmdlet uses the Win32_PingStatus class. A "get-wmiojbect win32_pin gstatus" command is equivalent to a Test-Connection command. -------------------------- EXAMPLE 1 -------------------------- C:\PS>test-connection server01 Source Destination IPV4Address IPV6Address Bytes Time(ms ) ------ ----------- ----------- ----------- ----- ------- - ADMIN1 Server01 157.59.137.44 32 0 ADMIN1 Server01 157.59.137.44 32 0 ADMIN1 Server01 157.59.137.44 32 0 ADMIN1 Server01 157.59.137.44 32 1 Description ----------- This command sends echo request packets ("pings") from the local computer t o the Server01 computer. This command uses the ComputerName parameter to sp ecify the Server01 computer, but omits the optional parameter name. -------------------------- EXAMPLE 2 -------------------------- C:\PS>test-connection -computername server01, server02, server12 -credentia l domain01\user01 Description ----------- This command sends pings from the local computer to several remote computer s. It uses the Credential parameter to specify a user account that has perm ission to ping all of the remote computers. -------------------------- EXAMPLE 3 -------------------------- C:\PS>test-connection -source Server02, Server 12, localhost -computername Server01 Description ----------- This command sends pings from different source computers to a single remote computer, Server01. Use this command format to test the latency of connect ions from multiple points. -------------------------- EXAMPLE 4 -------------------------- C:\PS>test-connection -computername Server01 -count 3 -delay 2 -TTL 256 -bu ffersize 256 -throttle 32 Description ----------- This command sends three pings from the local computer to the Server01 comp uter. It uses the parameters of Test-Connection to customize the command. Use this command format when the ping response is expected to take longer t han usual, either because of an extended number of hops or a high-traffic n etwork condition. -------------------------- EXAMPLE 5 -------------------------- C:\PS>$job = test-connection -computername (get-content servers.txt) -asjob C:\PS> if ($job.jobstateinfo.state -ne "Running") {$results = receive-job $ job} Description ----------- This example shows how to run a Test-Connection command as a Windows PowerS hell background job. The first command uses the Test-Connection cmdlet to ping many computers in an enterprise. The value of ComputerName parameter is a Get-Content comman d that reads a list of computer names from the Servers.txt file. The comman d uses the AsJob parameter to run the command as a background job. The second command checks to see that the job is not still running, and if it is not, it uses a Receive-Job command to get the results and store them in the $results variable. -------------------------- EXAMPLE 6 -------------------------- C:\PS>test-connection Server55 -credential domain55\user01 -impersonation I dentify Description ----------- This command uses the Test-Connection cmdlet to ping a remote computer. The command uses the Credential parameter to specify a user account with permi ssion to ping the remote computer and the Impersonation parameter to change the impersonation level to "Identify". -------------------------- EXAMPLE 7 -------------------------- C:\PS>if (test-connection -computername Server01 -quiet) {new-pssession Ser ver01} Description ----------- This command creates a PSSession on the Server01 only if at least one of th e pings sent to the computer succeeds. The command uses the Test-Connection cmdlet to ping the Server01 computer. The command uses the Quiet parameter, which returns a Boolean value, instea d of a Win32_PingStatus object. The value is $True if any of the four pings succeed and is, otherwise, false. If the Test-Connection command returns a value of $True, the command uses t he New-PSSession cmdlet to create the PSSession. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135266 Add-Computer Restart-Computer Stop-Computer Test-ModuleManifest NAME Test-ModuleManifest SYNOPSIS Verifies that a module manifest file accurately describes the contents of a module. SYNTAX Test-ModuleManifest [-Path] <string> [<CommonParameters>] DESCRIPTION The Test-ModuleManifest cmdlet verifies that the files that are listed in t he module manifest (.psd1) file actually exist in the specified paths. This cmdlet is designed to help module authors test their manifest files. M odule users can also use this cmdlet in scripts and commands to detect erro rs before running scripts that depend on the module. The Test-ModuleManifest cmdlet returns an object that represents the module (the same type of object that Get-Module returns). If any files are not in the locations specified in the manifest, the cmdlet also generates an erro r for each missing file. PARAMETERS -Path <string> Specifies the path to the module manifest file. Enter a path (optional ) and the name of the module manifest file with the .psd1 file name ext ension. The default location is the current directory. This parameter i s required. The parameter name ("Path") is optional. You can also pipe a path to Test-ModuleManifest. Required? true Position? 1 Default value None Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe the path to a module manifest to Test-ModuleManifest. OUTPUTS System.Management.Automation.PSModuleInfo Test-ModuleManifest returns a PSModuleInfo object that represents the m odule. It returns this object even if the manifest has errors. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>test-ModuleManifest -path $pshome\Modules\TestModule.psd1 Description ----------- This command tests the TestModule.psd1 module manifest. -------------------------- EXAMPLE 2 -------------------------- C:\PS>"$pshome\Modules\TestModule.psd1" | test-modulemanifest Test-ModuleManifest : The specified type data file 'C:\Windows\System32\Wi ndowsPowerShell\v1.0\Modules\TestModule\TestTypes.ps1xml' could not be pro cessed because the file was not found. Please correct the path and try aga in. At line:1 char:34 + "$pshome\Modules\TestModule.psd1" | test-modulemanifest + CategoryInfo : ResourceUnavailable: (C:\Windows\System32\Win dowsPowerShell\v1.0\Modules\TestModule\TestTypes.ps1xml:String) [Test-Modul eManifest], FileNotFoundException + FullyQualifiedErrorId : Modules_TypeDataFileNotFound,Microsoft. PowerShell.Commands.TestModuleManifestCommandName Name : TestModule Path : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Test Module\TestModule.psd1 Description : Guid : 6f0f1387-cd25-4902-b7b4-22cff6aefa7b Version : 1.0 ModuleBase : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Test Module ModuleType : Manifest PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {} ExportedVariables : {} NestedModules : {} Description ----------- This command uses a pipeline operator (|) to send a path string to Test-Mod uleManifest. The command output shows that the test failed, because the TestTypes.ps1xml file, which was listed in the manifest, was not found. -------------------------- EXAMPLE 3 -------------------------- C:\PS>function Bool-ModuleManifest ($path) {$a = dir $path | test-modulemanifest -erroraction SilentlyContinue; $? } Description ----------- This function is like Test-ModuleManifest, but it returns a Boolean value; it returns "True" if the manifest passed the test and "False" otherwise. The function uses the Get-ChildItem cmdlet (alias = dir) to get the module manifest specified by the $path variable. It uses a pipeline operator (|) t o pass the file object to the Test-ModuleManifest cmdlet. The Test-ModuleManifest command uses the ErrorAction common parameter with a value of SilentlyContinue to suppress the display of any errors that the command generates. It also saves the PSModuleInfo object that Test-ModuleMa nifest returns in the $a variable, so the object is not displayed. Then, in a separate command (the semi-colon [;] is the command separator), it displays the value of the $? automatic variable, which returns "True" if the previous command generated no error and "False" otherwise. You can use this function in conditional statements, such as those that mig ht precede an Import-Module command or a command that uses the module. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=141557 Import-Module Get-Module New-Module Remove-Module Export-ModuleMember New-ModuleManifest about_Modules Test-Path NAME Test-Path SYNOPSIS Determines whether all elements of a path exist. SYNTAX Test-Path [-LiteralPath] <string[]> [-Credential <PSCredential>] [-Exclude <string[]>] [-Filter <string>] [-Include <string[]>] [-IsValid] [-PathType {Any | Container | Leaf}] [-UseTransaction] [<CommonParameters>] Test-Path [-Path] <string[]> [-Credential <PSCredential>] [-Exclude <string []>] [-Filter <string>] [-Include <string[]>] [-IsValid] [-PathType {Any | Container | Leaf}] [-UseTransaction] [<CommonParameters>] DESCRIPTION The Test-Path cmdlet determines whether all elements of the path exist. It returns TRUE ($true) if all elements exist and FALSE ($false) if any are mi ssing. It can also tell whether the path syntax is valid and whether the pa th leads to a container or a terminal (leaf) element. PARAMETERS -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01" or "Domain01\User01". Or, enter a PS Credential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you will be prompted for a password. This parameter is not supported by any providers installed with Windows PowerShell. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Exclude <string[]> Omits the specified items. The value of this parameter qualifies the Pa th parameter. Enter a path element or pattern, such as "*.txt". Wildcar ds are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Filter <string> Specifies a filter in the provider's format or language. The value of t his parameter qualifies the Path parameter. The syntax of the filter, i ncluding the use of wildcards, depends on the provider. Filters are mor e efficient than other parameters, because the provider applies them wh en retrieving the objects rather than having Windows PowerShell filter the objects after they are retrieved. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Include <string[]> Tests only the specified paths. The value of this parameter qualifies t he Path parameter. Enter a path element or pattern, such as "*.txt". Wi ldcards are permitted. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -IsValid [<SwitchParameter>] Determines whether the syntax of the path is correct, regardless of whe ther the elements of the path exist. This parameter returns TRUE if the path syntax is valid and FALSE if it is not. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -LiteralPath <string[]> Specifies a path to be tested. Unlike Path, the value of the LiteralPat h parameter is used exactly as it is typed. No characters are interpret ed as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Path <string[]> Specifies a path to be tested. Wildcards are permitted. If the path inc ludes spaces, enclose it in quotation marks. The parameter name ("Path" ) is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PathType <TestPathType> Tells whether the final element in the path is of a particular type. Th is parameter returns TRUE if the element is of the specified type and F ALSE if it is not. Valid values are: -- Container: An element that contains other elements, such as a direct ory or registry key. -- Leaf: An element that does not contain other elements, such as a fil e. -- Any: Either a container or a leaf.Tells whether the final element in the path is of a particular type. Returns TRUE if the element is of th e specified type and FALSE if it is not. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a path (but not a literal path) to Test-Path. OUTPUTS System.Boolean The cmdlet returns "True" when the path exists and "False" when it does not. NOTES The cmdlets that contain the Path noun (the Path cmdlets) manipulate pa th names and return the names in a concise format that all Windows Powe rShell providers can interpret. They are designed for use in programs a nd scripts where you want to display all or part of a path name in a pa rticular format. Use them like you would use Dirname, Normpath, Realpat h, Join, or other path manipulators. You can use the Path cmdlets with several providers, including the Fil eSystem, Registry, and Certificate providers. The Test-Path cmdlet is designed to work with the data exposed by any p rovider. To list the providers available in your session, type "Get-PSP rovider". For more information, see about_Providers. -------------------------- EXAMPLE 1 -------------------------- C:\PS>test-path -path "C:\Documents and Settings\NicoleH" Description ----------- This command tells whether all elements in the path exist, that is, the C: directory, the Documents and Settings directory, and the NicoleH directory. If any are missing, the cmdlet returns FALSE. Otherwise, it returns TRUE. -------------------------- EXAMPLE 2 -------------------------- C:\PS>test-path -path $profile C:\PS>test-path -path $profile -IsValid Description ----------- These commands test the path to the Windows PowerShell profile. The first command determines whether all elements in the path exist. The se cond command determines whether the syntax of the path is correct. In this case, the path is FALSE, but the syntax is correct (TRUE). These commands u se $profile, the automatic variable that points to the location for the pro file, even if the profile does not exist. For more information about automatic variables, see about_Automatic_Variabl es. -------------------------- EXAMPLE 3 -------------------------- C:\PS>test-path -path "C:\CAD\Commercial Buildings\*" -exclude *.dwg Description ----------- This command tells whether there are any files in the Commercial Buildings directory other than .dwg files. The command uses the Path parameter to specify the path. Because it include s a space, the path is enclosed in quotes. The asterisk at the end of the p ath indicates the contents of the Commercial Building directory. (With long paths, like this one, type the first few letters of the path, and then use the TAB key to complete the path.) The command uses the Exclude parameter to specify files that will be omitte d from the evaluation. In this case, because the directory contains only .dwg files, the result is FALSE. -------------------------- EXAMPLE 4 -------------------------- C:\PS>test-path -path $profile -pathtype leaf Description ----------- This command tells whether the path stored in the $profile variable leads t o a file. In this case, because the Windows PowerShell profile is a .ps1 fi le, the cmdlet returns TRUE. -------------------------- EXAMPLE 5 -------------------------- C:\PS>test-path -path HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Micros oft.PowerShell TRUE C:\PS> test-path -path HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Micro soft.PowerShell\ExecutionPolicy FALSE Description ----------- These commands use the Test-Path cmdlet with the Windows PowerShell registr y provider. The first command tests whether the registry path to the Microsoft.PowerShe ll registry key is correct on the system. If Windows PowerShell is installe d correctly, the cmdlet returns TRUE. Test-Path does not work correctly with all Windows PowerShell providers. Fo r example, you can use Test-Path to test the path to a registry key, but if you use it to test the path to a registry entry, it always returns FALSE, even if the registry entry is present. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113418 about_Providers Convert-Path Split-Path Resolve-Path Join-Path Test-WSMan NAME Test-WSMan SYNOPSIS Tests whether the WinRM service is running on a local or remote computer. SYNTAX Test-WSMan [[-ComputerName] <string>] [-Authentication <Authentication>] [- Credential <PSCredential>] [<CommonParameters>] DESCRIPTION The Test-WSMan cmdlet submits an identification request that determines whe ther the WinRM service is running on a local or remote computer. If the tes ted computer is running the service, the cmdlet displays the WS-Management identity schema, the protocol version, the product vendor, and the product version of the tested service. PARAMETERS -Authentication <Authentication> Specifies the authentication mechanism to be used at the server. Possi ble values are: - Basic: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - Default : Use the authentication method implemented by the WS-Managem ent protocol. - Digest: Digest is a challenge-response scheme that uses a server-spec ified data string for the challenge. - Kerberos: The client computer and the server mutually authenticate by using Kerberos certificates. - Negotiate: Negotiate is a challenge-response scheme that negotiates w ith the server or proxy to determine the scheme to use for authenticati on. For example, this parameter value allows negotiation to determine w hether the Kerberos protocol or NTLM is used. - CredSSP: Use Credential Security Service Provider (CredSSP) authentic ation, which allows the user to delegate credentials. This option is de signed for commands that run on one remote computer but collect data fr om or run additional commands on other remote computers. Caution: CredSSP delegates the user's credentials from the local comput er to a remote computer. This practice increases the security risk of t he remote operation. If the remote computer is compromised, when creden tials are passed to it, the credentials can be used to control the netw ork session. Important: If the authentication parameter is not specified, then the T est-WSMan request will be sent to the remote machine anonymously (witho ut using authentication). If the Test-WSMan request is made anonymousl y, it does not return any information that is specific to the operating -system version. Instead, Test-WSMan displays null values for the oper ating system version and service pack level (OS: 0.0.0 SP: 0.0). Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies the computer against which you want to run the management ope ration. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (.) to specify the local computer. The local computer is the defau lt. When the remote computer is in a different domain from the user, yo u must use a fully qualified domain name must be used. Required? false Position? 1 Default value localhost Accept pipeline input? false Accept wildcard characters? false -Credential <PSCredential> Specifies a user account that has permission to perform this action. Th e default is the current user. Type a user name, such as "User01", "Dom ain01\User01", or User@Domain.com. Or, enter a PSCredential object, suc h as one returned by the Get-Credential cmdlet. When you type a user na me, you will be prompted for a password. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None This cmdlet does not accept any input. OUTPUTS None This cmdlet does not generate any output object. NOTES By default, the Test-WSMan cmdlet queries the WinRM service without usi ng authentication, and it does not return any information that is speci fic to the operating-system version. Instead, it displays null values f or the operating system version and service pack level (OS: 0.0.0 SP: 0 .0). -------------------------- EXAMPLE 1 -------------------------- C:\PS>test-wsman wsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidenti ty.xsd ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd ProductVendor : Microsoft Corporation ProductVersion : OS: 0.0.0 SP: 0.0 Stack: 2.0 Description ----------- This command determines whether the WinRM service is running on the local c omputer or on a remote computer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>test-wsman -computername server01 wsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidenti ty.xsd ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd ProductVendor : Microsoft Corporation ProductVersion : OS: 0.0.0 SP: 0.0 Stack: 2.0 Description ----------- This command determines whether the WinRM service is running on the server0 1 computer named. -------------------------- EXAMPLE 3 -------------------------- C:\PS>test-wsman -authentication default wsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidenti ty.xsd ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd ProductVendor : Microsoft Corporation ProductVersion : OS: 6.0.6001 SP: 1.0 Stack: 2.0 Description ----------- This command tests to see if the WS-Management (WinRM) service is running o n the local computer using the authentication parameter. Using the authentication parameter allows the Test-WSMan cmdlet to return t he Operating System version. -------------------------- EXAMPLE 4 -------------------------- C:\PS>test-wsman -computername server01 -authentication default wsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidenti ty.xsd ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd ProductVendor : Microsoft Corporation ProductVersion : OS: 6.1.7021 SP: 0.0 Stack: 2.0 Description ----------- This command tests to see if the WS-Management (WinRM) service is running o n the computer named server01 using the authentication parameter. Using the authentication parameter allows the Test-WSMan cmdlet to return t he operating system version. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkId=141464 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance New-WSManSessionOption Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Trace-Command NAME Trace-Command SYNOPSIS Configures and starts a trace of the specified expression or command. SYNTAX Trace-Command [-Command] <string> [-ArgumentList <Object[]>] [-Name] <strin g[]> [[-Option] {None | Constructor | Dispose | Finalizer | Method | Proper ty | Delegates | Events | Exception | Lock | Error | Errors | Warning | Ver bose | WriteLine | Data | Scope | ExecutionFlow | Assert | All}] [-Debugger ] [-FilePath <string>] [-Force] [-InputObject <psobject>] [-ListenerOption {None | LogicalOperationStack | DateTime | Timestamp | ProcessId | ThreadId | Callstack}] [-PSHost] [<CommonParameters>] Trace-Command [-Expression] <scriptblock> [-Name] <string[]> [[-Option] {No ne | Constructor | Dispose | Finalizer | Method | Property | Delegates | Ev ents | Exception | Lock | Error | Errors | Warning | Verbose | WriteLine | Data | Scope | ExecutionFlow | Assert | All}] [-Debugger] [-FilePath <strin g>] [-Force] [-InputObject <psobject>] [-ListenerOption {None | LogicalOper ationStack | DateTime | Timestamp | ProcessId | ThreadId | Callstack}] [-PS Host] [<CommonParameters>] DESCRIPTION The Trace-Command cmdlet configures and starts a trace of the specified exp ression or command. It works like Set-TraceSource, except that it applies o nly to the specified command. PARAMETERS -ArgumentList <Object[]> Specifies the parameters and parameter values for the command being tra ced. The alias for ArgumentList is Args. This feature is especially use ful for debugging dynamic parameters. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Command <string> Specifies a command that is being processed during the trace. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -Debugger [<SwitchParameter>] Sends the trace output to the debugger. You can view the output in any user-mode or kernel mode debugger or in Visual Studio. This parameter a lso selects the default trace listener. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Expression <scriptblock> Specifies the expression that is being processed during the trace. Encl ose the expression in curly braces ({}). Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false -FilePath <string> Sends the trace output to the specified file. This parameter also selec ts the file trace listener. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Force [<SwitchParameter>] Allows the cmdlet to append trace information to a read-only file. Used with the FilePath parameter. Even using the Force parameter, the cmdle t cannot override security restrictions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Provides input to the expression that is being processed during the tra ce. You can enter a variable that represents the input that the expression accepts, or pass an object through the pipeline. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -ListenerOption <TraceOptions> Adds optional data to the prefix of each trace message in the output. T he valid values are None, LogicalOperationStack, DateTime, Timestamp, P rocessId, ThreadId, and Callstack. "None" is the default. To specify multiple options, separate them with commas, but with no spa ces, and enclose them in quotation marks, such as "ProcessID,ThreadID". Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string[]> Determines which Windows PowerShell components are traced. Enter the na me of the trace source of each component. Wildcards are permitted. To f ind the trace sources on your computer, type "Get-TraceSource". Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Option <PSTraceSourceOptions> Determines the type of events that are traced. The valid values are None, Constructor, Dispose, Finalizer, Method, Pro perty, Delegates, Events, Exception, Lock, Error, Errors, Warning, Verb ose, WriteLine, Data, Scope, ExecutionFlow, Assert, and All. "All" is t he default. The following values are combinations of other values: -- ExecutionFlow: (Constructor, Dispose, Finalizer, Method, Delegates, Events, and Scope) -- Data: (Constructor, Dispose, Finalizer, Property, Verbose, and Write Line) -- Errors: (Error and Exception). To specify multiple options, separate them with commas, but with no spa ces, and enclose them in quotation marks, such as "Constructor,Dispose" . Required? false Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false -PSHost [<SwitchParameter>] Sends the trace output to the Windows PowerShell host. This parameter a lso selects the PSHost trace listener. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe objects that represent input to the expression to Trace-Co mmand. OUTPUTS System.Management.Automation.PSObject Returns the command trace in the debug stream. NOTES Tracing is a method that developers use to debug and refine programs. W hen tracing, the program generates detailed messages about each step in its internal processing. The Windows PowerShell tracing cmdlets are designed to help Windows Pow erShell developers, but they are available to all users. They let you m onitor nearly every aspect of the functionality of the shell. To find the Windows PowerShell components that are enabled for tracing, type "Get-Help Get-TraceSource." A "trace source" is the part of each Windows PowerShell component that manages tracing and generates trace messages for the component. To trac e a component, you identify its trace source. A "trace listener" receives the output of the trace and displays it to the user. You can elect to send the trace data to a user-mode or kernel -mode debugger, to the host or console, to a file, or to a custom liste ner derived from the System.Diagnostics.TraceListener class. When you use the Command parameter set, Windows PowerShell processes th e command just as it would be processed in a pipeline. For example, com mand discovery is not repeated for each incoming object. The names of the Name, Expression, Option, and Command parameters are o ptional. If you omit the parameter names, the unnamed parameter values must appear in this order: Name, Expression, Option or Name, Command,-O ption . If you include the parameter names, the parameters can appear i n any order. -------------------------- EXAMPLE 1 -------------------------- C:\PS>trace-command -name metadata,parameterbinding,cmdlet -expression {get -process notepad} -pshost Description ----------- This command starts a trace of metadata processing, parameter binding, and cmdlet creation and destruction of the "get-process notepad" expression. It uses the Name parameter to specify the trace sources, the Expression param eter to specify the command, and the PSHost parameter to send the output to the console. Because it does not specify any tracing options or listener o ptions, the command uses the defaults, "All" for the tracing options, and " None" for the listener options. -------------------------- EXAMPLE 2 -------------------------- C:\PS>trace-command -name commandprocessor,pipelineprocessor -command get-a lias -argumentlist "ghy" -option executionflow -listenerOption "timestamp,c allstack" -filepath c:\test\debug.txt Description ----------- This command starts a trace of the command processor and pipeline processor while processing the "get-alias cd" command. It uses the Name parameter to specify the trace sources, the Command parame ter to specify the command, the ArgumentList parameter to specify the param eters of the Get-Alias command, the Option parameter to specify tracing opt ions, and the ListenerOption parameter to specify the fields in the trace m essage prefix. The FilePath parameter sends the output to the C:\Test\Debug .txt file. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$a = "i*" C:\PS> trace-command parameterbinding {get-alias $input} -pshost -inputobje ct $a Description ----------- These commands trace the actions of the ParameterBinding operations of Wind ows PowerShell while it processes a Get-Alias expression that takes input f rom the pipeline. In Trace-Command, the InputObject parameter passes an object to the express ion that is being processed during the trace. The first command stores the string "i*" in the $a variable. The second com mand uses the Trace-Command cmdlet with the ParameterBinding trace source. The PSHost parameter sends the output to the console. The expression being processed is "get-alias $input", where the $input vari able is associated with the InputObject parameter. The InputObject paramete r passes the variable $a to the expression. In effect, the command being pr ocessed during the trace is "get-alias -inputobject $a" or "$a | get-alias" . RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113419 Get-TraceSource Set-TraceSource Undo-Transaction NAME Undo-Transaction SYNOPSIS Rolls back the active transaction. SYNTAX Undo-Transaction [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Undo-Transaction cmdlet rolls back the active transaction. When you rol l back a transaction, the changes made by the commands in the transaction a re discarded and the data is restored to its original form. If the transaction includes multiple subscribers, an Undo-Transaction comma nd rolls back the entire transaction for all subscribers. By default, transactions are rolled back automatically if any command in th e transaction generates an error. However, transactions can be started with a different rollback preference and you can use this cmdlet to roll back t he active transaction at any time. The Undo-Transaction cmdlet is one of a set of cmdlets that support the tra nsactions feature in Windows PowerShell. For more information, see about_Tr ansactions. PARAMETERS -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None This cmdlet does not return any output. NOTES You cannot roll back a transaction that has been committed. You cannot roll back any transaction other than the active transaction. To roll back a different, independent transaction, you must first comm it or roll back the active transaction. Rolling back the transaction ends the transaction. To use a transaction again, you must start a new transaction. -------------------------- EXAMPLE 1 -------------------------- C:\PS>undo-transaction Description ----------- This command rolls back the current (active) transaction. -------------------------- EXAMPLE 2 -------------------------- C:\PS>cd hkcu:\software PS HKCU:\Software> start-transaction PS HKCU:\Software> new-item MyCompany -usetransaction PS HKCU:\Software> undo-transaction Description ----------- This command starts a transaction and then rolls it back. As a result, no c hanges are made to the registry. -------------------------- EXAMPLE 3 -------------------------- C:\PS>cd hkcu:\software PS HKCU:\Software> start-transaction PS HKCU:\Software> new-item MyCompany -usetransaction PS HKCU:\Software> get-transaction RollbackPreference SubscriberCount Status ------------------ --------------- ----- Error 1 Active PS HKCU:\Software> start-transaction PS HKCU:\Software> get-transaction RollbackPreference SubscriberCount Status ------------------ --------------- ----- Error 2 Active PS HKCU:\Software> undo-transaction PS HKCU:\Software> get-transaction RollbackPreference SubscriberCount Status ------------------ --------------- ----- Error 0 RolledBack Description ----------- This example demonstrates that when any subscriber rolls back a transaction , the entire transaction is rolled back for all subscribers. The first command changes the location to the HKCU:\Software registry key. The second command starts a transaction. The third command uses the New-Item cmdlet to create a new registry key. Th e command uses the UseTransaction parameter to include the change in the tr ansaction. The fourth command uses the Get-Transaction cmdlet to get the active transa ction. Notice that the status is Active and the subscriber count is 1. The fifth command uses the Start-Transaction command again. Typically, starting a transaction while another transaction is in progress occurs when a script used by the main transaction includes its own complete transactio n. (This example is done interactively so that you can examine it in stages .) When you enter a Start-Transaction command while another transaction is in progress, the commands join the existing transaction as a new "subscriber" and the subscriber count is incremented. The sixth command uses the Get-Transaction cmdlet to get the active transac tion. Notice that the subscriber count is now 2. The seventh command uses the Undo-Transaction cmdlet to roll back the trans action. This command does not return any objects. The final command is a Get-Transaction command that gets the active (or in this case, the most recently active) transaction. The results show that the transaction is rolled back, and that the subscriber count is 0, showing th at the transaction was rolled back for all subscribers. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135268 about_Transactions about_Providers Start-Transaction Get-Transaction Complete-Transaction Use-Transaction Unregister-Event NAME Unregister-Event SYNOPSIS Cancels an event subscription. SYNTAX Unregister-Event [-SubscriptionId] <int> [-Force] [-Confirm] [-WhatIf] [<Co mmonParameters>] Unregister-Event [-SourceIdentifier] <string> [-Force] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Unregister-Event cmdlet cancels an event subscription that was created by using the Register-EngineEvent, Register-ObjectEvent, or Register-WmiEve nt cmdlet. When an event subscription is canceled, the event subscriber is deleted fro m the session and the subscribed events are no longer added to the event qu eue. When you cancel a subscription to an event created by using the New-Ev ent cmdlet, the new event is also deleted from the session. Unregister-Event does not delete events from the event queue. To delete eve nts, use the Remove-Event cmdlet. PARAMETERS -Force [<SwitchParameter>] Cancels all event subscriptions, including subscriptions that were hidd en by using the SupportEvent parameter of Register-ObjectEvent, Registe r-WmiEvent, and Register-EngineEvent. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SourceIdentifier <string> Cancels event subscriptions that have the specified source identifier. A SourceIdentifier or SubscriptionId parameter must be included in ever y command. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -SubscriptionId <int> Cancels event subscriptions that have the specified subscription identi fier. A SourceIdentifier or SubscriptionId parameter must be included in ever y command. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSEventSubscriber You can pipe the output from Get-EventSubscriber to Unregister-Event. OUTPUTS None This cmdlet does not return any output. NOTES Events, event subscriptions, and the event queue exist only in the curr ent session. If you close the current session, the event queue is disca rded and the event subscription is canceled. Unregister-Event cannot delete events created by using the New-Event cm dlet unless you have subscribed to the event by using the Register-Engi neEvent cmdlet. To delete a custom event from the session, you must rem ove it programmatically or close the session. -------------------------- EXAMPLE 1 -------------------------- C:\PS>unregister-event -sourceIdentifier ProcessStarted Description ----------- This command cancels the event subscription that has a source identifier of "ProcessStarted". To find the source identifier of an event, use the Get-Event cmdlet. To fin d the source identifier of an event subscription, use the Get-EventSubscrib er cmdlet. -------------------------- EXAMPLE 2 -------------------------- C:\PS>unregister-event -subscriptionId 2 Description ----------- This command cancels the event subscription that has a subscription identif ier of 2. To find the subscription identifier of an event subscription, use the Get-E ventSubscriber cmdlet. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-eventsubscriber -force | unregister-event -force Description ----------- This command cancels all event subscriptions in the session. The command uses the Get-EventSubscriber cmdlet to get all event subscriber objects in the session, including the subscribers that are hidden by using the SupportEvent parameter of the event registration cmdlets. It uses a pipeline operator (|) to send the subscriber objects to Unregiste r-Event, which deletes them from the session. To complete the task, the For ce parameter is also required on Unregister-Event. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135269 Register-ObjectEvent Register-EngineEvent Register-WmiEvent Unregister-Event Get-Event New-Event Remove-Event Wait-Event Get-EventSubscriber Unregister-PSSessionConfiguration NAME Unregister-PSSessionConfiguration SYNOPSIS Deletes registered session configurations from the computer. SYNTAX Unregister-PSSessionConfiguration [-Name] <string> [-Force] [-NoServiceRest art] [-Confirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Unregister-PSSessionConfiguration cmdlet deletes registered session con figurations from the computer. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurat ions for their users. If you accidentally delete the default Microsoft.PowerShell or Microsoft.Po werShell32 session configurations, use the Enable-PSRemoting cmdlet to rest ore them. PARAMETERS -Force [<SwitchParameter>] Suppresses all user prompts, and restarts the WinRM service without pro mpting. Restarting the service makes the configuration change effective . To prevent a restart and suppress the restart prompt, use the NoService Restart parameter. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Name <string> Specifies the names of session configurations to delete. Enter one or m ore configuration names. Wildcards are permitted. This parameter is req uired. You can also pipe a session configuration object to Unregister-PSSessio nConfiguration. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -NoServiceRestart [<SwitchParameter>] Does not restart the WinRM service, and suppresses the prompt to restar t the service. By default, when you enter an Unregister-PSSessionConfiguration command , you are prompted to restart the WinRM service to make the change effe ctive. Until the WinRM service is restarted, users can still use the u nregistered session configuration, even though Get-PSSessionConfigurati on does not find it. To restart the WinRM service without prompting, use the Force parameter . To restart the WinRM service manually, use the Restart-Service cmdlet . Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfi guration You can pipe a session configuration object from Get-PSSessionConfigura tion to Unregister-PSSessionConfiguration. OUTPUTS None This cmdlet does not return any objects. NOTES To run this cmdlet on Windows Vista, Windows Server 2008, and later ver sions of Windows, you must start Windows PowerShell with the "Run as ad ministrator" option. -------------------------- EXAMPLE 1 -------------------------- C:\PS>unregister-pssessionconfiguration -name MaintenanceShell Description ----------- This command deletes the MaintenanceShell session configuration from the co mputer. -------------------------- EXAMPLE 2 -------------------------- C:\PS>unregister-pssessionconfiguration -maintenanceShell -force Description ----------- This command deletes the MaintenanceShell session configuration from the co mputer. The command uses the Force parameter to suppress all user messages and to restart the WinRM service without prompting. -------------------------- EXAMPLE 3 -------------------------- C:\PS>unregister-pssessionconfiguration -name * C:\PS> get-pssessionconfiguration -name * | unregister-pssessionconfigurati on Description ----------- These commands delete all of the session configurations on the computer. Th e commands have the same effect and can be used interchangeably. -------------------------- EXAMPLE 4 -------------------------- C:\PS>unregister-pssessionconfiguration -name maintenanceShell -noServiceRe start C:\PS> get-pssessionconfiguration -name maintenanceShell Get-PSSessionConfiguration -name maintenanceShell : No Session Configuratio n matches criteria "maintenanceShell". + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorEx ception + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExcep tion C:\PS> new-pssession -configurationName MaintenanceShell Id Name ComputerName State Configuration Availability -- ---- ------------ ----- ------------- ------------ 1 Session1 localhost Opened MaintenanceShell Available C:\PS> restart-service winrm C:\PS> new-pssession -configurationName MaintenanceShell [localhost] Connecting to remote server failed with the following error mes sage : The WS-Management service cannot process the request. The resource URI (http://schemas.microsoft.com/powershell/MaintenanceShell) was not foun d in the WS-Management catalog. The catalog contains the metadata that desc ribes resour ces, or logical endpoints. For more information, see the about_Remote_Troub leshooting Help topic. + CategoryInfo : OpenError: (System.Manageme....RemoteRunspace :RemoteRunspace) [], PSRemotingTransportException + FullyQualifiedErrorId : PSSessionOpenFailed Description ----------- This example shows the effect of using the NoServiceRestart parameter of Un register-PSSessionConfiguration. This parameter is designed to prevent a se rvice restart, which would disrupt any sessions on the computer. The first command uses the Unregister-PSSessionConfiguration cmdlet to dele tes the MaintenanceShell session configuration. However, because the comman d uses the NoServiceRestart parameter, the WinRM service is not restarted a nd the change is not yet completely effective. The second command uses the Get-PSSessionConfiguration cmdlet to get the Ma intenanceShell session. Because the session has been removed from the WS-Ma nagement resource table, Get-PSSession cannot return it. The third command uses the New-PSSession cmdlet to create a session on the local computer that uses the MaintenanceShell configuration. The command su cceeds. The fourth command uses the Restart-Service cmdlet to restart the WinRM ser vice. The fifth command again uses the New-PSSession cmdlet to create a session t hat uses the MaintenanceShell configuration. This time, the session fails b ecause the MaintenanceShell configuration has been deleted. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=144308 about_Session_Configurations Disable-PSSessionConfiguration Enable-PSSessionConfiguration Get-PSSessionConfiguration Register-PSSessionConfiguration Set-PSSessionConfiguration WS-Management Provider Update-FormatData NAME Update-FormatData SYNOPSIS Updates the formatting data in the current session. SYNTAX Update-FormatData [[-AppendPath] <string[]>] [-PrependPath <string[]>] [-Co nfirm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Update-FormatData cmdlet reloads the formatting data from formatting fi les into the current session. This cmdlet lets you update the formatting da ta without restarting Windows PowerShell. Without parameters, Update-FormatData reloads the formatting files that it loaded previously. You can use the parameters of Update-FormatData to add n ew formatting files to the session. Formatting files are text files in XML format with the format.ps1xml file n ame extension. The formatting data in the files defines the display of Micr osoft .NET Framework objects in the session. When Windows PowerShell starts, it loads the format data from the formattin g files in the Windows PowerShell installation directory ($pshome) into the session. You can use Update-FormatData to reload the formatting data into the current session without restarting Windows PowerShell. This is useful w hen you have added or changed a formatting file, but do not want to interru pt the session. For more information about formatting files in Windows PowerShell, see abou t_Format.ps1xml. PARAMETERS -AppendPath <string[]> Adds the specified formatting files to the session. The files are loade d after Windows PowerShell loads the built-in formatting files. When formatting .NET objects, Windows PowerShell uses the first formatt ing definition that it finds for each .NET type. If you use the AppendP ath parameter, Windows PowerShell searches the data from the built-in f iles before it encounters the formatting data that you are adding. Use this parameter to add a file that formats a .NET object that is not referenced in the built-in formatting files. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PrependPath <string[]> Adds the specified formatting files to the session. The files are loade d before Windows PowerShell loads the built-in formatting files. When formatting .NET objects, Windows PowerShell uses the first formatt ing definition that it finds for each .NET type. If you use the Prepend Path parameter, Windows PowerShell searches the data from the files tha t you are adding before it encounters the formatting data from the buil t-in files. Use this parameter to add a file that formats a .NET object that is als o referenced in the built-in formatting files. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains the append path to Update-FormatDat a. OUTPUTS None The cmdlet does not return any output. NOTES Update-FormatData also updates the formatting data for commands in the session that were imported from modules. If the formatting file for a m odule changes, you can run an Update-FormatData command to update the f ormatting data for imported commands. You do not need to import the mod ule again. -------------------------- EXAMPLE 1 -------------------------- C:\PS>update-formatdata Description ----------- This command reloads the formatting files that it loaded previously. -------------------------- EXAMPLE 2 -------------------------- C:\PS>update-formatdata -appendpath trace.format.ps1xml, log.format.ps1xml Description ----------- This command reloads the formatting files into the session, including two n ew files, Trace.format.ps1xml and Log.format.ps1xml. Because the command uses the AppendPath parameter, the formatting data in t he new files is loaded after the formatting data from the built-in files. The AppendPath parameter is used because the new files contain formatting d ata for objects that are not referenced in the built-in files. -------------------------- EXAMPLE 3 -------------------------- C:\PS>update-formatdata -prependPath c:\test\NewFiles.format.ps1xml # Edit the NewFiles.format.ps1 file. C:\PS> update-formatdata Description ----------- This example shows how to reload a formatting file after you have edited it . The first command adds the NewFiles.format.ps1xml file to the session. It u ses the PrependPath parameter because the file contains formatting data for objects that are referenced in the built-in files. After adding the NewFiles.format.ps1xml file and testing it in these sessio n, the author edits the file. The second command uses the Update-FormatData cmdlet to reload the formatti ng files. Because the NewFiles.format.ps1xml file was previously loaded, Up date-FormatData automatically reloads it without using parameters. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113420 Update-List NAME Update-List SYNOPSIS Adds items to and removes items from a property value that contains a colle ction of objects. SYNTAX Update-List [-Add <Object[]>] [-Remove <Object[]>] [[-Property] <string>] [ -InputObject <psobject>] [<CommonParameters>] Update-List -Replace <Object[]> [[-Property] <string>] [-InputObject <psobj ect>] [<CommonParameters>] DESCRIPTION The Update-List cmdlet adds items to and removes items from a property valu e of an object, and then it returns the updated object. This cmdlet is desi gned for properties that contain collections of objects. The Add and Remove parameters add individual items to and remove them from the collection. The Replace parameter replaces the entire collection. If you do not specify a property in the command, Update-List returns an obj ect that describes the update instead of updating the object. You can submi t the update object to cmdlets that change objects, such as Set-* cmdlets. This cmdlet works only when the property that is being updated supports the IList interface that Update-List uses. Also, any Set-* cmdlets that accept an update must support the IList interface. The core cmdlets that are inst alled with Windows PowerShell do not support this interface. To determine w hether a cmdlet supports Update-List, see the cmdlet Help topic. PARAMETERS -Add <Object[]> Specifies the property values to be added to the collection. Enter the values in the order that they should appear in the collection. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be updated. You can also pipe the object to be updated to Update-List. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Property <string> Identifies the property that contains the collection that is being upda ted. If you omit this parameter, Update-List returns an object that rep resents the change instead of changing the object. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Remove <Object[]> Specifies the property values to be removed from the collection. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Replace <Object[]> Specifies a new collection. This parameter replaces all items in the or iginal collection with the items specified by this parameter. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe the objects to be updated to Update-List. OUTPUTS Objects or System.Management.Automation.PSListModifier Update-List returns the updated object, or it returns an object that re presents the update action. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-mailbox | update-list -Property aliases -Add "A","B" -Remove "X", "Y" | set-mailbox Description ----------- This command adds A and B and removes X and Y from the Aliases property of a mailbox. The command uses the Get-MailBox cmdlet from Microsoft Exchange Server to g et the mailbox. A pipeline operator sends the mailbox object to the Update- List cmdlet. The Update-List command uses the Property parameter to indicate that the Al iases property of the mailbox is being updated, and it uses the Add and Rem ove parameters to specify the items that are being added and removed from t he collection. The Aliases property fulfills the conditions of Update-List, because it stores a collection of Microsoft .NET Framework objects that ha ve Add and Remove methods. The Update-List cmdlet returns the updated mailbox, which is piped to the S et-MailBox cmdlet, which changes the mailbox. For more information about Get-Mailbox, see http://go.microsoft.com/fwlink/ ?LinkId=111536. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$m = get-mailbox C:\PS> update-list -InputObject $m -Property aliases -Add "A","B" -Remove " X", "Y" | set-mailbox Description ----------- This command adds A and B to the value of the Aliases property of a mailbox and removes X and Y. This command has the same effect as the previous comm and, although it has a slightly different format. The command uses the Get-MailBox cmdlet to get the mailbox, and it saves th e mailbox in the $m variable. This command uses the InputObject parameter o f Update-List to specify the mailbox. The value of InputObject is the mailb ox in the $m variable. It uses the Property parameter to specify the Aliase s property and the Add and Remove parameters to specify the items being add ed to and removed from the value of Aliases. The command uses a pipeline operator (|) to send the updated mailbox object to the Set-Mailbox cmdlet, which changes the mailbox. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-mailbox | set-mailbox -alias (update-list -Add "A", "B" -Remove " X","Y") Description ----------- This command adds A and B to the value of the Aliases property of a mailbox and removes X and Y. This command has the same effect as the two previous commands, but it uses a different procedure to perform the task. Instead of updating the Aliases property of the mailbox before sending it t o Set-Mailbox, this command uses Update-List to create an object that repre sents the change. Then it submits the change to the Alias parameter of Set- Mailbox. The command uses the Get-MailBox cmdlet to get the mailbox. A pipeline oper ator sends the mailbox object to the Set-Mailbox cmdlet, which changes mail boxes. The command uses the Alias parameter of Set-Mailbox to change the Aliases p roperty of the mailbox object. The value of the Alias parameter is an Updat e-List command that creates an object that represents the update. The Updat e-List command is enclosed in parentheses to ensure that it runs before the value of the Alias parameter is evaluated. When the Set-Mailbox command co mpletes, the mailbox is changed. -------------------------- EXAMPLE 4 -------------------------- C:\PS>update-list -InputObject $a -Property aliases -replace "A", "B" | set -mailbox Description ----------- This command uses the Replace operator of Update-List to replace the collec tion in the Aliases property of the object in $a with a new collection. This command uses the InputObject parameter which, in this case, is equival ent to using a pipeline operator to pass $a to Update-List. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113447 Select-Object Update-TypeData NAME Update-TypeData SYNOPSIS Updates the current extended type configuration by reloading the *.types.ps 1xml files into memory. SYNTAX Update-TypeData [[-AppendPath] <string[]>] [-PrependPath <string[]>] [-Conf irm] [-WhatIf] [<CommonParameters>] DESCRIPTION The Update-TypeData cmdlet updates the current extended type configuration by reloading the *.types.ps1xml files into memory. Extended type informatio n is normally loaded when Windows PowerShell requires the type information it contains. The Update-TypeData cmdlet can be used to preload all type inf ormation. It is particularly useful when you are developing types and want to load those new types for testing purposes. For more information about the *types.ps1xml files in Windows PowerShell, s ee about_Types.ps1xml. PARAMETERS -AppendPath <string[]> Specifies the path to the optional .ps1xml files that will be included in the list of files loaded. These are processed after the built-in fil es are loaded. Required? false Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -PrependPath <string[]> Specifies the path to the optional .ps1xml files that will be included in the list of files loaded. However, these files are processed in the order they are specified and before the built-in files are loaded. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Confirm [<SwitchParameter>] Prompts you for confirmation before executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -WhatIf [<SwitchParameter>] Describes what would happen if you executed the command without actuall y executing the command. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains the append path to Update-TypeData. OUTPUTS None This cmdlet does not return any output. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>update-typedata Description ----------- This example updates the extended type configuration from the *.types.ps1xm l files. -------------------------- EXAMPLE 2 -------------------------- C:\PS>update-typedata -prependpath typesA.types.Ps1xml, typesB.types.Ps1xml Description ----------- This example updates the extended type configuration from the *.types.ps1xm l files, processing the typesA and typesB files first. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113421 Use-Transaction NAME Use-Transaction SYNOPSIS Adds the script block to the active transaction. SYNTAX Use-Transaction [-TransactedScript] <scriptblock> [-UseTransaction] [<Commo nParameters>] DESCRIPTION The Use-Transaction cmdlet adds a script block to an active transaction. Th is enables you to do transacted scripting using transaction-enabled Microso ft .NET Framework objects. The script block can contain only transaction-en abled .NET Framework objects, such as instances of the Microsoft.PowerShell .Commands.Management.TransactedString class. The UseTransaction parameter, which is optional for most cmdlets, is requir ed when using this cmdlet. The Use-Transaction cmdlet is one of a set of cmdlets that support the tran sactions feature in Windows PowerShell. For more information, see about_Tra nsactions. PARAMETERS -TransactedScript <scriptblock> Specifies the script block that is run in the transaction. Enter any va lid script block enclosed in braces ( { } ). This parameter is required . Required? true Position? 1 Default value None Accept pipeline input? false Accept wildcard characters? false -UseTransaction [<SwitchParameter>] Includes the command in the active transaction. This parameter is valid only when a transaction is in progress. For more information, see abou t_Transactions. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS PSObject Use-Transaction returns the result of the transaction. NOTES The Use-Transaction parameter includes the command in the active transa ction. Because the Use-Transaction cmdlet is always used in transaction s, this parameter is required to make any Use-Transaction command effec tive. -------------------------- EXAMPLE 1 -------------------------- C:\PS>start-transaction C:\PS> $transactedString = New-Object Microsoft.PowerShell.Commands.Managem ent.TransactedString C:\PS> $transactedString.Append("Hello") C:\PS> use-transaction -TransactedScript { $transactedString.Append(", Worl d") } -UseTransaction C:\PS> $transactedString.ToString() Hello C:\PS> use-transaction -transactedScript { $transactedString.ToString() } - UseTransaction Hello, World C:\PS> complete-transaction C:\PS> $transactedString.ToString() Hello, World Description ----------- This example shows how to use the Use-Transaction cmdlet to script against a transaction-enabled .NET Framework object. In this case, the object is a TransactedString object. The first command uses the Start-Transaction cmdlet to start a transaction. The second command uses the New-Object command to create a TransactedString object. It stores the object in the $TransactedString variable. The third and fourth commands both use the Append method of the TransactedS tring object to add text to the value of $TransactedString. One command is part of the transaction; the other is not. The third command uses the Append method of the transacted string to add "H ello" to the value of $TransactedString. Because the command is not part of the transaction, the change is applied immediately. The fourth command uses the Use-Transaction cmdlet to add text to the strin g within the transaction. The command uses the Append method to add ", Worl d" to the value of $TransactedString. The command is enclosed in braces ( { } ) to make it a script block. The UseTransaction parameter is required in this command. The fifth and sixth commands use the ToString method of the TransactedStrin g object to display the value of the TransactedString as a string. Again, o ne command is part of the transaction; the other is not. The fifth command uses the ToString method to display the current value of the $TransactedString variable. Because it is not part of the transaction, it displays only the current state of the string. The sixth command uses the Use-Transaction cmdlet to run the same command w ithin the transaction. Because the command is part of the transaction, it d isplays the current value of the string within the transaction, much like a preview of the transaction changes. The seventh command uses the Complete-Transaction cmdlet to commit the tran saction. The final command uses the ToString method to display the resulting value o f the variable as a string. -------------------------- EXAMPLE 2 -------------------------- C:\PS>start-transaction C:\PS> $transactedString = New-Object Microsoft.PowerShell.Commands.Managem ent.TransactedString C:\PS> $transactedString.Append("Hello") C:\PS> use-transaction -TransactedScript { $transactedString.Append(", Worl d") } -UseTransaction C:\PS> undo-transaction C:\PS> $transactedString.ToString() Hello Description ----------- This example shows the effect of rolling back a transaction that includes U se-Transaction commands. Like all commands in a transaction, when the trans action is rolled back, the transacted changes are discarded and the data is unchanged. The first command uses the Start-Transaction cmdlet to start a transaction. The second command uses the New-Object command to create a TransactedString object. It stores the object in the $TransactedString variable. The third command, which is not part of the transaction, uses the Append me thod to add "Hello" to the value of $TransactedString. The fourth command uses the Use-Transaction cmdlet to run another command t hat uses the Append method within the transaction. The command uses the App end method to add ", World" to the value of $TransactedString. The fifth command uses the Undo-Transaction cmdlet to roll back the transac tion. As a result, all commands performed within the transaction are revers ed. The final command uses the ToString method to display the resulting value o f $TransactedString as a string. The results show that only the changes mad e outside of the transaction were applied to the object. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135271 about_Transactions Start-Transaction Get-Transaction Complete-Transaction Undo-Transaction Variable PROVIDER NAME Variable DRIVES Variable: SYNOPSIS Provides access to the Windows PowerShell variables and to their values. DESCRIPTION The Windows PowerShell Variable provider lets you get, add, change, clear, and delete Windows PowerShell variables in the current console. The Windows PowerShell Variable provider supports the variables that Window s PowerShell creates, including the automatic variables, the preference var iables, and the variables that you create. The Variable provider is a flat namespace that contains only the variable o bjects. The variables have no child items. Most of the variables are instances of the System.Management.Automation.PSV ariable class. However, there are some variations. For example, the "?" var iable is a member of the QuestionMarkVariable class, and the "MaximumVariab leCount" variable is a member of the SessionStateCapacityVariable class. The Variable provider exposes its data store in the Variable: drive. To wor k with variables, you can change your location to the Variable: drive ("set -location variable:"), or you can work from any other Windows PowerShell dr ive. To reference a variable from another location, use the drive name (Var iable:) in the path. Windows PowerShell includes a set of cmdlets designed especially to view an d to change variables: -- Get-Variable -- New-Variable -- Set-Variable -- Remove-Variable -- Clear-Variable When you use these cmdlets, you do not need to specify the Variable: drive in the name. The Variable provider supports all of the cmdlets whose names contain the I tem noun (the Item cmdlets), except for Invoke-Item. The Variable provider supports the Get-Content and Set-Content cmdlets. However, it does not supp ort the cmdlets whose names contain the ItemProperty noun (the ItemProperty cmdlets), and it does not support the Filter parameter in any cmdlet. You can also use the Windows PowerShell expression parser to create, view, and change the values of variables without using the cmdlets. When working with variables directly, use a dollar sign ($) to identify the name as a va riable and the assignment operator (=) to establish and change its value. F or example, "$p = get-process" creates the "p" variable and stores the resu lts of a "get-process" command in it. All changes to the variables affect the current session only. To save the c hanges, add the changes to the Windows PowerShell profile, or use Export-Co nsole to save the current console. CAPABILITIES TASKS TASK: Getting to the Variable: Drive -------------------------- EXAMPLE 1 -------------------------- This command changes the current location to the Variable: drive. You c an use this command from any drive in Windows PowerShell. To return to a file system drive, type the drive name. For example, type "set-locati on c:". set-location variable: TASK: Displaying the Value of Variables -------------------------- EXAMPLE 1 -------------------------- This command gets the list of all the variables and their values in the current session. You can use this command from any Windows PowerShell drive. get-childitem -path variable: -------------------------- EXAMPLE 2 -------------------------- This command gets the variables with names that begin with "max". You c an use this command from any Windows PowerShell drive. get-childitem -path variable:max* If you are in the Variable: drive, you can omit the drive name from the path. -------------------------- EXAMPLE 3 -------------------------- This command gets the value of the WhatIfPreference variable by typing it at the command line. The name of the variable is preceded by a dollar sign ($) to indicate t hat it is a variable. The Variable: drive name is not specified. $WhatIfPreference -------------------------- EXAMPLE 4 -------------------------- This command uses the LiteralPath parameter of Get-ChildItem to get the value of the "?" variable from within the Variable: drive. Get-ChildIt em does not attempt to resolve any wildcards in the values of the Liter alPath parameter. get-childitem -literalpath ? To display the value of a variable with a special character name withou t a cmdlet, type a dollar sign ($) and the variable name. For example, to display the value of the "?" variable, type "$?". -------------------------- EXAMPLE 5 -------------------------- This command gets the variables that have the values of "ReadOnly" or " Constant" for their Options property. get-childitem -path variable: | where-object {$_.options -match "Consta nt" -or $_.options -match "ReadOnly"} | format-list -property name, val ue, options TASK: Creating a New Variable -------------------------- EXAMPLE 1 -------------------------- This command creates the "services" variable and stores the results of a Get-Service command in it. Because the current location is in the Var iable: drive, the value of the Path parameter is a dot (.), which repre sents the current location. The parentheses around the Get-Service command ensure that the command is executed before the variable is created. Without the parentheses, th e value of the new variable is a "Get-Service" string. new-item -path . -name services -value (Get-Service) If you are not in the variable: drive, include the Variable: drive name in the path. -------------------------- EXAMPLE 2 -------------------------- This command creates a "services" variable and stores the result of a G et-Service command in it. The command uses a dollar sign ($) to indicate a variable and the assig nment operator (=) to assign the result of the Get-Service command to t he newly created variable. $services = Get-Service To create a variable without a value, omit the assignment operator. TASK: Displaying the Properties and Methods of Variables -------------------------- EXAMPLE 1 -------------------------- This command uses the Get-Item cmdlet to get all variables. The pipelin e operator (|) sends the results to the Get-Member cmdlet, which displa ys the methods and properties of the object. get-item -path variable:* | get-member When you pipe a collection of objects (such as the collection of variab les in the Variable: drive) to Get-Member, Get-Member evaluates each ob ject in the collection separately and returns information about each of the object types that it finds. To get information about the collection of objects in the Variable: dri ve, use the InputObject parameter of Get-Member. For example, "get-memb er -inputobject (get-item variable:*)". When you use InputObject, Get-M ember evaluates the collection, not the objects in the collection. -------------------------- EXAMPLE 2 -------------------------- This command lists the values of the properties of the "home" variable. It uses the Get-Item cmdlet to get an object that represents the "home " variable. The pipeline operator (|) sends the results to the Format-L ist command. The Format-List command uses the Property parameter with a wildcard character (*) to format and to display the values of all of t he properties of the "home" variable. get-item variable:home | format-list -property * TASK: Changing the Properties of a Variable -------------------------- EXAMPLE 1 -------------------------- This command uses the Rename-Item cmdlet to change the name of the "a" variable to "processes". rename-item -path variable:a -newname processes -------------------------- EXAMPLE 2 -------------------------- This command uses the Set-Item cmdlet to change the value of the ErrorA ctionPreference variable to "Stop". set-item -path variable:ErrorActionPreference -value Stop -------------------------- EXAMPLE 3 -------------------------- This command changes the value of the ErrorActionPreference variable to "Stop". It uses a dollar sign ($) to indicate a variable and the assignment ope rator (=) to assign the value. $ErrorActionPreference = Stop TASK: Copying a Variable -------------------------- EXAMPLE 1 -------------------------- This command uses the Copy-Item cmdlet to copy the "processes" variable to "old_processes". This creates a new variable named "old_processes" that has the same value as the "processes" variable. copy-item -path variable:processes -destination variable:old_processes If the command is issued from within the Variable: drive, you can omit the drive name from the value of the Path parameter. -------------------------- EXAMPLE 2 -------------------------- This command copies the "processes" variable to "old_processes" without using a cmdlet. It uses the dollar sign ($) to indicate variables and the assignment operator to assign the value of $processes to old_proces ses. $old_processes = $processes TASK: Deleting a Variable -------------------------- EXAMPLE 1 -------------------------- This command deletes the "serv" variable from the current session. You can use this command in any Windows PowerShell drive. remove-variable -path variable:serv -------------------------- EXAMPLE 2 -------------------------- This command deletes all variables from the current session except for the variables whose Options property has a value of Constant. Without t he Force parameter, the command does not delete variables whose Options property has a value of ReadOnly. remove-item variable:* -force TASK: Setting the Value of a Variable to NULL -------------------------- EXAMPLE 1 -------------------------- This command uses the Clear-Item cmdlet to change the value of the "pro cesses" variable to NULL. clear-item -path variable:processes -------------------------- EXAMPLE 2 -------------------------- This command clears the value of the "processes" variable by assigning a null value to it. It uses the $null automatic variable to represent t he NULL value. $processes = $null DYNAMIC PARAMETERS NOTES The Variable provider does not support any dynamic parameters. RELATED LINKS about_Variables about_Automatic_Variables about_Providers Wait-Event NAME Wait-Event SYNOPSIS Waits until a particular event is raised before continuing to run. SYNTAX Wait-Event [[-SourceIdentifier] <string>] [-Timeout <int>] [<CommonParamete rs>] DESCRIPTION The Wait-Event cmdlet suspends execution of a script or function until a pa rticular event is raised. Execution resumes when the event is detected. To cancel the wait, press CTRL+C. This feature provides an alternative to polling for an event. It also allow s you to determine the response to an event in two different ways: by using the Action parameter of the event subscription and by waiting for an event to return and then respond with an action. PARAMETERS -SourceIdentifier <string> Waits only for events with the specified source identifier. By default, Wait-Events waits for any event. Required? false Position? 1 Default value All events Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Timeout <int> Determines the maximum time, in seconds, that Wait-Event waits for the event to occur. The default, -1, waits indefinitely. The timing starts when you submit the Wait-Event command. If the specified time is exceeded, the wait ends and the command prompt returns, even if the event has not been raised. No error message is di splayed. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String OUTPUTS System.String NOTES Events, event subscriptions, and the event queue exist only in the curr ent session. If you close the current session, the event queue is disca rded and the event subscription is canceled. -------------------------- EXAMPLE 1 -------------------------- C:\PS>wait-event Description ----------- This command waits for the next event that is raised. -------------------------- EXAMPLE 2 -------------------------- C:\PS>wait-event -sourceIdentifier "ProcessStarted" Description ----------- This command waits for the next event that is raised and that has a source identifier of "ProcessStarted". -------------------------- EXAMPLE 3 -------------------------- C:\PS>$timer.Interval = 2000 C:\PS> $timer.Autoreset = $false C:\PS> $timer.Enabled = $true; Wait-Event Timer.Elapsed # After 2 seconds EventIdentifier : 12 Sender : System.Timers.Timer SourceEventArgs : System.Timers.ElapsedEventArgs SourceArgs : {System.Timers.Timer, System.Timers.ElapsedEventArgs} SourceIdentifier : Timer.Elapsed TimeGenerated : 6/10/2008 3:24:18 PM MessageData : ForwardEvent : False Description ----------- This command uses the Wait-Event cmdlet to wait for a timer event on a time r that is set for 2000 milliseconds. -------------------------- EXAMPLE 4 -------------------------- C:\PS>wait-event -sourceIdentifier "ProcessStarted" -timeout 90 Description ----------- This command waits up to 90 seconds for the next event that is raised and t hat has a source identifier of "ProcessStarted". If the specified time expi res, the wait ends. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135276 Register-ObjectEvent Register-EngineEvent Register-WmiEvent Unregister-Event Get-Event New-Event Remove-Event Wait-Event Get-EventSubscriber Wait-Job NAME Wait-Job SYNOPSIS Suppresses the command prompt until one or all of the Windows PowerShell ba ckground jobs running in the session are complete. SYNTAX Wait-Job [[-InstanceId] <Guid[]>] [-Any] [-Timeout <int>] [<CommonParameter s>] Wait-Job [-Job] <Job[]> [-Any] [-Timeout <int>] [<CommonParameters>] Wait-Job [[-Name] <string[]>] [-Any] [-Timeout <int>] [<CommonParameters>] Wait-Job [-Id] <Int32[]> [-Any] [-Timeout <int>] [<CommonParameters>] Wait-Job [-State {NotStarted | Running | Completed | Failed | Stopped | Blo cked}] [-Any] [-Timeout <int>] [<CommonParameters>] DESCRIPTION The Wait-Job cmdlet waits for Windows PowerShell background jobs to complet e before it displays the command prompt. You can wait until any background job is complete, or until all background jobs are complete, and you can set a maximum wait time for the job. You can use Wait-Job to get background jobs that were started by using Star t-Job or the AsJob parameter of Invoke-Command. When the commands in the job are complete, Wait-Job displays the command pr ompt and returns a job object so that you can pipe it to another command. PARAMETERS -Any [<SwitchParameter>] Displays the command prompt (and returns the job object) when any job c ompletes. By default, Wait-Job waits until all of the specified jobs ar e complete before displaying the prompt. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Id <Int32[]> Waits for jobs with the specified IDs. The ID is an integer that uniquely identifies the job within the curren t session. It is easier to remember and type than the InstanceId, but i t is unique only within the current session. You can type one or more I Ds (separated by commas). To find the ID of a job, type "Get-Job" witho ut parameters. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InstanceId <Guid[]> Waits for jobs with the specified instance IDs. The default is all jobs . An instance ID is a GUID that uniquely identifies the job on the comput er. To find the instance ID of a job, use Get-Job. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Job <Job[]> Waits for the specified jobs. Enter a variable that contains the job ob jects or a command that gets the job objects. You can also use a pipeli ne operator to send job objects to the Wait-Job cmdlet. By default, Wai t-Job waits for all jobs created in the current session. Required? true Position? 1 Default value Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? false -Name <string[]> Waits for jobs with the specified friendly name. Required? false Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -State <JobState> Waits for jobs in the specified state. Valid values are NotStarted, Run ning, Completed, Stopped, Failed, and Blocked. Required? false Position? named Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Timeout <int> Determines the maximum wait time for each background job, in seconds. T he default, -1, waits until the job completes, no matter how long it ru ns. The timing starts when you submit the Wait-Job command, not the Sta rt-Job command. If this time is exceeded, the wait ends and the command prompt returns, even if the job is still running. No error message is displayed. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.RemotingJob You can pipe a job object to Wait-Job. OUTPUTS System.Management.Automation.RemotingJob Wait-Job returns job objects that represent the completed jobs. If the wait ends because the value of the Timeout parameter is exceeded, Wait- Job does not return any objects. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-job | wait-job Description ----------- This command waits for all of the background jobs running in the session to complete. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$s = new-pssession server01, server02, server03 C:\PS> invoke-command -session $s -scriptblock {start-job -name Date1 -scri ptblock {get-date}} C:\PS> $done = invoke-command -session $s -command {wait-job -name Date1} C:\PS> $done.count 3 Description ----------- This example shows how to use the Wait-Job cmdlet with jobs started on remo te computers by using the Start-Job cmdlet. Both the Start-Job and Wait-Job commands are submitted to the remote computer by using the Invoke-Command cmdlet. This example uses Wait-Job to determine whether a Get-Date command running as a background job on three different computers is complete. The first command creates a Windows PowerShell session (PSSession) on each of the three remote computers and stores them in the $s variable. The second command uses the Invoke-Command cmdlet to run a Start-Job comman d in each of the three sessions in $s. All of the jobs are named Date1. The third command uses the Invoke-Command cmdlet to run a Wait-Job command. This command waits for the Date1 jobs on each computer to complete. It sto res the resulting collection (array) of job objects in the $done variable. The fourth command uses the Count property of the array of job objects in t he $done variable to determine how many of the jobs are complete. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$s = new-pssession (get-content machines.txt) C:\PS> $c = 'get-eventlog -log system | where {$_.EntryType -eq "error" -an d $_.Source -eq "LSASRV"} | out-file errors.txt' C:\PS> invoke-command -session $s -scriptblock {param($c)start-job -scriptb lock {$c}} -ArgumentList $c C:\PS> invoke-command -session $s -scriptblock {wait-job -any} Description ----------- This example uses the Any parameter of Wait-Job to determine when the first of many background jobs running in the current session are complete. It al so shows how to use the Wait-Job cmdlet to wait for remote jobs to complete . The first command creates a PSSession on each of the computers listed in th e Machines.txt file and stores the PSSessions in the $s variable. The comma nd uses the Get-Content cmdlet to get the contents of the file. The Get-Con tent command is enclosed in parentheses to ensure that it runs before the N ew-PSSession command. The second command stores a Get-EventLog command string (in quotation marks ) in the $c variable. The third command uses the Invoke-Command cmdlet to run a Start-Job command in each of the sessions in $s. The Start-Job command starts a background j ob that runs the command in $c. Because the $c variable is on the local computer, the command uses the "par am" keyword to declare the local variables in the command and the ArgumentL ist parameter to supply the values for those variables. The fourth command uses the Invoke-Command cmdlet to run a Wait-Job command in the sessions. It uses the Wait-Job cmdlet to wait until the first job o n the remote computers is complete. -------------------------- EXAMPLE 4 -------------------------- C:\PS>$s = new-pssession Server01, Server02, Server03 C:\PS> $jobs = invoke-command -session $s -scriptblock {start-job -script { get-date}} C:\PS> $done = invoke-command -session $s -scriptblock {wait-job -timeout 3 0} Description ----------- This example shows how to use the Timeout parameter of Wait-Job to set a ma ximum wait time for the jobs running on remote computers. The first command creates a PSSession on each of three remote computers (Se rver01, Server02, and Server03), and it saves the PSSessions in the $s vari able. The second command uses the Invoke-Command cmdlet to run a Start-Job comman d in each of the PSSessions in $s. It saves the resulting job objects in th e $jobs variable. The third command uses the Invoke-Command cmdlet to run a Wait-Job command in each of the PSSessions in $s. The Wait-Job command determines whether al l of the commands have completed within 30 seconds. It uses the Timeout par ameter with a value of 30 (seconds) to establish the maximum wait time and saves the results of the command in the $done variable. In this case, after 30 seconds, only the command on the Server02 computer h as completed. Wait-Job ends the wait, displays the command prompt, and retu rns the object that represents the job that was completed. The $done variable contains a job object that represents the job that ran o n Server02. -------------------------- EXAMPLE 5 -------------------------- C:\PS>wait-job -id 1,2,5 -any Description ----------- This command identifies three jobs by their IDs and waits until any of them are complete. The command prompt returns when the first job completes. -------------------------- EXAMPLE 6 -------------------------- C:\PS>wait-job -name DailyLog -timeout 120 Description ----------- This command waits 120 seconds (two minutes) for the DailyLog job to comple te. If the job does not complete in the next two minutes, the command promp t returns anyway, and the job continues to run in the background. -------------------------- EXAMPLE 7 -------------------------- C:\PS>wait-job -name Job3 Description ----------- This Wait-Job command uses the job name to identify the job to wait for. -------------------------- EXAMPLE 8 -------------------------- C:\PS>C:\PS> $j = start-job -script {get-childitem *.ps1| where {$_lastwrit etime -gt ((get-date) - (new-timespan -days 7))}} C:\PS> $j | wait-job Description ----------- This example shows how to use the Wait-Job cmdlet with jobs started on the local computer by using the Start-Job cmdlet. These commands start a job that gets the Windows PowerShell script files th at were added or updated in the last week. The first command uses the Start-Job cmdlet to start a background job on th e local computer. The job runs a Get-ChildItem command that gets all of the files with a ".ps1" file name extension that were added or updated in the last week. The third command uses the Wait-Job cmdlet to wait until the job is complet e. When the job completes, the command displays the job object, which conta ins information about the job. -------------------------- EXAMPLE 9 -------------------------- C:\PS>$s = new-pssession Server01, Server02, Server03 C:\PS> $j = invoke-command -session $s -scriptblock {get-process} -asjob C:\PS> $j | wait-job Description ----------- This example shows how to use the Wait-Job cmdlet with jobs started on remo te computers by using the AsJob parameter of the Invoke-Command cmdlet. Whe n using AsJob, the job is created on the local computer and the results are automatically returned to the local computer, even though the job runs on the remote computers. This example uses Wait-Job to determine whether a Get-Process command runni ng in the sessions on three remote computers is complete. The first command creates PSSessions on three computers and stores them in the $s variable. The second command uses the Invoke-Command cmdlet to run a Get-Process comm and in each of the three PSSessions in $s. The command uses the AsJob param eter to run the command asynchronously as a background job. The command ret urns a job object, just like the jobs started by using Start-Job, and the j ob object is stored in the $j variable. The third command uses a pipeline operator (|) to send the job object in $j to the Wait-Job cmdlet. Notice that an Invoke-Command command is not requi red in this case, because the job resides on the local computer. -------------------------- EXAMPLE 10 -------------------------- C:\PS>get-job Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job1 Completed True localhost,server01.. get-service 4 Job4 Completed True localhost dir | where C:\PS> wait-job -id 1 Description ----------- This command waits for the job with an ID value of 1. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113422 about_Jobs about_Job_Details about_Remote_Jobs Start-Job Get-Job Receive-Job Stop-Job Remove-Job Invoke-Command Wait-Process NAME Wait-Process SYNOPSIS Waits for the processes to be stopped before accepting more input. SYNTAX Wait-Process [-Id] <Int32[]> [[-Timeout] <int>] [<CommonParameters>] Wait-Process -InputObject <Process[]> [[-Timeout] <int>] [<CommonParameters >] Wait-Process [-Name] <string[]> [[-Timeout] <int>] [<CommonParameters>] DESCRIPTION The Wait-Process cmdlet waits for one or more running processes to be stopp ed before accepting input. In the Windows PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can spec ify a process by process name or process ID (PID), or pipe a process object to Wait-Process. Wait-Process works only on processes running on the local computer. PARAMETERS -Id <Int32[]> Specifies the process IDs of the processes. To specify multiple IDs, us e commas to separate the IDs. To find the PID of a process, type "get-p rocess". The parameter name ("Id") is optional. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -InputObject <Process[]> Specifies the processes by submitting process objects. Enter a variable that contains the process objects, or type a command or expression tha t gets the process objects, such as a Get-Process command. Required? true Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false -Name <string[]> Specifies the process names of the processes. To specify multiple names , use commas to separate the names. Required? true Position? 1 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? false -Timeout <int> Determines the maximum time, in seconds, that Wait-Process waits for th e specified processes to stop. When this interval expires, the command displays a non-terminating error that lists the processes that are stil l running, and ends the wait. Required? false Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Diagnostics.Process You can pipe a process object to Wait-Process. OUTPUTS None This cmdlet does not generate any output. NOTES This cmdlet uses the WaitForExit method of the System.Diagnostics.Proce ss class. For more information about this method, see the Microsoft .NE T Framework SDK. -------------------------- EXAMPLE 1 -------------------------- C:\PS>$nid = (get-process notepad).id C:\PS> stop-process -id $nid C:\PS> wait-process -id $nid Description ----------- These commands stop the Notepad process and then wait for the process to be stopped before proceeding with the next command. The first command uses the Get-Process cmdlet to get the ID of the Notepad process. It saves it in the $nid variable. The second command uses the Stop-Process cmdlet to stop the process with th e ID saved in $nid. The third command uses the Wait-Process cmdlet to wait until the Notepad pr ocess is stopped. It uses the ID parameter of Wait-Process to identify the process. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$p = get-process notepad C:\PS> wait-process -id $p.id C:\PS> wait-process -name notepad C:\PS> wait-process -inputobject $p Description ----------- These commands show three different methods of specifying a process to the Wait-Process cmdlet. The first command gets the Notepad process and saves i t in the $p variable. The second command uses the ID parameter, the third command uses the Name p arameter, and the fourth command uses the InputObject parameter. These commands have the same results and can be used interchangeably. -------------------------- EXAMPLE 3 -------------------------- C:\PS>wait-process -name outlook, winword -timeout 30 Description ----------- This command waits 30 seconds for the Outlook and Winword processes to stop . If both processes are not stopped, the cmdlet displays a non-terminating error and the command prompt. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135277 Get-Process Start-Process Stop-Process Wait-Process Debug-Process Where-Object NAME Where-Object SYNOPSIS Creates a filter that controls which objects will be passed along a command pipeline. SYNTAX Where-Object [-FilterScript] <scriptblock> [-InputObject <psobject>] [<Comm onParameters>] DESCRIPTION The Where-Object cmdlet selects objects from the set of objects that are pa ssed to it. It uses a script block as a filter and evaluates the script blo ck for each object. If the result of the evaluation is True, the object is returned. If the result of the evaluation is not True, the object is ignore d. PARAMETERS -FilterScript <scriptblock> Specifies the script block that is used to filter the objects. Enclose the script block in braces ( {} ). Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -InputObject <psobject> Specifies the objects to be filtered. You can also pipe the objects to Where-Object. Required? false Position? named Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe the objects to be filtered to Where-Object. OUTPUTS NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-service | where-object {$_.Status -eq "Stopped"} Description ----------- This command gets a list of all services that are currently stopped. The "$ " symbol represents each object that is passed to the Where-Object cmdlet. -------------------------- EXAMPLE 2 -------------------------- C:\PS>get-process | where-object {$_.workingset -gt 25000*1024} Description ----------- This command lists processes that have a working set greater than 25,000 ki lobytes (KB). Because the value of the WorkingSet property is stored in byt es, the value of 25,000 is multiplied by 1,024. -------------------------- EXAMPLE 3 -------------------------- C:\PS>get-process | where-object { $_.ProcessName -match "^p.*" } Description ----------- This command gets the processes with a ProcessName property that begins wit h the letter "p". The match operator enables you to use regular expressions within a Where clause. -------------------------- EXAMPLE 4 -------------------------- C:\PS>get-process -name svchost | where-object {$True} Description ----------- This command lists all of the processes named "svchost". The Where-Object cmdlet evaluates the script block, which typically include s a reference to the object currently in the pipeline ($_), and casts the results to a Boolean type: True or False. If the result is True, the object is returned. Otherwise, it is discarded. In this case, the script block just returns True, so all the objects are re turned. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113423 Write-Debug NAME Write-Debug SYNOPSIS Writes a debug message to the console. SYNTAX Write-Debug [-Message] <string> [<CommonParameters>] DESCRIPTION The Write-Debug cmdlet writes debug messages to the console from a script o r command. By default, debug messages are not displayed in the console, but you can di splay them by using the Debug parameter or the $DebugPreference variable. PARAMETERS -Message <string> Specifies the debug message to send to the console. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains a debug message to Write-Debug. OUTPUTS None Write-Debug writes only to the debug stream. It does not return any out put. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>Write-Debug "Cannot open file." Description ----------- This command writes a debug message. Because the value of $DebugPreference is "SilentlyContinue", the message is not displayed in the console. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$DebugPreference SilentlyContinue C:\PS> Write-Debug "Cannot open file." C:\PS> C:\PS> Write-Debug "Cannot open file." -debug DEBUG: Cannot open file. Description ----------- This example shows how to use the Debug common parameter to override the va lue of the $DebugPreference variable for a particular command. The first command displays the value of the $DebugPreference variable, whic h is "SilentlyContinue", the default. The second command writes a debug message but, because of the value of $Deb ugPreference, the message does not appear. The third command writes a debug message. It uses the Debug common paramete r to override the value of $DebugPreference and to display the debug messag es resulting from this command. As a result, even though the value of $DebugPreference is "SilentlyContinue ", the debug message appears. For more information about the Debug common parameter, see about_CommonPara meters. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$DebugPreference SilentlyContinue C:\PS> Write-Debug "Cannot open file." C:\PS> C:\PS> $DebugPreference = "Continue" C:\PS> Write-Debug "Cannot open file." DEBUG: Cannot open file. Description ----------- This command shows the effect of changing the value of the $DebugPreference variable on the display of debug messages. The first command displays the value of the $DebugPreference variable, whic h is "SilentlyContinue", the default. The second command writes a debug message but, because of the value of $Deb ugPreference, the message does not appear. The third command assigns a value of "Continue" to the $DebugPreference var iable. The fourth command writes a debug message, which appears on the console. For more information about $DebugPreference, see about_Preference_Variables . RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113424 Write-Verbose Write-Error Write-Host Write-Progress Write-Output Write-Warning Write-Error NAME Write-Error SYNOPSIS Writes an object to the error stream. SYNTAX Write-Error -ErrorRecord <ErrorRecord> [-CategoryActivity <string>] [-Categ oryReason <string>] [-CategoryTargetName <string>] [-CategoryTargetType <st ring>] [-RecommendedAction <string>] [<CommonParameters>] Write-Error [-Message] <string> [-Category {NotSpecified | OpenError | Clos eError | DeviceError | DeadlockDetected | InvalidArgument | InvalidData | I nvalidOperation | InvalidResult | InvalidType | MetadataError | NotImplemen ted | NotInstalled | ObjectNotFound | OperationStopped | OperationTimeout | SyntaxError | ParserError | PermissionDenied | ResourceBusy | ResourceExis ts | ResourceUnavailable | ReadError | WriteError | FromStdErr | SecurityEr ror}] [-ErrorId <string>] [-TargetObject <Object>] [-CategoryActivity <stri ng>] [-CategoryReason <string>] [-CategoryTargetName <string>] [-CategoryTa rgetType <string>] [-RecommendedAction <string>] [<CommonParameters>] Write-Error -Exception <Exception> [-Category {NotSpecified | OpenError | C loseError | DeviceError | DeadlockDetected | InvalidArgument | InvalidData | InvalidOperation | InvalidResult | InvalidType | MetadataError | NotImple mented | NotInstalled | ObjectNotFound | OperationStopped | OperationTimeou t | SyntaxError | ParserError | PermissionDenied | ResourceBusy | ResourceE xists | ResourceUnavailable | ReadError | WriteError | FromStdErr | Securit yError}] [-ErrorId <string>] [-Message <string>] [-TargetObject <Object>] [ -CategoryActivity <string>] [-CategoryReason <string>] [-CategoryTargetName <string>] [-CategoryTargetType <string>] [-RecommendedAction <string>] [ ommonParameters>] DESCRIPTION The Write-Error cmdlet writes an error to the Windows PowerShell error stre am. By default, errors are sent to the host program to be displayed, along with output. You can write an error by submitting an error message string, an ErrorRecor d object, or an Exception object. Use the other parameters of Write-Error to populate the error record. PARAMETERS -Category <ErrorCategory> Specifies the category of the error. The default value is NotSpecified . For information about the error categories, see "ErrorCategory Enumerat ion" in the MSDN (Microsoft Developer Network) library at http://go.mic rosoft.com/fwlink/?LinkId=143600. Required? false Position? named Default value NotSpecified Accept pipeline input? false Accept wildcard characters? false -CategoryActivity <string> Describes the action that caused the error. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -CategoryReason <string> Explains how or why the activity caused the error. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -CategoryTargetName <string> Specifies the name of the object that was being processed when the erro r occurred. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -CategoryTargetType <string> Specifies the .NET type of the object that was being processed when the error occurred. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -ErrorId <string> Specifies an ID string to identify the error. The string should be uniq ue to the error. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -ErrorRecord <ErrorRecord> Specifies an error record object that includes properties that describe the error. To get an error record object, use the New-Object cmdlet or take an err or record object from the array in the $Error automatic variable. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Exception <Exception> Specifies an exception that represents the error. You can use an exception instead of specifying message text or an excep tion record. Required? true Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Message <string> Specifies the message text of the error. If the text includes spaces o r special characters, enclose it in quotation marks. You can also pipe a message string to Write-Error. Required? true Position? 1 Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? false -RecommendedAction <string> Describes the action that the user should take to resolve or prevent th e error. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -TargetObject <Object> Specifies the object that was being processed when the error occurred. Enter the object (such as a string), a variable that contains the objec t, or a command that gets the object. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains an error message to Write-Error. OUTPUTS Error object Write-Error writes only to the error stream. It does not return any obj ects. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>get-childitem | foreach-object { if ($_.gettype().tostring() -eq "Mic rosoft.Win32.RegistryKey") {write-error "Out-of-band object" -errorID B1 -t argetobject $_ } else {$_ } } Description ----------- This command writes an error when the Get-ChildItem cmdlet returns a Micros oft.Win32.RegistryKey object, such as the objects in the HKLM: or HKCU driv es of the Windows PowerShell Registry provider. -------------------------- EXAMPLE 2 -------------------------- C:\PS>write-error "Access denied." Description ----------- This command writes an "Access denied" error. The command uses the Message parameter to specify the message, but omits the optional Message parameter name. -------------------------- EXAMPLE 3 -------------------------- C:\PS>write-error -message "Error: Too many input values." -category Invali dArgument Description ----------- This command writes a error and specifies an error category. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113425 Write-Debug Write-Verbose Write-Output Write-Host Write-Progress Write-Warning Write-EventLog NAME Write-EventLog SYNOPSIS Writes an event to an event log. SYNTAX Write-EventLog [-LogName] <string> [-Source] <string> [-EventID] <int> [-Me ssage] <string> [[-EntryType] {Error | Warning | Information | SuccessAudit | FailureAudit}] [-Category <Int16>] [-ComputerName <string>] [-RawData <B yte[]>] [<CommonParameters>] DESCRIPTION The Write-EventLog cmdlet writes an event to an event log. To write an event to an event log, the event log must exist on the computer and the source must be registered for the event log. The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinE vent. PARAMETERS -Category <Int16> Specifies a task category for the event. Enter an integer that is assoc iated with the strings in the category message file for the event log. Required? false Position? named Default value 1 Accept pipeline input? false Accept wildcard characters? false -ComputerName <string> Specifies a remote computer. The default is the local computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qu alified domain name of a remote computer. This parameter does not rely on Windows PowerShell remoting. You can us e the ComputerName parameter of Get-EventLog even if your computer is n ot configured to run remote commands. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -EntryType <EventLogEntryType> Specifies the entry type of the event. Valid values are Error, Warning , Information, SuccessAudit, and FailureAudit. The default value is Inf ormation. For a description of the values, see System.Diagnostics.EventLogEntryTy pe in the MSDN (Microsoft Developer Network) library at http://go.micro soft.com/fwlink/?LinkId=143599. Required? false Position? 4 Default value Accept pipeline input? false Accept wildcard characters? false -EventID <int> Specifies the event identifier. This parameter is required. Required? true Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false -LogName <string> Specifies the name of the log to which the event is written. Enter the log name (the value of the Log property, not the LogDisplayName). Wildc ard characters are not permitted. This parameter is required. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Message <string> Specifies the event message. This parameter is required. Required? true Position? 5 Default value Accept pipeline input? false Accept wildcard characters? false -RawData <Byte[]> Specifies the binary data that is associated with the event, in bytes. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Source <string> Specifies the event source, which is typically the name of the applicat ion that is writing the event to the log. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS System.Diagnostics.EventLogEntry Write-EventLog returns objects that represents the events in the logs. NOTES To use Write-EventLog on Windows Vista and later versions of Windows, s tart Windows PowerShell with the "Run as administrator" option. -------------------------- EXAMPLE 1 -------------------------- C:\PS>write-eventlog -logname Application -source MyApp -eventID 3001 -entr ytype Information -message "MyApp added a user-requested feature to the dis play." -category 1 -rawdata 10,20 Description ----------- This command writes an event from the MyApp source to the Application event log. -------------------------- EXAMPLE 2 -------------------------- C:\PS>write-eventlog -computername Server01 -logname Application -source My App -eventID 3001 -message "MyApp added a user-requested feature to the dis play." Description ----------- This command writes an event from the MyApp source to the Application event log on the Server01 remote computer. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=135281 Clear-EventLog Get-EventLog Limit-EventLog New-EventLog Remove-EventLog Show-EventLog Write-EventLog Get-WinEvent Write-Host NAME Write-Host SYNOPSIS Writes customized output to a host. SYNTAX Write-Host [[-Object] <Object>] [-BackgroundColor {Black | DarkBlue | DarkG reen | DarkCyan | DarkRed | DarkMagenta | DarkYellow | Gray | DarkGray | Bl ue | Green | Cyan | Red | Magenta | Yellow | White}] [-ForegroundColor {Bla ck | DarkBlue | DarkGreen | DarkCyan | DarkRed | DarkMagenta | DarkYellow | Gray | DarkGray | Blue | Green | Cyan | Red | Magenta | Yellow | White}] [ -NoNewline] [-Separator <Object>] [<CommonParameters>] DESCRIPTION The Write-Host cmdlet customizes output. You can specify the color of text by using the ForegroundColor parameter, and you can specify the background color by using the BackgroundColor parameter. The Separator parameter lets you specify a string to use to separate displayed objects. The particular r esult depends on the program that is hosting Windows PowerShell. PARAMETERS -BackgroundColor <ConsoleColor> Specifies the background color. There is no default. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -ForegroundColor <ConsoleColor> Specifies the text color. There is no default. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -NoNewline [<SwitchParameter>] Specifies that the content displayed in the console does not end with a newline character. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false -Object <Object> Objects to display in the console. Required? false Position? 1 Default value None Accept pipeline input? true (ByValue) Accept wildcard characters? false -Separator <Object> String to the output between objects displayed on the console. Required? false Position? named Default value None Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Object You can pipe objects to be written to the host. OUTPUTS None Write-Host sends the objects to the host. It does not return any object s. However, the host might display the objects that Write-Host sends to it. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>write-host "no newline test " -nonewline no newline test C:\PS> Description ----------- This command displays the input to the console, but because of the NoNewlin e parameter, the output is followed directly by the prompt. -------------------------- EXAMPLE 2 -------------------------- C:\PS>write-host (2,4,6,8,10,12) -Separator ", +2= " 2, +2= 4, +2= 6, +2= 8, +2= 10, +2= 12 Description ----------- This command displays the even numbers from 2 through 12. The Separator par ameter is used to add the string , +2= (comma, space, +, 2, =, space). -------------------------- EXAMPLE 3 -------------------------- C:\PS>write-host (2,4,6,8,10,12) -Separator ", -> " -foregroundcolor DarkGr een -backgroundcolor white Description ----------- This command displays the even numbers from 2 through 12. It uses the Foreg roundColor parameter to output dark green text and the BackgroundColor para meter to display a white background. -------------------------- EXAMPLE 4 -------------------------- C:\PS>write-host "Red on white text." -ForegroundColor red -BackgroundColor white Red on white text. Description ----------- This command displays the string "Red on white text." The text is red, as d efined by the ForegroundColor parameter. The background is white, as define d by the BackgroundColor parameter. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113426 Write-Verbose Write-Error Write-Progress Write-Debug Write-Output Write-Warning Out-Host Write-Output NAME Write-Output SYNOPSIS Sends the specified objects to the next command in the pipeline. If the com mand is the last command in the pipeline, the objects are displayed in the console. SYNTAX Write-Output [-InputObject] <PSObject[]> [<CommonParameters>] DESCRIPTION The Write-Output cmdlet sends the specified object down the pipeline to the next command. If the command is the last command in the pipeline, the obje ct is displayed in the console. Write-Output sends objects down the primary pipeline, also known as the "ou tput stream" or the "success pipeline." To send error objects down the erro r pipeline, use Write-Error. This cmdlet is typically used in scripts to display strings and other objec ts on the console. However, because the default behavior is to display the objects at the end of a pipeline, it is generally not necessary to use the cmdlet. For example, "get-process | write-output" is equivalent to "get-pro cess". PARAMETERS -InputObject <PSObject[]> Specifies the objects to send down the pipeline. Enter a variable that contains the objects, or type a command or expression that gets the obj ects. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.Management.Automation.PSObject You can pipe objects to Write-Output. OUTPUTS System.Management.Automation.PSObject Write-Output returns the objects that are submitted as input. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>$p = get-process c:\PS> write-output $p c:\PS> $p Description ----------- These commands get objects representing the processes running on the comput er and display the objects on the console. -------------------------- EXAMPLE 2 -------------------------- C:\PS>write-output "test output" | get-member Description ----------- This command pipes the "test output" string to the Get-Member cmdlet, which displays the members of the String class, demonstrating that the string wa s passed along the pipeline. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113427 Write-Debug Write-Verbose Write-Error Write-Progress Write-Host Write-Warning Tee-Object Write-Progress NAME Write-Progress SYNOPSIS Displays a progress bar within a Windows PowerShell command window. SYNTAX Write-Progress [-Activity] <string> [-Status] <string> [[-Id] <int>] [-Comp leted] [-CurrentOperation <string>] [-ParentId <int>] [-PercentComplete <in t>] [-SecondsRemaining <int>] [-SourceId <int>] [<CommonParameters>] DESCRIPTION The Write-Progress cmdlet displays a progress bar in a Windows PowerShell c ommand window that depicts the status of a running command or script. You c an select the indicators that the bar reflects and the text that appears ab ove and below the progress bar. PARAMETERS -Activity <string> Specifies the first line of text in the heading above the status bar. T his text describes the activity whose progress is being reported. Required? true Position? 1 Default value Accept pipeline input? false Accept wildcard characters? false -Completed [<SwitchParameter>] Indicates whether the progress bar is visible. If this parameter is omi tted, Write-Progress displays progress information. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -CurrentOperation <string> Specifies the line of text below the progress bar. This text describes the operation that is currently taking place. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Id <int> Specifies an ID that distinguishes each progress bar from the others. U se this parameter when you are creating more than one progress bar in a single command. If the progress bars do not have different IDs, they a re superimposed instead of being displayed in a series. Required? false Position? 3 Default value Accept pipeline input? false Accept wildcard characters? false -ParentId <int> Identifies the parent activity of the current activity. Use the value - 1 if the current activity has no parent activity. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -PercentComplete <int> Specifies the percentage of the activity that is completed. Use the val ue -1 if the percentage complete is unknown or not applicable. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SecondsRemaining <int> Specifies the projected number of seconds remaining until the activity is completed. Use the value -1 if the number of seconds remaining is un known or not applicable. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -SourceId <int> Identifies the source of the record. Required? false Position? named Default value Accept pipeline input? false Accept wildcard characters? false -Status <string> Specifies the second line of text in the heading above the status bar. This text describes current state of the activity. Required? true Position? 2 Default value Accept pipeline input? false Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None You cannot pipe input to this cmdlet. OUTPUTS None Write-Progress does not generate any output. NOTES If the progress bar does not appear, check the value of the $ProgressPr eference variable. If the value is set to SilentlyContinue, the progres s bar is not displayed. For more information about Windows PowerShell p references, see about_Preference_Variables. The parameters of the cmdlet correspond to the properties of the Progre ssRecord class (System.Management.Automation.ProgressRecord). For more information, see the ProgressRecord topic in the Windows PowerShell Sof tware Development Kit (SDK). -------------------------- EXAMPLE 1 -------------------------- C:\PS>for ($i = 1; $i -lt 101; $i++ ) {for ($j=0;$j -lt 10000;$j++) {} write-progress -activity "Search in Progre ss" -status "% Complete:" -percentcomplete $i;} Description ----------- This command displays the progress of two nested For loops. The first loop counts to 100. For each increment of that loop, the second loop counts to 1 0,000. The Write-Progress command includes a status bar heading ("activity"), a st atus line, and the variable $i (the counter in the For loop), which indicat es the relative completeness of the task. -------------------------- EXAMPLE 2 -------------------------- C:\PS>for($i = 1; $i -lt 101; $i++ ) {write-progress -activity Updating -st atus progress-> -percentcomplete $i -currentOperation OuterLoop} for($i = 1 ; $i -lt 101; $i++ ) {write-progress -activity Updating -status progress -p ercentcomplete $i -id 1 -currentOperation InnerLoop} Updating progress -> [oooooooooooooooooo ] OutsideLoop Updating progress [oooooooooooooooooo ] InnerLoop Description ----------- This example displays the progress of two nested For loops, each of which i s represented by a progress bar. The Write-Progress command for the second progress bar includes the Id para meter that distinguishes it from the first progress bar. Without the Id par ameter, the progress bars would be superimposed on each other instead of be ing displayed one below the other. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$events = get-eventlog -logname system C:\PS> $events | foreach-object -begin {clear-host;$i=0;$out=""} ` -process {if($_.message -like "*bios*") {$out=$out + $_.Message}; $i = $i+1;` write-progress -activity "Searching Events" ` -status "Progress:" -percentcomplete ($i/$events.count*100)} ` -end {$out} Description ----------- This command displays the progress of a command to find the string "bios" i n the System event log. In the first line of the command, the Get-EventLog cmdlet gets the events i n the System log and stores them in the $events variable. In the second line, the events are piped to the ForEach-Object cmdlet. Befo re processing begins, the Clear-Host cmdlet is used to clear the screen, th e $i counter variable is set to zero, and the $out output variable is set t o the empty string. In the third line, which is the Process script block of the ForEach-Object cmdlet, the cmdlet searches the message property of each incoming object fo r "bios". If the string is found, the message is added to $out. In the fourth line, the $i counter variable is incremented to record that a nother event has been examined. The fifth line uses the Write-Progress cmdlet with values for the Activity and Status text fields that create the first and second lines of the progre ss bar heading, respectively. The PercentComplete parameter value is calcul ated by dividing the number of events that have been processed ($i) by the total number of events retrieved ($events.count) and then multiplying that result by 100. In the last line, the End parameter of the ForEach-Object cmdlet is used to display the messages that are stored in the $out variable. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113428 Write-Verbose Write-Error Write-Host Write-Debug Write-Output Write-Warning Write-Verbose NAME Write-Verbose SYNOPSIS Writes text to the verbose message stream. SYNTAX Write-Verbose [-Message] <string> [<CommonParameters>] DESCRIPTION The Write-Verbose cmdlet writes text to the verbose message stream in Windo ws PowerShell. Typically, the verbose message stream is used to deliver inf ormation about command processing that is used for debugging a command. By default, the verbose message stream is not displayed, but you can displa y it by changing the value of the $VerbosePreference variable or using the Verbose common parameter in any command. PARAMETERS -Message <string> Specifies the message to display. This parameter is required. You can a lso pipe a message string to Verbose-Message. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains the message to Write-Verbose. OUTPUTS None Write-Verbose writes only to the verbose message stream. NOTES -------------------------- EXAMPLE 1 -------------------------- C:\PS>Write-Verbose -message "Searching the Application Event Log." C:\PS> Write-Verbose -message "Searching the Application Event Log." -verbo se Description ----------- These commands use the Write-Verbose cmdlet to display a status message. By default, the message is not displayed. The second command uses the Verbose common parameter, which displays any ve rbose messages, regardless of the value of the $VerbosePreference variable. -------------------------- EXAMPLE 2 -------------------------- C:\PS>$VerbosePreference = "Continue" C:\PS> Write-Verbose "Copying file $filename" Description ----------- These commands use the Write-Verbose cmdlet to display a status message. By default, the message is not displayed. The first command assigns a value of "Continue" to the $VerbosePreference p reference variable. The default value, "SilentlyContinue", suppresses verbo se messages. The second command writes a verbose message. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113429 Write-Error Write-Warning about_Preference_Variables Write-Warning NAME Write-Warning SYNOPSIS Writes a warning message. SYNTAX Write-Warning [-Message] <string> [<CommonParameters>] DESCRIPTION The Write-Warning cmdlet writes a warning message to the Windows PowerShell host. The response to the warning depends on the value of the user's $Warn ingPreference variable and the use of the WarningAction common parameter. PARAMETERS -Message <string> Specifies the warning message. Required? true Position? 1 Default value Accept pipeline input? true (ByValue) Accept wildcard characters? false <CommonParameters> This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type, "get-help about_commonparameters". INPUTS System.String You can pipe a string that contains the warning to Write-Warning. OUTPUTS None Write-Warning writes only to the warning stream. It does not generate a ny other output. NOTES The default value for the $WarningPreference variable is "Continue", wh ich displays the warning and then continues executing the command. To d etermine valid values for a preference variable such as $WarningPrefere nce, set it to a string of random characters, such as "abc". The result ing error message will list the valid values. -------------------------- EXAMPLE 1 -------------------------- C:\PS>write-warning "This is only a test warning." Description ----------- This command displays the message "WARNING: This is only a test warning." -------------------------- EXAMPLE 2 -------------------------- C:\PS>$w = "This is only a test warning." C:\PS> $w | write-warning Description ----------- This example shows that you can use a pipeline operator (|) to send a strin g to Write-Warning. You can save the string in a variable, as shown in this command, or pipe the string directly to Write-Warning. -------------------------- EXAMPLE 3 -------------------------- C:\PS>$warningpreference Continue C:\PS> write-warning "This is only a test warning." This is only a test warning. C:\PS> $warningpreference = "SilentlyContinue" C:\PS> write-warning "This is only a test warning." C:\PS> C:\PS> $warningpreference = "Stop" C:\PS> write-warning "This is only a test warning." WARNING: This is only a test message. Write-Warning : Command execution stopped because the shell variable "Warni ngPreference" is set to Stop. At line:1 char:14 + write-warning < "This is only a test message." Description ----------- This example shows the effect of the value of the $WarningPreference variab le on a Write-Warning command. The first command displays the default value of the $WarningPreference vari able, which is "Continue". As a result, when you write a warning, the warni ng message is displayed and execution continues. When you change the value of the $WarningPreference variable, the effect of the Write-Warning command changes again. A value of "SilentlyContinue" sup presses the warning. A value of "Stop" displays the warning and then stops execution of the command. For more information about the $WarningPreference variable, see about_Prefe rence_Variables. -------------------------- EXAMPLE 4 -------------------------- C:\PS>write-warning "This is only a test warning." -warningaction Inquire WARNING: This is only a test warning. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default i s "Y"): Description ----------- This example shows the effect of the WarningAction common parameter on a Wr ite-Warning command. You can use the WarningAction common parameter with an y cmdlet to determine how Windows PowerShell responds to warnings resulting from that command. The WarningAction common parameter overrides the value of the $WarningPreference only for that particular command. This command uses the Write-Warning cmdlet to display a warning. The Warnin gAction common parameter with a value of "Inquire" directs the system to pr ompt the user when the command displays a warning. For more information about the WarningAction common parameter, see about_Co mmonParameters. RELATED LINKS Online version: http://go.microsoft.com/fwlink/?LinkID=113430 about_Preference_Variables about_CommonParameters Write-Debug Write-Error Write-Host Write-Output Write-Progress Write-Verbose WSMan PROVIDER NAME WSMan DRIVES WSMan SYNOPSIS Provides access to Web Services for Management (WS-Management) configuratio n information. DESCRIPTION The WS-Management provider for Windows PowerShell lets you add, change, cle ar, and delete WS-Management configuration data on local or remote computer s. The WS-Management provider exposes a Windows PowerShell drive with a direct ory structure that corresponds to a logical grouping of WS-Management confi guration settings. These groupings are known as containers. -- Client You can configure various aspects of the WS-Management client. The configur ation information is stored in the registry. -- Service You can configure various aspects of the WS-Management service. The configu ration information is stored in the registry. Note: Service configuration is sometimes referred to as Server configuratio n. -- Shell You can configure various aspects of the WS-Management shell, such as the s etting to allow remote shell access (AllowRemoteShellAccess) and the maximu m number of concurrent users allowed (MaxConcurrentUsers). -- Listener You can create and configure a listener. A listener is a management service that implements the WS-Management protocol to send and to receive messages . -- Plugin Plug-ins are loaded and used by the WS-Management service to provide variou s functions. By default, Windows PowerShell provides three plug-ins: the Ev ent Forwarding plug-in, the Microsoft.PowerShell plug-in, and the Windows M anagement Instrumentation (WMI) Provider plug-in. These three plug-ins supp ort event forwarding, configuration, and WMI access. -- ClientCertificate You can create and configure a client certificate. A client certificate is used when the WS-Management client is configured to use certificate authent ication. Directory Hierarchy of the WS-Management Provider --------------- The directory hierarchy of the WS-Management provider for the local compute r is as follows: WSMan:\localhost --- Client --- Service --- Shell --- Listener ------ <Specific_Listener> --- Plugin ------ Event Forwarding Plugin --------- InitializationParameters --------- Resources ------------ Security ------ Microsoft.Powershell --------- InitializationParameters --------- Resources ------------ Security ------ WMI Provider --------- InitializationParameters --------- Resources ------------ Security --- ClientCertificate The directory hierarchy of the WS-Management provider for a remote computer is the same as a local computer. However, in order to access the configura tion settings of a remote computer, you need to make a connection to the re mote computer using Connect-WSMan. Once a connection is made to a remote co mputer, the name of the remote computer shows up in the provider. WSMan:\<Remote_Computer_Name> --- Client --- Service --- Shell --- Listener ------ <Specific_Listener> --- Plugin ------ Event Forwarding Plugin --------- InitializationParameters --------- Resources ------------ Security ------ Microsoft.Powershell --------- InitializationParameters --------- Resources ------------ Security ------ WMI Provider --------- InitializationParameters --------- Resources ------------ Security --- ClientCertificate Custom Provider Help -------------------- The Listener, Plugin (IntitializationParameters, Resources, Security) and C lientCertificate provider paths provide specific New-Item support. Type "g et-help New-Item" in the relevant path for custom help. CAPABILITIES TASKS TASK: Navigating the WSMan: Drive -------------------------- EXAMPLE 1 -------------------------- This command uses the Set-Location cmdlet to change the current locatio n to the WSMan: drive. Set-Location WSMan: -------------------------- EXAMPLE 2 -------------------------- This command uses the Set-Location command to change the current locati on to the root location in the Localhost store location. Use a backsla sh (\) or forward slash (/) to indicate a level of the WSMan: drive. Set-Location -Path Localhost If you are not in the WSMan: drive, begin the path with the drive name. -------------------------- EXAMPLE 3 -------------------------- This command uses the Set-Location command to change the current locati on to the root location in the remote system store location. Use a bac kslash (\) or forward slash (/) to indicate a level of the WSMan: drive . Set-Location -Path WSMan:\SERVER01 If you are not in the WSMan: drive, begin the path with the drive name. The above command assume that a connection to the remote system already exists. If a connection has not been made to the remote system, then a connection could be make immediately prior to navigating to the root location in the remote system store location. For example: WSMan-Connect SERVER01 Set-Location -Path WSMan:\SERVER01 -------------------------- EXAMPLE 4 -------------------------- This command uses the Set-Location command to change the current locati on to the Client location in the Localhost store location. Use a backs lash (\) or forward slash (/) to indicate a level of the WSMan: drive. Set-Location -Path Localhost\Client If you are not in the WSMan: drive, begin the path with the drive name. TASK: Displaying the Contents of the WSMan: Drive -------------------------- EXAMPLE 1 -------------------------- This command uses the Get-Childitem cmdlet to display the WS-Management stores in the Localhost store location. get-childitem -path WSMan:\Localhost If you are in the WSMan: drive, you can omit the drive name. -------------------------- EXAMPLE 2 -------------------------- This command uses the Get-Childitem cmdlet to display the WS-Management stores in the remote computer (SERVER01) store location. get-childitem -path WSMan:\SERVER01 If you are in the WSMan: drive, you can omit the drive name. The above command assume that a connection to the remote system already exists. If a connection has not been made to the remote system, then a connection could be make immediately displaying the properties and co ntainers in the remote system store location. For example: WSMan-Connect SERVER01 get-childitem -path WSMan:\SERVER01 -------------------------- EXAMPLE 3 -------------------------- This command uses the Get-Childitem cmdlet to display the current WS-Ma nagement connections. get-childitem -path WSMan:\ If you are in the WSMan: drive, you can omit the drive name. -------------------------- EXAMPLE 4 -------------------------- This command uses the Get-Item cmdlet to get the properties and contain ers in the current store. Get-Childitem The above command returns a list of properties and containers. For exa mple: PS WSMan:\localhost> get-childitem WSManConfig: Microsoft.WSMan.Management\WSMan::localhost Name Value Type ---- ----- ---- MaxEnvelopeSizekb 150 System.String MaxTimeoutms 60000 System.String MaxBatchItems 32000 System.String MaxProviderRequests 4294967295 System.String Client Container Service Container Shell Container Listener Container Plugin Container ClientCertificate Container DYNAMIC PARAMETERS -Address <String> Specifies the address for which this listener was created. The value ca n be one of the following: -- The literal string "*". (The wildcard character (*) makes the comman d bind all the IP addresses on all the network interface cards [NIC].) -- The literal string "IP:" followed by a valid IP address in either IP v4 dotted-decimal format or in IPv6 cloned-hexadecimal format. -- The literal string "MAC:" followed by the MAC address of a NIC. For example: MAC:32-a3-58-90-be-cc. Note: The Address value is set when creating a Listener. Cmdlets Supported: Get-Item -AllowRemoteShellAccess <Boolean> Enables access to remote shells. If you set this parameter to False, ne w remote shell connections will be rejected by the server. The default is True. Cmdlets Supported: Get-Item, Set-Item -AllowUnEncrypted <Boolean> Allows the client computer to request unencrypted traffic. By default, the client computer requires encrypted network traffic. Cmdlets Supported: Get-Item, Set-Item -Arguments <String> Specifies the argument string and the command-line arguments that you w ant to pass to the custom shell. This parameter is optional. Cmdlets Supported: Get-Item, Set-Item -Basic <Boolean> Allows the client computer to use Basic authentication. Basic authentic ation is a scheme in which the user name and password are sent in clear text to the server or proxy. This method is the least secure method of authentication. Cmdlets Supported: Get-Item, Set-Item -Capability <Enumeration> Specifies an operation that is supported on this Uniform Resource Ident ifier (URI). You have to create one entry for each type of operation th at the URI supports. The following are valid values: -- Create: Create operations are supported on the URI. The SupportFragm ent attribute is used if the Create operation supports the concept. The SupportFiltering attribute is not valid and should be set to False. Th is operation is not valid for a URI if Shell operations are also suppor ted. -- Delete: Delete operations are supported on the URI. The SupportFragm ent attribute is used if the Delete operation supports the concept. The SupportFiltering attribute is not valid and should be set to False. Th is operation is not valid for a URI if Shell operations are also suppor ted. -- Enumerate: Enumerate operations are supported on the URI. The Suppor tFragment attribute is not supported for Enumerate operations and shoul d be set to False. The SupportFiltering attribute is valid, and if the plug-in supports filtering, this attribute should be set to True. This operation is not valid for a URI if Shell operations are also supported . -- Get: Get operations are supported on the URI. The SupportFragment at tribute is used if the Get operation supports the concept. The SupportF iltering attribute is not valid and should be set to False. This operat ion is not valid for a URI if Shell operations are also supported. -- Invoke: Invoke operations are supported on the URI. The SupportFragm ent attribute is not supported for Invoke operations and should be set to False. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if Shell operations ar e also supported. -- Put: Put operations are supported on the URI. The SupportFragment at tribute is used if the Put operation supports the concept. The SupportF iltering attribute is not valid and should be set to False. This operat ion is not valid for a URI if Shell operations are also supported. -- Subscribe: Subscribe operations are supported on the URI. The Suppor tFragment attribute is not supported for Subscribe operations and shoul d be set to False. The SupportFiltering attribute is not valid and shou ld be set to False. This operation is not valid for a URI if Shell oper ations are also supported. -- Shell: Shell operations are supported on the URI. The SupportFragmen t attribute is not supported for Shell operations and should be set to False. The SupportFiltering attribute is not valid and should be set to False. This operation is not valid for a URI if any other operation is also supported. If a Shell operation is configured for a URI, Get, Put , Create, Delete, Invoke, and Enumerate operations are processed intern ally within the WS-Management (WinRM) service to manage shells. As a re sult, the plug-in cannot handle the operations. Cmdlets Supported: Get-Item, New-Item, Remove-Item, Set-Item -CbtHardeningLevel <String> Sets the policy for channel-binding token requirements in authenticatio n requests. The following are valid values: -- Strict: Any request will be denied unless a channel-binding token i s present. This setting guarantees that all connections are secured by the use of channel-binding tokens. -- Relaxed: If a channel-binding token is present in a request, the con nection will be secured. If a channel-binding token is not present, th e connection will still be accepted. However, it will be vulnerable to attacks that are prevented by the use of channel-binding tokens. -- None: Any channel-binding tokens that are supplied are ignored. The value of this parameter is only effective for HTTPS connections. Cmdlets Supported: Get-Item, Set-Item -CertificateThumbprint <String> Specifies the thumbprint of the service certificate. This value represents the string of two-digit hexadecimal values in the Thumbprint field of the certificate. It specifies the digital public k ey certificate (X509) of a user account that has permission to perform this action. Certificates are used in client certificate-based authenti cation. They can be mapped only to local user accounts, and they do not work with domain accounts. To get a certificate thumbprint, use the Ge t-Item or Get-ChildItem cmdlets in the Windows PowerShell Cert: drive. Cmdlets Supported: Clear-Item, Get-Item, Set-Item -Certificate <Boolean> Allows the client to be used for certificate authentication. The WS-Man agement client will try to find the certificate in the computer store. If the client cannot find the certificate in the computer store, the cl ient tries to find it in the current user store. If no matching certifi cate is found, the user receives an error message. Cmdlets Supported: Get-Item, Set-Item -CredSSP <Boolean> Allows the client to use Credential Security Service Provider (CredSSP) authentication. CredSSP authentication allows the user to delegate credentials. This op tion is designed for commands that run on one remote computer but colle ct data from or run additional commands on other remote computers. Caution: CredSSP authentication delegates the user's credentials from t he local computer to a remote computer. This practice increases the sec urity risk of the remote operation. If the remote computer is compromis ed, when credentials are passed to it, the credentials can be used to c ontrol the network session. Cmdlets Supported: Get-Item, Set-Item -HTTP <Unsigned Short Integer> Specifies the port that the client will use when HTTP is used. By defau lt, HTTP uses port 80. You can specify any value from 1 through 65535. Cmdlets Supported: Get-Item, Set-Item -HTTPS <Unsigned Short Integer> Specifies the port that the client will use when HTTPS is used. By defa ult, HTTPS uses port 443. You can specify any value from 1 through 6553 5. Cmdlets Supported: Get-Item, Set-Item -Digest <Boolean> Allows the client to use Digest authentication. Digest authentication i s a challenge-response scheme that uses a server-specified data string for the challenge. Only the client computer can initiate a Digest auth entication request. The client computer sends a request to the server t o authenticate and receives a token string from the server. Then, the c lient computer sends the resource request, including the user name and a cryptographic hash of the password combined with the token string. Di gest authentication is supported for HTTP and for HTTPS. WinRM Shell cl ient scripts and applications can specify Digest authentication, but th e WS-Management service does not accept Digest authentication. Note: Digest authentication over HTTP is not considered secure. Cmdlets Supported: Get-Item, Set-Item -Enabled <Boolean> Specifies whether the listener is enabled or disabled. The default is T rue. Cmdlets Supported: Get-Item, Set-Item -ExactMatch <Boolean> Specifies how to use the security settings that are specified in the Sd dl parameter. If the ExactMatch parameter is set to True, the security settings in Sddl are used only to authorize access attempts to the URI exactly as specified by the URI. If ExactMatch is set to false, the sec urity settings in Sddl are used to authorize access attempts to the URI s that begin with the string specified in the URI. Cmdlets Supported: Get-Item, Set-Item -FileName <String> Specifies an input file to use to update the management resource specif ied by the ResourceURI and SelectorSet. Cmdlets Supported: Get-Item, Set-Item -FileName (Plugin) <String> Specifies the file name of the operations plug-in. Any environment vari ables that are put in this entry will be expanded in the users' context when a request is received. Because each user could have a different v ersion of the same environment variable, each user could have a differe nt plug-in. This entry cannot be blank and must point to a valid plug-i n. Cmdlets Supported: Get-Item, Set-Item -HostName <String> Specifies the host name of the computer on which the WS-Management (Win RM) service is running. The value must be a fully qualified domain name, an IPv4 or IPv6 litera l string, or a wildcard character. Cmdlets Supported: Clear-Item, Get-Item, Set-Item -IdleTimeOut <Unsigned Long Integer> Specifies the maximum time, in milliseconds, that the remote shell will remain open when there is no user activity in the remote shell. The re mote shell is automatically deleted after the time that is specified. Y ou can specify any values from 0 through 2147483647. A value of 0 indic ates an infinite time-out. The default is 900000 (15 minutes). Cmdlets Supported: Get-Item, Set-Item -IPv4Filter <String> Specifies the IPv4 addresses that listeners can use. The following are valid values: -- If you leave the parameter blank, no IPv4 addresses can be used. -- If you enter a wildcard character (*), any IPv4 address can be used. -- If you enter a list of IP ranges, any IP address in the specified ra nges can be used. Separate the ranges by using a comma (,), and specify each range as a pair of IPv4 addresses in dotted-decimal format, separ ated by a hyphen (-). Make sure that the smaller value occurs first in the pair. The ranges are inclusive. Note: An IPv4 literal string consists of four dotted decimal numbers, e ach in the range 0 though 255. For example: 192.168.0.0. Cmdlets Supported: Clear-Item, Get-Item, Set-Item -IPv6Filter <String> Specifies the IPv6 addresses that listeners can use. The following are valid values: -- If you leave the parameter blank, no IPv6 addresses can be used. -- If you enter a wildcard character (*), any IPv6 address can be used. -- If you enter a list of IP ranges, any IP address in the specified ra nges can be used. Separate the ranges by using a comma (,"), and specif y each range as a pair of IPv6 addresses in cloned-hexadecimal format, separated by a hyphen (-). Make sure that the smaller value occurs firs t in the pair. The ranges are inclusive. Note: An IPv6 literal string is enclosed in brackets and contains hexad ecimal numbers that are separated by colons. For example: [::1] or [3ff e:ffff::6ECB:0101]. Cmdlets Supported: Clear-Item, Get-Item, Set-Item -Issuer <String> Specifies the name of the certification authority that issued the certi ficate. Cmdlets Supported: Get-Item, Set-Item -Kerberos <Boolean> Allows the client to use Kerberos authentication. Kerberos authenticati on is a scheme in which the client and server mutually authenticate by using Kerberos certificates. Cmdlets Supported: Get-Item, Set-Item -ListeningOn <String> Specifies the IP address or all the IP addresses on which the service i s actually listening. This is derived from the Address element based up on the actual IPs associated with the listener. The value of the IP add ress must be in IPv4 dotted-decimal notation or in IPv6 colon-delimited hexadecimal notation. Multiple ListeningOn entries exist, each entry s tarting with ListeningOn_. For example: ListeningOn_1201550598 ListeningOn_1973755898 ListeningOn_1508953035 ListeningOn_1560839940 Cmdlets Supported: Get-Item -MaxBatchItems <Unsigned Long Integer> Specifies the maximum number of elements that can be used in a Pull res ponse. You can specify any value from 1 through 4294967295. Cmdlets Supported: Get-Item, Set-Item -MaxConcurrentUsers <Unsigned Long Integer> Specifies the maximum number of users who can concurrently perform remo te operations on the same computer through a remote shell. New shell co nnections will be rejected if they exceed the specified limit. You can specify any value from 1 through 100. Cmdlets Supported: Get-Item, Set-Item -MaxEnvelopeSizekb <Unsigned Long Integer> Specifies the maximum SOAP data in kilobytes. You can specify any value from 32 through 4294967295. Cmdlets Supported: Get-Item, Set-Item -MaxMemoryPerShellMB <Unsigned Long Integer> Specifies the maximum total amount of memory that can be allocated by a n active remote shell and all its child processes. You can specify any value from 0 through 2147483647. A value of 0 means that the ability of the remote operations to allocate memory is limited only by the avail able virtual memory. The default value is 0. Cmdlets Supported: Get-Item, Set-Item -MaxProcessesPerShell <Unsigned Long Integer> Specifies the maximum number of processes that any shell operation is a llowed to start. You can specify any number from 0 through 2147483647. A value of 0 allows for an unlimited number of processes. By default, t he limit is five processes per shell. Cmdlets Supported: Get-Item, Set-Item -MaxProviderRequests <Unsigned Long Integer> Specifies the maximum number of concurrent requests that are allowed by the service. You can specify any value from 1 through 4294967295. The limit is applied per provider. Note: This value is deprecated and should not be used. Cmdlets Supported: Get-Item -MaxShellsPerUser <Unsigned Long Integer> Specifies the maximum number of concurrent shells that any user can rem otely open on the same system. If this policy setting is enabled, the u ser will not be able to open new remote shells if the count exceeds th e specified limit. If this policy setting is disabled or is not configu red, by default, the limit will be set to two remote shells per user. Y ou can specify any number from 0 through 2147483647. A value of 0 allow s for an unlimited number of shells. Cmdlets Supported: Get-Item, Set-Item -MaxTimeoutMs <Unsigned Long Integer> Specifies the maximum time-out in milliseconds that can be used for any request except for Pull requests. You can specify any number from 500 to 4294967295. Cmdlets Supported: Get-Item, Set-Item -Name <String> Specifies a display name for the WS-Management session . You can use th e name to refer to the session when using other cmdlets, such as Get-PS Session and Enter-PSSession. The name does not have to be unique to the computer or to the current session. Cmdlets Supported: Get-Item, Set-Item -Name (Plugin) <String> Specifies the display name to use for the plug-in. If an error is retur ned by the plug-in, the display name will be put in the error XML that is returned to the client application. The name is not locale specific. Cmdlets Supported: Get-Item, Set-Item -Negotiate <Boolean> Allows the client to use Negotiate authentication. Negotiate authentica tion is a scheme in which the client sends a request to the server to a uthenticate. The server determines whether to use the Kerberos protocol or NTLM. The Kerberos protocol is selected to authenticate a domain ac count, and NTLM is selected for local computer accounts. The user name must be specified in the domain\user_name form for a domain user. The u ser name must be specified in the server_name\user_name format for a lo cal user on a server computer. Cmdlets Supported: Get-Item, Set-Item -NetworkDelayMs <Unsigned Long Integer> Specifies the extra time in milliseconds that the client computer waits to accommodate for network delay time. You can specify any value from 500 through 4294967295. Cmdlets Supported: Get-Item, Set-Item -Password <String> Specifies the password for a local or a domain account. It cannot be NU LL. The client computer can specify the credentials to use when creating a shell on a computer. The user name must be specified in the domain\use r_name form for a domain user. The user name must be specified in the s erver_name\user_name format for a local user on a server computer. If you use this structure, then it should have both the user name and p assword fields specified. It can be used with Basic, Digest, Negotiate, or Kerberos authentication. The client must explicitly specify the cre dentials when either Basic or Digest authentication is used. Cmdlets Supported: Get-Item, Set-Item -Plugin <> WS-Management plug-ins are native dynamic link libraries (DLLs) that p lug in to and extend the functionality of WS-Management . The WSW-Manag ement Plug-in API provides functionality that enables a user to write plug-ins by implementing certain APIs for supported resource URIs and o perations. After the plug-ins are configured for either the WS-Manageme nt (WinRM) service or for Internet Information Services (IIS), the plug -ins are loaded in the WS-Management host or in the IIS host, respectiv ely. Remote requests are routed to these plug-in entry points to perfor m operations. Cmdlets Supported: New-Item, Remove-Item -Port <Unsigned Short Integer> Specifies the TCP port for which this listener is created. You can spec ify any value from 1 through 65535. Cmdlets Supported: Get-Item, Set-Item -Resource <String> Specifies an endpoint that represents a distinct type of management ope ration or value. A service exposes one or more resources, and some reso urces can have more than one instance. A management resource is similar to a WMI class or to a database table, and an instance is similar to a n instance of the class or to a row in the table. For example, the Win3 2_LogicalDisk class represents a resource. Win32_LogicalDisk="C:\" is a specific instance of the resource. A Uniform Resource Identifier (URI) contains a prefix and a path to a r esource. For example: http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalD isk http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor Cmdlets Supported: Get-Item, Set-Item -ResourceURI <String> Specifies the Uniform Resource Identifier (URI) that identifies a speci fic type of resource, such as a disk or a process, on a computer. A URI consists of a prefix and a path to a resource. For example: http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalD isk http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor Cmdlets Supported: Get-Item -RootSDDL <String> Specifies the Security Descriptor Definition Language (SDDL) for the ac cess control entry. This identifies the security settings that are used to authorize access to a specified resource URI. Cmdlets Supported: Get-Item, Set-Item -SDKVersion <String> Specifies the version of the WS-Management plug-in SDK. The only valid value is 1. Cmdlets Supported: Get-Item, Set-Item -Shell <String> Specifies the process string for the custom shell. You can specify envi ronment variables. Cmdlets Supported: Get-Item, Set-Item -ShellTimeout <Unsigned Long Integer> Specifies the length of time before the shell times out due to inactivi ty. Specify the time-out value in milliseconds. Cmdlets Supported: Get-Item, Set-Item -Subject <String> Specifies the entity that is identified by the certificate. Cmdlets Supported: Get-Item -SupportsOptions <Boolean> Specifies whether the plug-in supports the use of options, which are pa ssed within the wsman:OptionSet header in a request message. Cmdlets Supported: Get-Item, Set-Item -Transport <String> Specifies the transport to use to send and receive WS-Management protoc ol requests and responses. The value must be either HTTP or HTTPS. Note: The Transport value is set when creating a Listener. Cmdlets Supported: Get-Item -TrustedHosts <String> List of remote computers that are connected to the local computer throu gh a trusted network connection. Requests are allowed to be sent to co mputers specified in this list when using an authentication scheme and transport that does not allow the client to authenticate the service, s uch as Basic authentication over HTTP. If a server is specified in TrustedHosts, the client does not authentic ate the server's identity, leaving it vulnerable to man-in-the-middle a ttacks. You should only specify hostnames when the network connection is safe from malicious users, such as in a Domain environment. The specified host names can be either Domain Name System (DNS) names o r IP addresses. The following values are valid: -- Blank: No hosts are trusted. -- The asterisk "*" character: All hosts are trusted. A list of host name patterns separated by commas (,) The host name patt erns must be formatted as follows: -- A string that starts with the wildcard character (*). The string mus t contain at least two characters. All the hosts that share the suffix are trusted. -- A string that ends with the wildcard character (*). The string must contain at least two characters. All the hosts that share the prefix ar e trusted. -- All NetBIOS names are trusted (for example, strings that do not cont ain a period). -- A string without the wildcard character (*): The host named by the s tring is trusted. Note: When the TrustedHosts value is set with the Set-Item cmdlet, the Set-Item cmdlet supports an additional parameter -Concatenate. The fol lowing example will append a new value (*.domain2.com) to the old value stored in TrustedHost: Set-Item .\TrustedHosts *.domain2.com -Concatenate -Force Cmdlets Supported: Clear-Item, Get-Item, Set-Item -URI <String> Identifies the URI for which access is authorized based on the value of the Sddl parameter. Cmdlets Supported: Get-Item -URLPrefix <String> A URL prefix on which to accept HTTP or HTTPS requests. This is a strin g containing only the characters a-z, A-Z, 9-0, underscore (_) and back slash (/). The string must not start with or end with a backslash (/). For example, if the computer name is SampleComputer, the WS-Management client would specify http://SampleMachine/URLPrefix in the destination address. Cmdlets Supported: Clear-Item, Get-Item, Set-Item -UserName <String> Specifies the user name for a local account or for a domain account. It cannot have a value of NULL. The client can specify the credentials to use when creating a shell on a computer. The user name must be specified in the domain\user_name fo rmat for a domain account. The user name must be specified in the serve r_name\user_name format for a local account on a server computer. If this structure is used, it must have both the username and password fields specified . It can be used with Basic, Digest, Negotiate, or Ker beros authentication. The client must explicitly specify the credentia ls when either Basic or Digest authentication is used. Cmdlets Supported: Get-Item, Set-Item -Value <String> Specifies the value of an initialization parameter, which is a plug-in- specific value that is used to specify configuration options. Cmdlets Supported: Get-Item, Set-Item -XMLRenderingType <String> Specifies the format in which XML is passed to plug-ins through the WSM AN_DATA object. The following are valid values: Text: Incoming XML data is contained in a WSMAN_DATA_TYPE_TEXT structur e, which represents the XML as a PCWSTR memory buffer. XMLReader: Incoming XML data is contained in a WSMAN_DATA_TYPE_WS_XML_ READER structure, which represents the XML as an XmlReader object, whic h is defined in the WebServices.h header file. Cmdlets Supported: Get-Item, Set-Item -xmlns <String> A string that specifies specifies a Uniform Resource Name (URN) that un iquely identifies the namespace. Cmdlets Supported: Get-Item, Set-Item -lang <String> A string that specifies a language, or a language-region with language and region separated by a hyphen. Cmdlets Supported: Get-Item, Set-Item -HTTP <Short Integer> Specifies the port that the client will use when HTTP is used. By defau lt, HTTP uses port 80. You can specify any value from 1 through 65535. Cmdlets Supported: Get-Item, Set-Item -HTTPS <Short-Integer> Specifies the port that the client will use when HTTPS is used. By defa ult, HTTPS uses port 443. You can specify any value from 1 through 6553 5. Cmdlets Supported: Get-Item, Set-Item -MaxShellRunTime <Unsigned Long Integer> Note: This value is deprecated and the value is no longer used. Cmdlets Supported: Get-Item -MaxShellRunTime <Unsigned Long Integer> Note: This value is deprecated and should not be used. Cmdlets Supported: Get-Item NOTES RELATED LINKS
about_aliases TOPIC about_aliases SHORT DESCRIPTION Describes how to use alternate names for cmdlets and commands in Windows PowerShell. LONG DESCRIPTION An alias is an alternate name or nickname for a cmdlet or for a command element, such as a function, script, file, or executable file. You can use the alias instead of the command name in any Windows PowerShell commands. To create an alias, use the New-Alias cmdlet. For example, the following command creates the "gas" alias for the Get-AuthenticodeSignature cmdlet: new-alias -name gas -value Get-AuthenticodeSignature After you create the alias for the cmdlet name, you can use the alias instead of the cmdlet name. For example, to get the Authenticode signature for the SqlScript.ps1 file, type: get-authenticodesignature sqlscript.ps1 Or, type: gas sqlscript.ps1 If you create "word" as the alias for Microsoft Office Word, you can type "word" instead of the following: "c:\program files\microsoft office\office11\winword.exe" BUILT-IN ALIASES Windows PowerShell includes a set of built-in aliases, including "cd" and "chdir" for the Set-Location cmdlet, and "ls" and "dir" for the Get-ChildItem cmdlet. To get all the aliases on the computer, including the built-in aliases, type: get-alias ALIAS CMDLETS Windows PowerShell includes the following cmdlets, which are designed for working with aliases: - Get-Alias. Gets all the aliases in the current session. - New-Alias. Creates a new alias. - Set-Alias. Creates or changes an alias. - Export-Alias. Exports one or more aliases to a file. - Import-Alias. Imports an alias file into Windows PowerShell. For detailed information about the cmdlets, type: get-help <cmdlet-name> -detailed For example, type: get-help export-alias -detailed CREATING AN ALIAS To create a new alias, use the New-Alias cmdlet. For example, to create the "gh" alias for Get-Help, type: new-alias -name gh -value get-help You can use the alias in commands, just as you would use the full cmdlet name, and you can use the alias with parameters. For example, to get detailed Help for the Get-WmiObject cmdlet, type: get-help get-wmiobject -detailed Or, type: gh get-wmiobject -detailed SAVING ALIASES The aliases that you create are saved only in the current session. To use the aliases in a different session, add the alias to your Windows PowerShell profile. Or, use the Export-Alias cmdlet to save the aliases to a file. For more information, type: get-help about_profile GETTING ALIASES To get all the aliases in the current session, including the built-in aliases, the aliases in your Windows PowerShell profiles, and the aliases that you have created in the current session, type: get-alias To get particular aliases, use the Name parameter of the Get-Alias cmdlet. For example, to get aliases that begin with "p", type: get-alias -name p* To get the aliases for a particular item, use the Definition parameter. For example, to get the aliases for the Get-ChildItem cmdlet type: get-alias -definition Get-ChildItem ALTERNATE NAMES FOR COMMANDS WITH PARAMETERS You can assign an alias to a cmdlet, script, function, or executable file. However, you cannot assign an alias to a command and its parameters. For example, you can assign an alias to the Get-EventLog cmdlet, but you cannot assign an alias to the "get-eventlog -logname system" command. However, you can create a function that includes the command. To create a function, type the word "function" followed by a name for the function. Type the command, and enclose it in braces ({}). For example, the following command creates the syslog function. This function represents the "get-eventlog -logname system" command: function syslog {get-eventlog -logname system} You can now type "syslog" instead of the command. And, you can create aliases for the syslog function. For more information about functions, type: get-help about_functions ALIAS OBJECTS Windows PowerShell aliases are represented by objects that are instances of the System.Management.Automation.AliasInfo class. For more information about this type of object, see "AliasInfo Class" in the Microsoft Developer Network (MSDN) library at http://go.microsoft.com/fwlink/?LinkId=143644. To view the properties and methods of the alias objects, get the aliases. Then, pipe them to the Get-Member cmdlet. For example: get-alias | get-member To view the values of the properties of a specific alias, such as the "dir" alias, get the alias. Then, pipe it to the Format-List cmdlet. For example, the following command gets the "dir" alias. Next, the command pipes the alias to the Format-List cmdlet. Then, the command uses the Property parameter of Format-List with a wildcard character (*) to display all the properties of the "dir" alias. The following command performs these tasks: get-alias -name dir | format-list -property * WINDOWS POWERSHELL ALIAS PROVIDER Windows PowerShell includes the Alias provider. The Alias provider lets you view the aliases in Windows PowerShell as though they were on a file system drive. The Alias provider exposes the Alias: drive. To go into the Alias: drive, type: set-location alias: To view the contents of the drive, type: get-childitem To view the contents of the drive from another Windows PowerShell drive, begin the path with the drive name. Include the colon (:). For example: get-childitem -path alias: To get information about a particular alias, type the drive name and the alias name. Or, type a name pattern. For example, to get all the aliases that begin with "p", type: get-childitem -path alias:p* For more information about the Windows PowerShell Alias provider, type: get-help alias-psprovider SEE ALSO new-alias get-alias set-alias export-alias import-alias get-psprovider get-psdrive about_functions about_profiles about_providers about_Arithmetic_Operators TOPIC about_Arithmetic_Operators SHORT DESCRIPTION Describes the operators that perform arithmetic in Windows PowerShell. LONG DESCRIPTION Arithmetic operators calculate numeric values. You can use one or more arithmetic operators to add, subtract, multiply, and divide values, and to calculate the remainder (modulus) of a division operation. In addition, the addition operator (+) and multiplication operator (*) also operate on strings, arrays, and hash tables. The addition operator concatenates the input. The multiplication operator returns multiple copies of the input. You can even mix object types in an arithmetic statement. The method that is used to evaluate the statement is determined by the type of the leftmost object in the expression. Windows PowerShell supports the following arithmetic operators: Operator Description Example -------- ----------- ------- + Adds integers; concatenates strings, 6+2 arrays, and hash tables. "file" + "name" - Subtracts one value from another 6-2 value. (get-date).date - 1 - Makes a number a negative number. -6+2 -4 * Multiplies integers; copies strings 6*2 and arrays the specified number of "w" * 3 times. / Divides two values. 6/2 % Returns the remainder of a division 7%2 operation. OPERATOR PRECEDENCE Windows PowerShell processes arithmetic operators in the following order: Parentheses () - (for a negative number) *, /, % +, - (for subtraction) Windows PowerShell processes the expressions from left to right according to the precedence rules. The following examples show the effect of the precedence rules: C:\PS> 3+6/3*4 11 C:\PS> 10+4/2 12 C:\PS> (10+4)/2 7 C:\PS> (3+3)/ (1+1) 3 The order in which Windows PowerShell evaluates expressions might differ from other programming and scripting languages that you have used. The following example shows a complicated assignment statement. C:\PS> $a = 0 C:\PS> $b = 1,2 C:\PS> $c = -1,-2 C:\PS> $b[$a] = $c[$a++] C:\PS> $b 1 -1 In this example, the expression $a++ is evaluated before $c[$a++]. Evaluating $a++ changes the value of $a. The variable $a in $b[$a] equals 1, not 0, so the statement assigns a value to $b[1], not $b[0]. ADDING AND MULTIPLYING NON-NUMERIC TYPES You can add numbers, strings, arrays, and hash tables. And, you can multiply numbers, strings, and arrays. However, you cannot multiply hash tables. When you add strings, arrays, or hash tables, the elements are concatenated. When you concatenate collections, such as arrays or hash tables, a new object is created that contains the objects from both collections. If you try to concatenate hash tables that have the same key, the operation fails. For example, the following commands create two arrays and then add them: C:\PS> $a = 1,2,3 C:\PS> $b = "A","B,"C" C:\PS> $a + $b 1 2 3 A B C You can also perform arithmetic operations on objects of different types. The operation that Windows PowerShell performs is determined by the Microsoft .NET Framework type of the leftmost object in the operation. Windows PowerShell tries to convert all the objects in the operation to the .NET Framework type of the first object. If it succeeds in converting the objects, it performs the operation appropriate to the .NET Framework type of the first object. If it fails to convert any of the objects, the operation fails. The following example demonstrates the use of the addition and multiplication operators in operations that include different object types: C:\PS> "file" + 16 file16 C:\PS> $array = 1,2,3 C:\PS> $array + 16 1 2 3 16 C:\PS> $array + "file" 1 2 3 file C:\PS> "file" * 3 filefilefile Because the method that is used to evaluate statements is determined by the leftmost object, addition and multiplication in Windows PowerShell are not strictly commutative. For example, (a + b) does not always equal (b + a), and (a * b) does not always equal (b * a). The following examples demonstrate this principle: C:\PS> "file" + 2 file2 C:\PS> 2 + "file" Cannot convert value "file" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:4 + 2 + < "file" C:\PS> "file" * 3 filefilefile C:\PS> 3 * "file" Cannot convert value "file" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:4 + 3 * < "file" Hash tables are a slightly different case. You can add hash tables. And, you can add a hash table to an array. However, you cannot add any other type to a hash table. The following examples show how to add hash tables to each other and to other objects: C:\PS> $hash1 = @{a=1; b=2; c=3} C:\PS> $hash2 = @{c1="Server01"; c2="Server02"} C:\PS> $hash1 + $hash2 Name Value ---- ----- c2 Server02 a 1 b 2 c1 Server01 c 3 C:\PS> $hash1 + 2 You can add another hash table only to a hash table. At line:1 char:9 + $hash1 + < 2 C:\PS> 2 + $hash1 Cannot convert "System.Collections.Hashtable" to "System.Int32". At line:1 char:4 + 2 + < $hash1 The following examples demonstrate that you can add a hash table to an array. The entire hash table is added to the array as a single object. C:\PS> $array = 1,2,3 C:\PS> $array + $hash1 1 2 3 Name Value ---- ----- a 1 b 2 c 3 C:\PS> $sum = $array + $hash1 C:\PS> $sum.count 4 C:\PS> $sum[3] Name Value ---- ----- a 1 b 2 c 3 PS C:\ps-test> $sum + $hash2 1 2 3 Name Value ---- ----- a 1 b 2 c 3 c2 Server02 The following example shows that you cannot add hash tables that contain the same key: C:\PS> $hash1 = @{a=1; b=2; c=3} C:\PS> $hash2 = @{c="red"} C:\PS> $hash1 + $hash2 Bad argument to operator '+': Item has already been added. Key in dictionary: 'c' Key being added: 'c'. At line:1 char:9 + $hash1 + < $hash2 Although the addition operators are very useful, use the assignment operators to add elements to hash tables and arrays. For more information see about_assignment_operators. The following examples use the += assignment operator to add items to an array: C:\PS> $array 1 2 3 C:\PS> $array + "file" 1 2 3 file C:\PS> $array 1 2 3 C:\PS> $array += "file" C:\PS> $array 1 2 3 file C:\PS> $hash1 Name Value ---- ----- a 1 b 2 c 3 C:\PS> $hash1 += @{e = 5} C:\PS> $hash1 Name Value ---- ----- a 1 b 2 e 5 c 3 Windows PowerShell automatically selects the .NET Framework numeric type that best expresses the result without losing precision. For example: C:\PS> 2 + 3.1 5.1 C:\PS> (2). GetType().FullName System.Int32 C:\PS> (2 + 3.1).GetType().FullName System.Double If the result of an operation is too large for the type, the type of the result is widened to accommodate the result, as in the following example: C:\PS> (512MB).GetType().FullName System.Int32 C:\PS> (512MB * 512MB).GetType().FullName System.Double The type of the result will not necessarily be the same as one of the operands. In the following example, the negative value cannot be cast to an unsigned integer, and the unsigned integer is too large to be cast to Int32: C:\PS> ([int32]::minvalue + [uint32]::maxvalue).gettype().fullname System.Int64 In this example, Int64 can accommodate both types. The System.Decimal type is an exception. If either operand has the Decimal type, the result will be of the Decimal type. If the result is too large for the Decimal type, it will not be cast to Double. Instead, an error results. C:\PS> [Decimal]::maxvalue 79228162514264337593543950335 C:\PS> [Decimal]::maxvalue + 1 Value was either too large or too small for a Decimal. At line:1 char:22 + [Decimal]::maxvalue + < 1 ARITHMETIC OPERATORS AND VARIABLES You can also use arithmetic operators with variables. The operators act on the values of the variables. The following examples demonstrate the use of arithmetic operators with variables: C:\PS> $intA = 6 C:\PS> $intB = 4 C:\PS> $intA + $intB 10 C:\PS> $a = "Windows " C:\PS> $b = "PowerShell " C:\PS> $c = 2 C:\PS> $a + $b + $c Windows PowerShell 2 ARITHMETIC OPERATORS AND COMMANDS Typically, you use the arithmetic operators in expressions with numbers, strings, and arrays. However, you can also use arithmetic operators with the objects that commands return and with the properties of those objects. The following examples show how to use the arithmetic operators in expressions with Windows PowerShell commands: C:\PS> get-date Wednesday, January 02, 2008 1:28:42 PM C:\PS> $day = new-timespan -day 1 C:\PS> get-date + $day Thursday, January 03, 2008 1:34:52 PM C:\PS> get-process | where {($_.ws * 2) -gt 50mb} Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 1896 39 50968 30620 264 1,572.55 1104 explorer 12802 78 188468 81032 753 3,676.39 5676 OUTLOOK 660 9 36168 26956 143 12.20 988 powershell 561 14 6592 28144 110 1,010.09 496 services 3476 80 34664 26092 234 ...45.69 876 svchost 967 30 58804 59496 416 930.97 2508 WINWORD EXAMPLES The following examples show how to use the arithmetic operators in Windows PowerShell: C:\PS> 1 + 1 2 C:\PS> 1 - 1 0 C:\PS> -(6 + 3) -9 C:\PS> 6 * 2 12 C:\PS> 7 / 2 3.5 C:\PS> 7 % 2 1 C:\PS> w * 3 www C:\PS> 3 * "w" Cannot convert value "w" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:4 + 3 * < "w" PS C:\ps-test> "Windows" + " " + "PowerShell" Windows PowerShell PS C:\ps-test> $a = "Windows" + " " + "PowerShell" PS C:\ps-test> $a Windows PowerShell C:\PS> $a[0] W C:\PS> $a = "TestFiles.txt" C:\PS> $b = "C:\Logs\" C:\PS> $b + $a C:\Logs\TestFiles.txt C:\PS> $a = 1,2,3 C:\PS> $a + 4 1 2 3 4 C:\PS> $servers = @{0 = "LocalHost"; 1 = "Server01"; 2 = "Server02"} C:\PS> $servers + @{3 = "Server03"} Name Value ---- ----- 3 Server03 2 Server02 1 Server01 0 LocalHost C:\PS> $servers Name Value ---- ----- 2 Server02 1 Server01 0 LocalHost C:\PS> $servers += @{3 = "Server03"} #Use assignment operator C:\PS> $servers Name Value ---- ----- 3 Server03 2 Server02 1 Server01 0 LocalHost SEE ALSO about_arrays about_assignment_operators about_comparison_operators about_hash_tables about_operators about_variables Get-Date New-TimeSpan about_arrays TOPIC about_Arrays SHORT DESCRIPTION Describes a compact data structure for storing data elements. LONG DESCRIPTION An array is a data structure for storing a collection of data elements of the same type. Windows PowerShell supports data elements, such as string, int (32-bit integer), long (64-bit integer), bool (Boolean), byte, and other Microsoft .NET Framework object types. CREATING AND INITIALIZING AN ARRAY To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator (=). For example, to create an array named $A that contains the seven numeric (int) values of 22, 5, 10, 8, 12, 9, and 80, type: $A = 22,5,10,8,12,9,80 You can also create and initialize an array by using the range operator (..). For example, to create and initialize an array named "$B" that contains the values 5 through 8, type: $B = 5..8 As a result, $B contains four values: 5, 6, 7, and 8. When no data type is specified, Windows PowerShell creates each array as an object array (type: object[]). To determine the data type of an array, use the GetType() method. For example, to determine the data type of the $a array, type: $a.gettype() To create a strongly typed array, that is, an array that can contain only values of a particular type, cast the variable as an array type, such as string[], long[], or int32[]. To cast an array, precede the variable name with an array type enclosed in brackets. For example, to create a 32-bit integer array named $ia containing four integers (1500, 2230, 3350, and 4000), type: [int32[]]$ia = 1500,2230,3350,4000 As a result, the $ia array can contain only integers. You can create arrays that are cast to any supported type in the Microsoft .NET Framework. For example, the objects that Get-Process retrieves to represent processes are of the System.Diagnostics.Process type. To create a strongly typed array of process objects, enter the following command: [Diagnostics.Process[]]$zz = Get-Process You can populate an array by using the output of a cmdlet, function, or statement. For example, the following statement creates an array that contains the processes that start with the letters "co" and that are running on the current computer: $LocalProcesses = get-process co* If the statement gets only a single process, the $LocalProcesses variable would not be an array. To ensure the command creates an array, use the array subexpression operator, @, as shown in the following example: $LocalProcesses = @(get-process co*) Even if the command returns a single process, the $LocalProcesses variable is an array. Even if it has only one member, you can treat it like any other array. For example, you can add other objects to it. For more information, see about_Operators. READING AN ARRAY You can refer to an array by using its variable name, such as $A or $a. Windows PowerShell is not case-sensitive. To display all the elements in the array, type the array name. For example: $a You can refer to the elements in an array by using an index, beginning at position 0. Enclose the index number in brackets. For example, to display the first element in the $a array, type: $a[0] To display the third element in the $a array, type: $a[2] Negative numbers count from the end of the array. For example, "-1" refers to the last element of the array. To display the last three elements of the array, type: $a[-3..-1] However, be cautious when using this notation. $a[0..-2] This command does not refer to all the elements of the array, except for the last one. It refers to the first, last, and second-to-last elements in the array. You can use the range operator to display a subset of all the values in an array. For example, to display the data elements at index position 1 through 3, type: $a[1..3] You can use the plus operator (+) to combine a range with a list of elements in an array. For example, to display the elements at index positions 0, 2, and 4 through 6, type: $a[0,2+4..6] To determine how many items are in an array, combine the range with the length property of an array. For example, to display the elements from index position 2 to the end of the array, type: $a[2..($a.length-1)] The length is set to -1 because the index begins at position 0. Therefore, in a three-element array (1,2,3), the index of the third element is 2, which is one less than the length of the array. You can also use looping constructs, such as Foreach, For, and While loops, to refer to the elements in an array. For example, to use a Foreach loop to display the elements in the $a array, type: foreach ($element in $a) {$element} The Foreach loop iterates through the array and returns each value in the array until reaching the end of the array. The For loop is useful when you are incrementing counters while examining the elements in an array. For example, to return every other value in an array by using a For loop, type: for ($i = 0; $i -le ($a.length - 1); $i += 2) {$a[$i]} You can use a While loop to display the elements in an array until a defined condition is no longer true. For example, to display the elements in the $a array while the array index is less than 4, type: $i=0 while($i -lt 4) {$a[$i]; $i++} To learn about the properties and methods of an array, such as the Length property and the SetValue method, use the InputObject parameter of the Get-Member cmdlet. When you pipe an array to Get-Member, it displays information about the objects in the array. When you use the InputObject parameter, it displays information about the array. To find the properties and methods of the $a array, type: get-member -inputobject $a MANIPULATING AN ARRAY You can change the elements in an array, add an element to an array, and combine the values from two arrays into a third array. To change the value of a particular element in an array, specify the array name and the index of the element that you want to change, and then use the assignment operator (=) to specify a new value for the element. For example, to change the value of the second item in the $a array (index position 1) to 10, type: $a[1] = 10 You can also use the SetValue method of an array to change a value. The following example changes the second value (index position 1) of the $a array to 500: $a.SetValue(500,1) You can append an element to an existing array by using the += operator. This operator adds to an existing value. When the operator is used on an element of an array, it increases the value of the element. When the operator is used on the array itself, it appends the value. For example, to append an element with a value of 200 to the $a array, type: $a += 200 It is not easy to delete elements from an array, but you can create a new array that contains only selected elements of an existing array. For example, to create the $t array with all the elements in the $a array except for the value at index position 2, type: $t = $a[0,1 + 3..($a.length - 1)] To combine two arrays into a single array, use the plus operator (+). The following example creates two arrays, combines them, and then displays the resulting combined array. $x = 1,3 $y = 5,9 $z = $x + $y As a result, the $z array contains 1, 3, 5, and 9. To delete an array, use the Remove-Item cmdlet to delete the variable that contains the array. The following command specifies the element "a" in the Variable: drive. remove-item variable:a (For more information about the Variable: drive, see the Variable provider Help topic.) SEE ALSO about_Assignment_Operators about_Hash_Tables about_Operators about_For about_Foreach about_While about_Assignment_Operators TOPIC about_assignment_operators SHORT DESCRIPTION Describes how to use operators to assign values to variables. LONG DESCRIPTION Assignment operators assign one or more values to a variable. They can perform numeric operations on the values before the assignment. Windows PowerShell supports the following assignment operators. Operator Description ------- ----------- = Sets the value of a variable to the specified value. += Increases the value of a variable by the specified value, or appends the specified value to the existing value. -= Decreases the value of a variable by the specified value. *= Multiplies the value of a variable by the specified value, or appends the specified value to the existing value. /= Divides the value of a variable by the specified value. %= Divides the value of a variable by the specified value and then assigns the remainder (modulus) to the variable. ++ Increases the value of a variable, assignable property, or array element by 1. -- Decreases the value of a variable, assignable property, or array element by 1. SYNTAX The syntax of the assignment operators is as follows: <assignable-expression> <assignment-operator> <value> Assignable expressions include variables and properties. The value can be a single value, an array of values, or a command, expression, or statement. The increment and decrement operators are unary operators. Each has prefix and postfix versions. <assignable-expression><operator> <operator><assignable-expression> The assignable expression must a number or it must be convertible to a number. ASSIGNING VALUES Variables are named memory spaces that store values. You store the values in variables by using the assignment operator (=). The new value can replace the existing value of the variable, or you can append a new value to the existing value. The basic assignment operator is the equal sign (=)(ASCII 61). For example, the following statement assigns the value Windows PowerShell to the $MyShell variable: $MyShell = "Windows PowerShell" When you assign a value to a variable in Windows PowerShell, the variable is created if it did not already exist. For example, the first of the following two assignement statements creates the $a variable and assigns a value of 6 to $a. The second assignment statement assigns a value of 12 to $a. The first statement creates a new variable. The second statement changes only its value: $a = 6 $a = 12 Variables in Windows PowerShell do not have a specific data type unless you cast them. When a variable contains only one object, the variable takes the data type of that object. When a variable contains a collection of objects, the variable has the System.Object data type. Therefore, you can assign any type of object to the collection. The following example shows that you can add process objects, service objects, strings, and integers to a variable without generating an error: $a = get-process $a += get-service $a += "string" $a += 12 Because the assignment operator (=) has a lower precedence than the pipeline operator (|), parentheses are not required to assign the result of a command pipeline to a variable. For example, the following command sorts the services on the computer and then assigns the sorted services to the $a variable: $a = get-service | sort name You can also assign the value created by a statement to a variable, as in the following example: $a = if ($b -lt 0) { 0 } else { $b } This example assigns 0 to the $a variable if the value of $b is less than 0. It assigns the value of $b to $a if the value of $b is not less than zero. THE ASSIGNMENT OPERATOR (=) The assignment operator (=) assigns values to variables. If the variable already has a value, the assignment operator (=) replaces the value without warning. The following statement assigns the integer value 6 to the $a variable: $a = 6 To assign a string value to a variable, enclose the string value in quotation marks, as follows: $a = "baseball" To assign an array (multiple values) to a variable, separate the values with commas, as follows: $a = "apple", "orange", "lemon", "grape" To assign a hash table to a variable, use the standard hash table notation in Windows PowerShell. Type an at sign (@) followed by key/value pairs that are separated by semicolons (;) and enclosed in braces ({ }). For example, to assign a hash table to the $a variable, type: $a = @{one=1; two=2; three=3} To assign hexadecimal values to a variable, precede the value with "0x". Windows PowerShell converts the hexadecimal value (0x10) to a decimal value (in this case, 16) and assigns that value to the $a variable. For example, to assign a value of 0x10 to the $a variable, type: $a = 0x10 To assign an exponential value to a variable, type the root number, the letter "e", and a number that represents a multiple of 10. For example, to assign a value of 3.1415 to the power of 1,000 to the $a variable, type: $a = 3.1415e3 Windows PowerShell can also convert kilobytes (KB), megabytes (MB), and gigabytes (GB) into bytes. For example, to assign a value of 10 kilobytes to the $a variable, type: $a = 10kb THE ASSIGNMENT BY ADDITION OPERATOR (+=) The assignment by addition operator (+=) either increments the value of a variable or appends the specified value to the existing value. The action depends on whether the variable has a numeric or string type and whether the variable contains a single value (a scalar) or multiple values (a collection). The += operator combines two operations. First, it adds, and then it assigns. Therefore, the following statements are equivalent: $a += 2 $a = ($a + 2) When the variable contains a single numeric value, the += operator increments the existing value by the amount on the right side of the operator. Then, the operator assigns the resulting value to the variable. The following example shows how to use the += operator to increase the value of a variable: C:\PS> $a = 4 C:\PS> $a += 2 C:\PS> $a 6 When the value of the variable is a string, the value on the right side of the operator is appended to the string, as follows: C:\PS> $a = "Windows" C:\PS> $a +- " PowerShell" C:\PS> $a Windows PowerShell When the value of the variable is an array, the += operator appends the values on the right side of the operator to the array. Unless the array is explicitly typed by casting, you can append any type of value to the array, as follows: C:\PS> $a = 1,2,3 C:\PS> $a += 2 C:\PS> $a 1 2 3 2 C:\PS> $a += "String" C:\PS> $a 1 2 3 2 String When the value of a variable is a hash table, the += operator appends the value on the right side of the operator to the hash table. However, because the only type that you can add to a hash table is another hash table, all other assignments fail. For example, the following command assigns a hash table to the $a variable. Then, it uses the += operator to append another hash table to the existing hash table, effectively adding a new key/value pair to the existing hash table. This command succeeds, as shown in the output: C:\PS> $a = @{a = 1; b = 2; c = 3} C:\PS> $a += @{mode = "write"} C:\PS> $a Name Value ---- ----- a 1 b 2 mode write c 3 The following command attempts to append an integer (1) to the hash table in the $a variable. This command fails: C:\PS> $a = @{a = 1; b = 2; c = 3} C:\PS> $a += 1 You can add another hash table only to a hash table. At line:1 char:6 + $a += < 1 THE ASSIGNMENT BY SUBTRACTION OPERATOR (-=) The assignment by subtraction operator (-=) decrements the value of a variable by the value that is specified on the right side of the operator. This operator cannot be used with string variables, and it cannot be used to remove an element from a collection. The -= operator combines two operations. First, it subtracts, and then it assigns. Therefore, the following statements are equivalent: $a -= 2 $a = ($a - 2) The following example shows how to use of the -= operator to decrease the value of a variable: C:\PS> $a = 8 C:\PS> $a -= 2 C:\PS> $a 6 You can also use the -= assignment operator to decrease the value of a member of a numeric array. To do this, specify the index of the array element that you want to change. In the following example, the value of the third element of an array (element 2) is decreased by 1: C:\PS> $a = 1,2,3 C:\PS> $a[2] -= 1. C:\PS> $a 1 2 2 You cannot use the -= operator to delete the values of a variable. To delete all the values that are assigned to a variable, use the Clear-Item or Clear-Variable cmdlets to assign a value of $null or "" to the variable. $a = $null To delete a particular value from an array, use array notation to assign a value of $null to the particular item. For example, the following statement deletes the second value (index position 1) from an array: C:\PS> $a = 1,2,3 C:\PS> $a 1 2 3 C:\PS> $a[1] = $null C:\PS> $a 1 3 To delete a variable, use the Remove-Variable cmdlet. This method is useful when the variable is explicitly cast to a particular data type, and you want an untyped variable. The following command deletes the $a variable: remove-variable a THE ASSIGNMENT BY MULTIPLICATION OPERATOR (*=) The assignment by multiplication operator (*=) multiplies a numeric value or appends the specified number of copies of the string value of a variable. When a variable contains a single numeric value, that value is multiplied by the value on the right side of the operator. For example, the following example shows how to use the *= operator to multiply the value of a variable: C:\PS> $a = 3 C:\PS> $a *= 4 C:\PS> $a 12 In this case, the *= operator combines two operations. First, it multiplies, and then it assigns. Therefore, the following statements are equivalent: $a *= 2 $a = ($a * 2) When a variable contains a string value, Windows PowerShell appends the specified number of strings to the value, as follows: C:\PS> $a = "file" C:\PS> $a *= 4 C:\PS> $a filefilefilefile To multiply an element of an array, use an index to identify the element that you want to multiply. For example, the following command multiplies the first element in the array (index position 0) by 2: $a[0] *= 2 THE ASSIGNMENT BY DIVISION OPERATOR (/=) The assignment by division operator (/=) divides a numeric value by the value that is specified on the right side of the operator. The operator cannot be used with string variables. The /= operator combines two operations. First, it divides, and then it assigns. Therefore, the following two statements are equivalent: $a /= 2 $a = ($a / 2) For example, the following command uses the /= operator to divide the value of a variable: C:\PS> $a = 8 C:\PS> $a /=2 C:\PS> $a 4 To divide an element of an array, use an index to identify the element that you want to change. For example, the following command divides the second element in the array (index position 1) by 2: $a[1] /= 2 THE ASSIGNMENT BY MODULUS OPERATOR (%=) The assignment by modulus operator (%=) divides the value of a variable by the value on the right side of the operator. Then, the %= operator assigns the remainder (known as the modulus) to the variable. You can use this operator only when a variable contains a single numeric value. You cannot use this operator when a variable contains a string variable or an array. The %= operator combines two operations. First, it divides and determines the remainder, and then it assigns the remainder to the variable. Therefore, the following statements are equivalent: $a %= 2 $a = ($a % 2) The following example shows how to use the %= operator to save the modulus of a quotient: C:\PS> $a = 7 C:\PS> $a %= 4 C:\PS> $a 3 THE INCREMENT AND DECREMENT OPERATORS The increment operator (++) increases the value of a variable by 1. When you use the increment operator in a simple statement, no value is returned. To view the result, display the value of the variable, as follows: C:\PS> $a = 7 C:\PS> ++$a C:\PS> $a 8 To force a value to be returned, enclose the variable and the operator in parentheses, as follows: C:\PS> $a = 7 C:\PS> (++$a) 8 The increment operator can be placed before (prefix) or after (postfix) a variable. The prefix version of the operator increments a variable before its value is used in the statement, as follows: C:\PS> $a = 7 C:\PS> $c = ++$a C:\PS> $a 8 C:\PS> $c 8 The postfix version of the operator increments a variable after its value is used in the statement. In the following example, the $c and $a variables have different values because the value is assigned to $c before $a changes: C:\PS> $a = 7 C:\PS> $c = $a++ C:\PS> $a 8 C:\PS> $c 7 The decrement operator (--) decreases the value of a variable by 1. As with the increment operator, no value is returned when you use the operator in a simple statement. Use parentheses to return a value, as follows: C:\PS> $a = 7 C:\PS> --$a C:\PS> $a 6 C:\PS> (--$a) 5 The prefix version of the operator decrements a variable before its value is used in the statement, as follows: C:\PS> $a = 7 C:\PS> $c = --$a C:\PS> $a 6 C:\PS> $c 6 The postfix version of the operator decrements a variable after its value is used in the statement. In the following example, the $d and $a variables have different values because the value is assigned to $d before $a changes: C:\PS> $a = 7 C:\PS> $d = $a-- C:\PS> $a 6 C:\PS> $d 7 MICROSOFT .NET FRAMEWORK TYPES By default, when a variable has only one value, the value that is assigned to the variable determines the data type of the variable. For example, the following command creates a variable that has the Integer (System.Int32) type: $a = 6 To find the .NET Framework type of a variable, use the GetType method and its FullName property, as follows. Be sure to include the parentheses after the GetType method name, even though the method call has no arguments: C:\PS> $a = 6 C:\PS> $a.gettype().fullname System.Int32 To create a variable that contains a string, assign a string value to the variable. To indicate that the value is a string, enclose it in quotation marks, as follows: C:\PS> $a = "6" C:\PS> $a.gettype().fullname System.String If the first value that is assigned to the variable is a string, Windows PowerShell treats all operations as string operations and casts new values to strings. This occurs in the following example: C:\PS> $a = "file" C:\PS> $a += 3 C:\PS> $a file3 If the first value is an integer, Windows PowerShell treats all operations as integer operations and casts new values to integers. This occurs in the following example: C:\PS> $a = 6 C:\PS> $a += "3" C:\PS> $a 9 You can cast a new scalar variable as any .NET Framework type by placing the type name in brackets that precede either the variable name or the first assignment value. When you cast a variable, you can determine the types of data that can be stored in the variable. And, you can determine how the variable behaves when you manipulate it. For example, the following command casts the variable as a string type: C:\PS> [string]$a = 27 C:\PS> $a += 3 C:\PS> $a 273 The following example casts the first value, instead of casting the variable: $a = [string]27 When you cast a variable to a specific type, the common convention is to cast the variable, not the value. However, you cannot recast the data type of an existing variable if its value cannot be converted to the new data type. To change the data type, you must replace its value, as follows: C:\PS> $a = "string" C:\PS> [int]$a Cannot convert value "string" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:8 + [int]$a C:\PS> [int]$a =3 In addition, when you precede a variable name with a data type, the type of that variable is locked unless you explicitly override the type by specifying another data type. If you try to assign a value that is incompatible with the existing type, and you do not explicitly override the type, Windows PowerShell displays an error, as shown in the following example: C:\PS> $a = 3 C:\PS> $a = "string" C:\PS> [int]$a = 3 C:\PS> $a = "string" Cannot convert value "string" to type "System.Int32". Error: "Input string was not in a correct format." At line:1 char:3 + $a < = "string" C:\PS> [string]$a = "string" In Windows PowerShell, the data types of variables that contain multiple items in an array are handled differently from the data types of variables that contain a single item. Unless a data type is specifically assigned to an array variable, the data type is always System.Object []. This data type is specific to arrays. Sometimes, you can override the default type by specifying another type. For example, the following command casts the variable as a string [] array type: [string []] $a = "one", "two", "three" Windows PowerShell variables can be any .NET Framework data type. In addition, you can assign any fully qualified .NET Framework data type that is available in the current process. For example, the following command specifies a System.DateTime data type: [system.datetime]$a = "5/31/2005" The variable will be assigned a value that conforms to the System.DateTime data type. The value of the $a variable would be the following: Tuesday, May 31, 2005 12:00:00 AM ASSIGNING MULTIPLE VARIABLES In Windows PowerShell, you can assign values to multiple variables by using a single command. The first element of the assignment value is assigned to the first variable, the second element is assigned to the second variable, the third element to the third variable, and so on. For example, the following command assigns the value 1 to the $a variable, the value 2 to the $b variable, and the value 3 to the $c variable: C:\PS> $a, $b, $c = 1, 2, 3 If the assignment value contains more elements than variables, all the remaining values are assigned to the last variable. For example, the following command contains three variables and five values: $a, $b, $c = 1, 2, 3, 4, 5 Therefore, Windows PowerShell assigns the value 1 to the $a variable and the value 2 to the $b variable. It assigns the values 3, 4, and 5 to the $c variable. To assign the values in the $c variable to three other variables, use the following format: $d, $e, $f = $c This command assigns the value 3 to the $d variable, the value 4 to the $e variable, and the value 5 to the $f variable. You can also assign a single value to multiple variables by chaining the variables. For example, the following command assigns a value of "three" to all four variables: $a = $b = $c = $d = "three" VARIABLE-RELATED CMDLETS In addition to using an assignment operation to set a variable value, you can also use the Set-Variable cmdlet. For example, the following command uses Set-Variable to assign an array of 1, 2, 3 to the $a variable. Set-Variable -name a -value 1, 2, 3 SEE ALSO about_Arrays about_Hash_Tables about_Variables Clear-Variable Remove-Variable Set-Variable 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. $_ 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. $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. $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]). $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. $EventSubscriber Contains a PSEventSubscriber object that represents the event subscribe r 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 of a ForEach-Object loop. You can use the properties and methods of enumerators on the value of the $ForEach variable. This variable exists only while the For loop is running. It is deleted when the loop is completed. $Home Contains the full path of the user's home directory. This variable is the equivalent of the %homedrive%%homepath% environment variables, typically C:\Documents and Settings\<user>. $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 An enumerator that contains the input that is passed to a function. The $Input variable is case-sensitive and is available only in functions and in script blocks. (Script blocks are essentially unnamed functions.) In the Process block of a function, the $Input variable contains the object that is currently in the pipeline. When the Process block is completed, the value of $Input is NULL. If the function does not have a Process block, the value of $Input is available to the End block, and it contains all the 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 -not match 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 object with information about the current command, such as a script, function, or script block. You can use the information in the object, 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 script that is running. $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 Contains a NULL or empty value. You can use this variable to represent NULL in commands and scripts instead of using the string "NULL". The string can be interpreted as TRUE if it is converted to a non-empty string or a non-zero integer. $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 active parameters 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. $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 $PSScriptRoot Contains the directory from which the script module is being executed. This variable allows scripts to use the module path to access other resources. $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 stac k 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. $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. $SourceArgs 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 (System.Management.Automation.PSEventArgs) object that Get-Event returns. $SourceEventArgs Contains an object that represents the first event argument that derive s 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 SourceArgs property of the PSEventArgs (System.Management.Automation.PSEventArgs) object that Get-Event returns. $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_Break TOPIC about_Break SHORT DESCRIPTION Describes a statement you can use to immediately exit Foreach, For, While, Do, or Switch statements. LONG DESCRIPTION When a Break statement appears in a loop, such as a Foreach, For, Switch, or While loop, the Break statement causes Windows PowerShell to immediately exit the loop. In a Switch construct that does not loop, Break causes Windows PowerShell to exit the Switch code block. A Break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as Foreach, For, or While, in a script. When you use a label, Break exits the specified loop. Break exits the specified loop, regardless of which loop the Break statement is in. The following example shows how to use a Break statement to exit a For statement: for($i=1; $i -le 10; $i++) { Write-Host $i break } In this example, the Break statement exits the For loop when the $i variable equals 1. Even though the For statement evaluates to True until $i is greater than 10, Windows PowerShell reaches the break statement the first time the For loop is run. It is more common to use the Break statement in a loop where an inner condition must be met. Consider the following Foreach statement example: $i=0 $varB = 10,20,30,40 foreach ($val in $varB) { $i++ if ($val -eq 30) { break } } Write-Host "30 was found in array position $i" In this example, the Foreach statement iterates the $varB array. Each time the code block is run, the $i variable is incremented by 1. The If statement evaluates to False the first two times the loop is run. The third time the loop is run, $i equals 3, and the $val variable equals 30. At this point, the Break statement runs, and the Foreach loop exits. You break out of the other looping statements in the same way you break out of the Foreach loop. In the following example, the Break statement exits a While statement when a DivideByZeroException exception is trapped using the Trap statement. $i = 3 while ($true) { trap [DivideByZeroException] { Write-Host "divide by zero trapped" break } 1 / $i-- } A Break statement can include a label. If you use the Break keyword with a label, Windows PowerShell exits the labeled loop instead of exiting the current loop. The syntax for a label is as follows (this example shows a label in a While loop): :myLabel while (<condition>) { <statement list>} The label is a colon followed by a name that you assign. The label must be the first token in a statement, and it must be followed by the looping keyword, such as While. In Windows PowerShell, only loop keywords, such as Foreach, For, and While can have a label. Break moves execution out of the labeled loop. In embedded loops, this has a different result than the Break keyword has when it is used by itself. This schematic example has a While statement with a For statement: :myLabel while (<condition 1>) { for ($item in $items) { if (<condition 2>) { break myLabel } $item = $x # A statement inside the For-loop } } $a = $c # A statement after the labeled While-loop If condition 2 evaluates to True, the execution of the script skips down to the statement after the labeled loop. In the example, execution starts again with the statement "$a = $c". You can nest many labeled loops, as shown in the following schematic example. :red while (<condition1>) { :yellow while (<condition2>) { while (<condition3>) { if ($a) {break} if ($b) {break red} if ($c) {break yellow} } # After innermost loop } # After "yellow" loop } # After "red" loop If the $b variable evaluates to True, execution of the script resumes after the loop that is labeled "red". If the $c variable evaluates to True, execution of the script control resumes after the loop that is labeled "yellow". If the $a variable evaluates to True, execution resumes after the innermost loop. No label is needed. Windows PowerShell does not limit how far labels can resume execution. The label can even pass control across script and function call boundaries. The Break keyword is used to leave the Switch construct. For example, the following Switch statement uses Break statements to test for the most specific condition: $var = "word2" switch -regex ($var) { "word2" { Write-Host "Exact" $_ break } "word.*" { Write-Host "Match on the prefix" $_ break } "w.*" { Write-Host "Match on at least the first letter" $_ break } default { Write-Host "No match" $_ break } } In this example, the $var variable is created and initialized to a string value of "word2". The Switch statement uses the Regex class to match the variable value first with the term "word2". (The Regex class is a regular expression Microsoft .NET Framework class.) Because the variable value and the first test in the Switch statement match, the first code block in the Switch statement runs. When Windows PowerShell reaches the first Break statement, the Switch statement exits. If the four Break statements are removed from the example, all four conditions are met. This example uses the break statement to display results when the most specific condition is met. SEE ALSO about_Comparison_Operators about_For about_Foreach about_Switch about_While about_command_precedence TOPIC about_Command_Precedence SHORT DESCRIPTION Describes how Windows PowerShell determines which command to run. LONG DESCRIPTION This topic explains how Windows PowerShell determines which command to run, especially when a session contains more than one command with the same name. It also explains how to run commands that do not run by default, and it explains how to avoid command-name conflicts in your session. COMMAND PRECEDENCE When a session includes commands that have the same name, Windows PowerShell uses the following rules to decide which command to run. These rules become very important when you add commands to your session from modules, snap-ins, and other sessions. -- If you specify the path to a command, Windows PowerShell runs the command at the location specified by the path. For example, the following command runs the FindDocs.ps1 script in the C:\TechDocs directory: C:\TechDocs\FindDocs.ps1 As a security feature, Windows PowerShell does not run executable (native) commands, including Windows PowerShell scripts, unless the command is located in a path that is listed in the Path environment variable ($env:path) or unless you specify the path to the script file. To run a script that is in the current directory, specify the full path, or type a dot (.) to represent the current directory. For example, to run the FindDocs.ps1 file in the current directory, type: .\FindDocs.ps1 -- If you do not specify a path, Windows PowerShell uses the following precedence order when it runs commands: 1. Alias 2. Function 3. Cmdlet 4. Native Windows commands Therefore, if you type "help", Windows PowerShell first looks for an alias named "help", then a function named "Help", and finally a cmdlet named "Help". It runs the first "help" item that it finds. For example, assume you have a function named Get-Map. Then, you add or import a cmdlet named Get-Map. By default, Windows PowerShell runs the function when you type "Get-Map". -- When the session contains items of the same type that have the same name, such as two cmdlets with the same name, Windows PowerShell runs the item that was added to the session most recently. For example, assume you have a cmdlet named Get-Date. Then, you import another cmdlet named Get-Date. By default, Windows PowerShell runs the most-recently imported cmdlet when you type "Get-Date". HIDDEN and REPLACED ITEMS As a result of these rules, items can be replaced or hidden by items with the same name. -- Items are "hidden" or "shadowed" if you can still access the original item, such as by qualifying the item name with a module or snap-in name. For example, if you import a function that has the same name as a cmdlet in the session, the cmdlet is hidden (but not replaced) because it was imported from a snap-in or module. -- Items are "replaced" or "overwritten" if you can no longer access the original item. For example, if you import a variable that has the same name as a a variable in the session, the original variable is replaced and is no longer accessible. You cannot qualify a variable with a module name. Also, if you type a function at the command line and then import a function with the same name, the original function is replaced and is no longer accessible. RUNNING HIDDEN COMMANDS You can run particular commands by specifying item properties that distinguish the command from other commands that might have the same name. You can use this method to run any command, but it is especially useful for running hidden commands. Use this method as a best practice when writing scripts that you intend to distribute because you cannot predict which commands might be present in the session in which the script runs. QUALIFIED NAMES You can run commands that have been imported from a Windows PowerShell snap-in or module or from another session by qualifying the command name with the name of the module or snap-in in which it originated. You can qualify commands, but you cannot qualify variables or aliases. For example, if the Get-Date cmdlet from the Microsoft.PowerShell.Utility snap-in is hidden by an alias, function, or cmdlet with the same name, yo u can run it by using the snap-in-qualified name of the cmdlet: Microsoft.PowerShell.Utility\Get-Date To run a New-Map command that was added by the MapFunctions module, use its module-qualified name: MapFunctions\New-Map To find the snap-in or module from which a command was imported, use the following Get-Command command format: get-command <command-name> | format-list -property Name, PSSnapin, Mo dule For example, to find the source of the Get-Date cmdlet, type: get-command get-date | format-list -property Name, PSSnapin, Module Name : Get-Date PSSnapIn : Microsoft.PowerShell.Utility Module : CALL OPERATOR You can also use the Call operator (&) to run any command that you can get by using a Get-ChildItem (the alias is "dir"), Get-Command, or Get-Module command. To run a command, enclose the Get-Command command in parentheses, and use the Call operator (&) to run the command. &(get-command ...) - or - &(dir ... ) For example, if you have a function named Map that is hidden by an alias named Map, use the following command to run the function. &(get-command -name map -type function) - or - &(dir function:\map) You can also save your hidden command in a variable to make it easier to run. For example, the following command saves the Map function in the $myMap variable and then uses the Call operator to run it. $myMap = (get-command -name map -type function) &($myMap) If a command originated in a module, you can use the following format to run it. & <PSModuleInfo-object> <command> For example, to run the Add-File cmdlet in the FileCommands module, use the following command sequence. $FileCommands = get-module -name FileCommands & $FileCommands Add-File REPLACED ITEMS Items that have not been imported from a module or snap-in, such as functions, variables, and aliases that you create in your session or that you add by using a profile can be replaced by commands that have the same name. If they are replaced, you cannot access them. Variables and aliases are always replaced even if they have been imported from a module or snap-in because you cannot use a call operator or a qualified name to run them. For example, if you type a Get-Map function in your session, and you import a function called Get-Map, the original function is replaced. You cannot retrieve it in the current session. AVOIDING NAME CONFLICTS The best way to manage command name conflicts is to prevent them. When you name your commands, use a name that is very specific or is likely to be unique. For example, add your initials or company name acronym to the nouns in your commands. Also, when you import commands into your session from a Windows PowerShel l module or from another session, use the Prefix parameter of the Import-Module or Import-PSSession cmdlet to add a prefix to the nouns in the names of commands. For example, the following command avoids any conflict with the Get-Date and Set-Date cmdlets that come with Windows PowerShell when you import the DateFunctions module. import-module -name DateFunctions -prefix ZZ For more information, see Import-Module and Import-PSSession. SEE ALSO about_Path_Syntax about_Aliases about_Functions Alias (provider) Function (provider) Get-Command Import-Module Import-PSSession about_Command_Syntax TOPIC about_Command_Syntax SHORT DESCRIPTION Describes the notation used for Windows PowerShell syntax in Help. LONG DESCRIPTION The Get-Help cmdlet displays the parameter usage for a cmdlet. The Get-Help cmdlet uses the following special symbols: Angle brackets (<>) indicate placeholder text. Brackets ([]) indicate optional items. Braces ({}) indicate a choice among values. Some cmdlets have more than one set of parameters. Distinct parameter sets can share some parameters. The Get-Help cmdlet displays all the parameter sets for a cmdlet. You can find additional information about a parameter in the parameter description and in the parameter attribute table. To view complete information about a parameter, use the Full or Parameter parameters of Get-Help. Syntax Windows PowerShell cmdlet Help, Help topics, and other documentation use the following notation for cmdlets in syntax descriptions. <cmdlet name> -<Required Parameter name> <Required parameter Value> [-<Optional Parameter name> <Optional Parameter Value>] [-<Optional Switch Parameter>] [-<Optional Parameter Name>] <Required parameter Value> The following is the syntax for the New-Alias cmdlet. New-Alias [-Force] [-PassThru] [-Scope <string>] [-Option {None | ReadOnly | Constant | Private | AllScope}] [-Description <string>] [-Name] <string> [-Value] <string> [-confirm] [-whatif] [<CommonParameters>] The syntax is capitalized for readability, but Windows Powershell is case-insensitive. Parameters appear in order. The order of parameters is significant only when the parameter names are optional. If you do not specify parameter names when you use a cmdlet, Windows PowerShell assigns values to parameters by position and by type. Parameter names are preceded by a hyphen (-). Switch parameters appear without a value type. Other parameters appear with the Microsoft .NET Framework type of the argument required or with an enumeration of possible values. For more information about .NET Framework types, see http://go.microsoft.com/fwlink/?LinkId=143682. Angle brackets (<>) indicate placeholder text. This text can describe the type of an item (such as a string or a Process object). It can also be a placeholder for one or more common parameters. Brackets ([]) indicate optional items. A parameter can be optional, or the name of a required parameter can be optional. Switch parameters are always optional. Braces ({}) appear around the values of an enumeration. In the example of the New-Alias cmdlet, the Option parameter can have any of the listed values. Optional Items Brackets ([]) surround optional items. For example, in the New-Alias cmdlet syntax description, the Scope parameter is optional. This is indicated in the syntax by the brackets around the parameter name and type: [-Scope <string>] Both the following examples are correct uses of the New-Alias cmdlet: New-Alias -Name utd -Value Update-TypeData New-Alias -Name utd -Value Update-TypeData -Scope global A parameter name can be optional even if the value for that parameter is required. This is indicated in the syntax by the brackets around the parameter name but not the parameter type, as in this example from the New-Alias cmdlet: [-Name] <string> [-Value] <string> The following commands correctly use the New-Alias cmdlet. The commands produce the same result: New-Alias -Name utd -Value Update-TypeData New-Alias -Name utd Update-TypeData New-Alias utd -Value Update-TypeData New-Alias utd Update-TypeData If the parameter name is not included in the statement as typed, Windows PowerShell tries to use the position of the arguments to assign the values to parameters. The following example is not complete: New-Alias utd This cmdlet requires values for both the Name and Value parameters. In syntax examples, brackets are also used in naming and casting to .NET Framework types. In this context, brackets do not indicate an element is optional. Array Arguments Brackets are also used in syntax descriptions to represent an array. The following example shows the syntax for the Restart-Service cmdlet: Restart-Service [-Name] <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Force] [-PassThru] [-Confirm] [-WhatIf] [<CommonParameters>] The Name parameter requires an argument. Specifically, it requires the name of the service to be restarted. It can take a comma-separated list of services, as in the following example: Restart-Service RasAuto, RasMan, RemoteAccess SEE ALSO Get-Help about_Comment_Based_Help TOPIC about_Comment_Based_Help SHORT DESCRIPTION Describes how to write comment-based Help topics for functions and scripts. LONG DESCRIPTION You can write comment-based Help topics for functions and scripts by using special Help comment keywords. The Get-Help cmdlet displays comment-based Help in the same format in which it displays the cmdlet Help topics that are generated from XML files. Users can use all of the parameters of Get-Help, such as Detailed, Full, Example, and Online, to display function and script Help. You can also write XML-based Help files for scripts and functions by using Help comment keywords, and you can redirect users to a different Help file. This topic explains how to write Help topics for functions and scripts. For information about how to display Help topics for functions and scripts, see Get-Help. SYNTAX FOR COMMENT-BASED HELP The syntax for comment-based Help is as follows: # .< help keyword> # <help content> -or - <# .< help keyword> < help content> #> Comment-based Help is written as a series of comments. You can type a comment symbol (#) before each line of comments, or you can use the "<#" an d "#>" symbols to create a comment block. All the lines within the comment block a re interpreted as comments. All of the lines in a comment-based Help topic must be contiguous. If a comment-based Help topic follows a comment that is not part of the Help topic, there must be at least one blank line between the last non-Help comment line and the beginning of the comment-based Help. Keywords define each section of comment-based Help. Each comment-based Help keyword is preceded by a dot (.). The keywords can appear in any order. The keyword names are not case-sensitive. For example, the Description keyword precedes a description of a function o r script. <# .Description Get-Function displays the name and syntax of all functions in the s ession. #> The comment block must contain at least one keyword. Some of the keywords, such as EXAMPLE, can appear many times in the same comment block. The Help content for each keyword begins on the line after the keyword and can span multiple lines. SYNTAX FOR COMMENT-BASED HELP IN FUNCTIONS Comment-based Help for a function can appear in one of three locations: -- At the beginning of the function body. -- At the end of the function body. -- Before the Function keyword. There cannot be more than one blank line between the last line of the function Help and the Function keyword. For example: function MyFunction { <# .< help keyword> < help content> #> <function commands> } -or - function MyFunction { <function commands> <# .< help keyword> < help content> #> } -or - <# .< help keyword> < help content> #> function MyFunction { } SYNTAX FOR COMMENT-BASED HELP IN SCRIPTS Comment-based Help for a script can appear in one of the following two locations in the script. -- At the beginning of the script file. Script Help can be preceded in the script only by comments and blank lines. -- If the first item in the script body (after the Help) is a function declaration, there must be at least two blank lines between the end of t he script Help and the function declaration. Otherwise, the Help is interpreted as being Help for the function, not Help for the script. -- At the end of the script file. For example: <# .< help keyword> < help content> #> function MyFunction { } -or- function MyFunction { } <# .< help keyword> < help content> #> COMMENT-BASED HELP KEYWORDS The following are valid comment-based Help keywords. They are listed in the order in which they typically appear in a Help topic along with their intended use. These keywords can appear in any order in the comment-based Help, and they are not case-sensitive. .SYNOPSIS A brief description of the function or script. This keyword can be used only once in each topic. .DESCRIPTION A detailed description of the function or script. This keyword can be used only once in each topic. .PARAMETER <Parameter-Name> The description of a parameter. You can include a Parameter keyword for each parameter in the function or script syntax. The Parameter keywords can appear in any order in the comment block, bu t the function or script syntax determines the order in which the paramet ers (and their descriptions) appear in Help topic. To change the order, change the syntax. You can also specify a parameter description by placing a comment in th e function or script syntax immediately before the parameter variable nam e. If you use both a syntax comment and a Parameter keyword, the descripti on associated with the Parameter keyword is used, and the syntax comment i s ignored. .EXAMPLE A sample command that uses the function or script, optionally followed by sample output and a description. Repeat this keyword for each exampl e. .INPUTS The Microsoft .NET Framework types of objects that can be piped to the function or script. You can also include a description of the input objects. .OUTPUTS The .NET Framework type of the objects that the cmdlet returns. You can also include a description of the returned objects. .NOTES Additional information about the function or script. .LINK The name of a related topic. Repeat this keyword for each related topic . This content appears in the Related Links section of the Help topic. The Link keyword content can also include a Uniform Resource Identifier (URI) to an online version of the same Help topic. The online version opens when you use the Online parameter of Get-Help. The URI must begin with "http" or "https". .COMPONENT The technology or feature that the function or script uses, or to which it is related. This content appears when the Get-Help command includes the Component parameter of Get-Help. .ROLE The user role for the Help topic. This content appears when the Get-Hel p command includes the Role parameter of Get-Help. .FUNCTIONALITY The intended use of the function. This content appears when the Get-Hel p command includes the Functionality parameter of Get-Help. .FORWARDHELPTARGETNAME <Command-Name> Redirects to the Help topic for the specified command. You can redirect users to any Help topic, including Help topics for a function, script, cmdlet, or provider. .FORWARDHELPCATEGORY <Category> Specifies the Help category of the item in ForwardHelpTargetName. Valid values are Alias, Cmdlet, HelpFile, Function, Provider, General, FAQ, Glossary, ScriptCommand, ExternalScript, Filter, or All. Use this keyword to avoid conflicts when there are commands with the same name. .REMOTEHELPRUNSPACE <PSSession-variable> Specifies a session that contains the Help topic. Enter a variable that contains a PSSession. This keyword is used by the Export-PSSession cmdlet to find the Help topics for the exported commands. .EXTERNALHELP <XML Help File Path> Specifies the path to an XML-based Help file for the script or function . In Windows Vista and later versions of Windows, if the specified path to the XML file contains UI-culture-specific subdirectories, Get-Help searches the subdirectories recursively for an XML file with the name of the script or function in accordance with the language fallback standards established for Windows Vista, just as it does for all XML-based Help topics. For more information about the cmdlet Help XML-based Help file format, see "How to Create Cmdlet Help" in the MSDN (Microsoft Developer Networ k) library at http://go.microsoft.com/fwlink/?LinkID=123415. AUTOGENERATED CONTENT The name, syntax, parameter list, parameter attribute table, common parameters, and remarks are automatically generated by the Get-Help cmdlet. Name: The Name section of a function Help topic is taken from the functio n name in the function syntax. The Name of a script Help topic is taken from the script file name. To change the name or its capitalization, change the function syntax or the script file name. Syntax: The Syntax section of the Help topic is generated from the function or script syntax. To add detail to the Help topic syntax, such as the .NET Framework type of a parameter, add the detail to the synta x. If you do not specify a parameter type, the "Object" type is inserted as the default value. Parameter List: The Parameter list in the Help topic is generated from the function or script syntax and from the descriptions that you add by using th e Parameters keyword. The function parameters appear in the "Paramete rs" section of the Help topic in the same order that they appear in the function or script syntax. The spelling and capitalization of parameter names is also taken from the syntax; it is not affected by the parameter name specified by the Parameter keyword. Common Parameters: The common parameters are added to the syntax and parameter list of the Help topic, even if they have no effect. For more informatio n about the common parameters, see about_CommonParameters. Parameter Attribute Table: Get-Help generates the table of parameter attributes that appears when you use the Full or Parameter parameter of Get-Help. The value of the Required, Position, and Default value attributes is taken from the function or script syntax. Remarks: The Remarks section of the Help topic is automatically generated from the function or script name. You cannot change or affect its content. EXAMPLES Example 1: Comment-based Help for a Function The following sample function includes comment-based Help: function Add-Extension { param ([string]$Name,[string]$Extension = "txt") $name = $name + "." + $extension $name <# .SYNOPSIS Adds a file name extension to a supplied name. .DESCRIPTION Adds a file name extension to a supplied name. Takes any strings for the file name or extension. .PARAMETER Name Specifies the file name. .PARAMETER Extension Specifies the extension. "Txt" is the default. .INPUTS None. You cannot pipe objects to Add-Extension. .OUTPUTS System.String. Add-Extension returns a string with the extension or file name. .EXAMPLE C:\PS> extension -name "File" File.txt .EXAMPLE C:\PS> extension -name "File" -extension "doc" File.doc .EXAMPLE C:\PS> extension "File" "doc" File.doc .LINK Online version: http://www.fabrikam.com/extension.html .LINK Set-Item #> } The results are as follows: C:\PS> get-help add-extension -full NAME Add-Extension SYNOPSIS Adds a file name extension to a supplied name. SYNTAX Add-Extension [[-Name] <String>] [[-Extension] <String>] [<CommonPa rameters>] DESCRIPTION Adds a file name extension to a supplied name. Takes any strings fo r the file name or extension. PARAMETERS -Name Specifies the file name. Required? false Position? 0 Default value Accept pipeline input? false Accept wildcard characters? -Extension Specifies the extension. "Txt" is the default. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? <CommonParameters> This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable, -OutBuffer and -OutVariable. For more information, type "get-help about_commonparameters". INPUTs None. You cannot pipe objects to Add-Extension. OUTPUTS System.String. Add-Extension returns a string with the extension or file name. -------------------------- EXAMPLE 1 -------------------------- C:\PS> extension -name "File" File.txt -------------------------- EXAMPLE 2 -------------------------- C:\PS> extension -name "File" -extension "doc" File.doc -------------------------- EXAMPLE 3 -------------------------- C:\PS> extension "File" "doc" File.doc RELATED LINKS Online version: http://www.fabrikam.com/extension.html Set-Item Example 2: Parameter Descriptions in Function Syntax This example is the same as the previous one, except that the parameter descriptions are inserted in the function syntax. This format is most useful when the descriptions are brief. function Add-Extension { param ( [string] # Specifies the file name. $name, [string] # Specifies the file name extension. "Txt" is the default. $extension = "txt" ) $name = $name + "." + $extension $name <# .SYNOPSIS Adds a file name extension to a supplied name. .DESCRIPTION Adds a file name extension to a supplied name. Takes any strings fo r the file name or extension. .INPUTS None. You cannot pipe objects to Add-Extension. .OUTPUTS System.String. Add-Extension returns a string with the extension or file name. .EXAMPLE C:\PS> extension -name "File" File.txt .EXAMPLE C:\PS> extension -name "File" -extension "doc" File.doc .EXAMPLE C:\PS> extension "File" "doc" File.doc .LINK Online version: http://www.fabrikam.com/extension.html .LINK Set-Item #> } Example 3: Comment-based Help for a Script The following sample script includes comment-based Help. Notice the blank lines between the closing "#>" and the Param statement . In a script that does not have a Param statement, there must be at leas t two blank lines between the final comment in the Help topic and the fir st function declaration. Without these blank lines, Get-Help associates th e Help topic with the function, not the script. <# .SYNOPSIS Performs monthly data updates. .DESCRIPTION The Update-Month.ps1 script updates the registry with new data gener ated during the past month and generates a report. .PARAMETER InputPath Specifies the path to the CSV-based input file. .PARAMETER OutputPath Specifies the name and path for the CSV-based output file. By defaul t, MonthlyUpdates.ps1 generates a name from the date and time it runs, and saves the output in the local directory. .INPUTS None. You cannot pipe objects to Update-Month.ps1. .OUTPUTS None. Update-Month.ps1 does not generate any output. .EXAMPLE C:\PS> .\Update-Month.ps1 .EXAMPLE C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv .EXAMPLE C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPath C:\Reports\2009\January.csv #> param ([string]$InputPath, [string]$OutPutPath) function Get-Data { } ... The following command gets the script Help. Because the script is not in a directory that is listed in the Path environment variable, the Get-Help command that gets the script Help must specify the script path . PS C:\ps-test> get-help .\update-month.ps1 -full NAME C:\ps-test\Update-Month.ps1 SYNOPSIS Performs monthly data updates. SYNTAX C:\ps-test\Update-Month.ps1 [-InputPath] <String> [[-OutputPath ] <String>] [<CommonParameters>] DESCRIPTION The Update-Month.ps1 script updates the registry with new data generated during the past month and generates a report. PARAMETERS -InputPath Specifies the path to the CSV-based input file. Required? true Position? 0 Default value Accept pipeline input? false Accept wildcard characters? -OutputPath Specifies the name and path for the CSV-based output file. B y default, MonthlyUpdates.ps1 generates a name from the date and time it runs, and saves the output in the local director y. Required? false Position? 1 Default value Accept pipeline input? false Accept wildcard characters? <CommonParameters> This cmdlet supports the common parameters: -Verbose, -Debug , -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariab le, -OutBuffer and -OutVariable. For more information, type, "get-help about_commonparameters". INPUTS None. You cannot pipe objects to Update-Month.ps1. OUTPUTS None. Update-Month.ps1 does not generate any output. -------------------------- EXAMPLE 1 -------------------------- C:\PS> .\Update-Month.ps1 -------------------------- EXAMPLE 2 -------------------------- C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -------------------------- EXAMPLE 3 -------------------------- C:\PS> .\Update-Month.ps1 -inputpath C:\Data\January.csv -outputPat h C:\Reports\2009\January.csv RELATED LINKS Example 4: Redirecting to an XML File You can write XML-based Help topics for functions and scripts. Although comment-based Help is easier to implement, XML-based Help is required if you want more precise control over Help content or if you are translating Help topics into multiple languages. The following example shows the first few lines of the Update-Month.ps1 script. The script uses the ExternalHelp keyword to specify the path to an XML-based Help topic for the script. # .ExternalHelp C:\MyScripts\Update-Month-Help.xml param ([string]$InputPath, [string]$OutPutPath) function Get-Data { } ... The following example shows the use of the ExternalHelp keyword in a function. function Add-Extension { param ([string] $name, [string]$extension = "txt") $name = $name + "." + $extension $name # .ExternalHelp C:\ps-test\Add-Extension.xml } Example 5: Redirecting to a Different Help Topic The following code is an excerpt from the beginning of the built-in Help function in Windows PowerShell, which displays one screen of Help text at a time. Because the Help topic for the Get-Help cmdlet describe s the Help function, the Help function uses the ForwardHelpTargetName and ForwardHelpCategory keywords to redirect the user to the Get-Help cmdle t Help topic. function help { <# .FORWARDHELPTARGETNAME Get-Help .FORWARDHELPCATEGORY Cmdlet #> [CmdletBinding(DefaultParameterSetName='AllUsersView')] param( [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)] [System.String] ${Name}, ... The following command uses this feature: C:\PS> get-help help NAME Get-Help SYNOPSIS Displays information about Windows PowerShell cmdlets and conce pts. ... SEE ALSO about_Functions about_Functions_Advanced_Parameters about_Scripts "How to Write Cmdlet Help" (http://go.microsoft.com/fwlink/?LinkID=123415) about_CommonParameters TOPIC about_CommonParameters SHORT DESCRIPTION Describes the parameters that can be used with any cmdlet. LONG DESCRIPTION The common parameters are a set of cmdlet parameters that you can use with any cmdlet. They are implemented by Windows PowerShell, not by the cmdlet developer, and they are automatically available to any cmdlet. You can use the common parameters with any cmdlet, but they might not have an effect on all cmdlets. For example, if a cmdlet does not generate any verbose output, using the Verbose common parameter has no effect. Several common parameters override system defaults or preferences that you set by using the Windows PowerShell preference variables. Unlike the preference variables, the common parameters affect only the commands in which they are used. In addition to the common parameters, many cmdlets offer the WhatIf and Confirm risk mitigation parameters. Cmdlets that involve risk to the system or to user data usually offer these parameters. The common parameters are: -Verbose -Debug -WarningAction -WarningVariable -ErrorAction -ErrorVariable -OutVariable -OutBuffer The risk mitigation parameters are: -WhatIf -Confirm For more information about preference variables, type: help about_preference_variables Common Parameter Descriptions -Verbose[:{$true | $false}] Displays detailed information about the operation performed by the command. This information resembles the information in a trace or in a transaction log. This parameter works only when the command generates a verbose message. For example, this parameter works when a command contains the Write-Verbose cmdlet. The Verbose parameter overrides the value of the $VerbosePreference variable for the current command. Because the default value of the $VerbosePreference variable is SilentlyContinue, verbose messages are not displayed by default. Valid values: $true (-Verbose:$true) has the same effect as -Verbose. $false (-Verbose:$false) suppresses the display of verbose messages. Use this parameter when the value of $VerbosePreference is not SilentlyContinue (the default). -Debug[:{$true | $false}] Displays programmer-level detail about the operation performed by the command. This parameter works only when the command generates a debugging message. For example, this parameter works when a command contains the Write-Debug cmdlet. The Debug parameter overrides the value of the $DebugPreference variable for the current command. Because the default value of the $DebugPreference variable is SilentlyContinue, debugging messages are not displayed by default. Valid values: $true (-Debug:$true). Has the same effect as -Debug. $false (-Debug:$false). Suppresses the display of debugging messages when the value of the $DebugPreference is not SilentlyContinue (the default). -WarningAction[:{SilentlyContinue | Continue | Inquire | Stop}] Determines how the cmdlet responds to a warning from the command. "Continue" is the default value. This parameter works only when the command generates a warning message. For example, this parameter works when a command contains the Write-Warning cmdlet. The WarningAction parameter overrides the value of the $WarningPreference variable for the current command. Because the default value of the $WarningPreference variable is Continue, warnings are displayed and execution continues unless you use the WarningAction parameter. Valid Values: SilentlyContinue. Suppresses the warning message and continues executing the command. Continue. Displays the warning message and continues executing the command. "Continue" is the default value. Inquire. Displays the warning message and prompts you for confirmation before continuing execution. This value is rarely used. Stop. Displays the warning message and stops executing the command. -WarningVariable [+]<variable-name> Stores warnings about the command in the specified variable. To append the warnings to the variable content, instead of replacing any warnings that might already be stored there, type a plus sign (+) before the variable name. For example, the following command creates the $a variable and then stores any warnings in it: get-process -id 6 -WarningVariable a The following command adds any warnings to the $a variable: get-process -id 2 -WarningVariable +a The following command displays the contents of $a: $a You can use this parameter to create a variable that contains only warnings from specific commands. You can use array notation, such as $a[0] or $warning[1,2] to refer to specific warnings stored in the variable. -ErrorAction[:{SilentlyContinue | Continue | Inquire | Stop)] Determines how the cmdlet responds to a non-terminating error from the command. This parameter works only when the command generates a debugging message. For example, this parameters works when a command contains the Write-Error cmdlet. The ErrorAction parameter overrides the value of the $ErrorActionPreference variable for the current command. Because the default value of the $ErrorActionPreference variable is Continue, error messages are displayed and execution continues unless you use the ErrorAction parameter. The ErrorAction parameter has no effect on terminating errors (such as missing data, parameters that are not valid, or insufficient permissions) that prevent a command from completing successfully. Valid values: SilentlyContinue. Suppresses the error message and continues executing the command. Continue. Displays the error message and continues executing the command. "Continue" is the default value. Inquire. Displays the error message and prompts you for confirmation before continuing execution. This value is rarely used. Stop. Displays the error message and stops executing the command. -ErrorVariable [+]<variable-name> Stores error messages about the command in the specified variable and in the $Error automatic variable. For more information, type the following command: get-help about_automatic_variables By default, new error messages overwrite error messages that are already stored in the variable. To append the error message to the variable content, type a plus sign (+) before the variable name. For example, the following command creates the $a variable and then stores any errors in it: get-process -id 6 -ErrorVariable a The following command adds any error messages to the $a variable: get-process -id 2 -ErrorVariable +a The following command displays the contents of $a: $a You can use this parameter to create a variable that contains only error messages from specific commands. The $Error automatic variable contains error messages from all the commands in the session. You can use array notation, such as $a[0] or $error[1,2] to refer to specific errors stored in the variables. -OutVariable [+]<variable-name> Stores output objects from the command in the specified variable and displays it at the command line. To add the output to the variable, instead of replacing any output that might already be stored there, type a plus sign (+) before the variable name. For example, the following command creates the $out variable and stores the process object in it: get-process powershell -OutVariable out The following command adds the process object to the $out variable: get-process iexplore -OutVariable +out The following command displays the contents of the $out variable: $out -OutBuffer <Int32> Determines the number of objects to accumulate in a buffer before any objects are sent through the pipeline. If you omit this parameter, objects are sent as they are generated. This resource management parameter is designed for advanced users. When you use this parameter, Windows PowerShell does not call the next cmdlet in the pipeline until the number of objects generated equals OutBuffer + 1. Thereafter, it sends all objects as they are generated. Risk Management Parameter Descriptions -WhatIf[:{$true | $false}] Displays a message that describes the effect of the command, instead of executing the command. The WhatIf parameter overrides the value of the $WhatIfPreference variable for the current command. Because the default value of the $WhatIfPreference variable is 0 (disabled), WhatIf behavior is not performed without the WhatIf parameter. For more information, type the following command: get-help about_preference_variables Valid values: $true (-WhatIf:$true). Has the same effect as -WhatIf. $false (-WhatIf:$false). Suppresses the automatic WhatIf behavior that results when the value of the $WhatIfPreference variable is 1. For example, the following command uses the WhatIf parameter in a Remove-Item command: PS> remove-item date.csv -whatif Instead of removing the item, Windows PowerShell lists the operations it would perform and the items that would be affected. This command produces the following output: What if: Performing operation "Remove File" on Target "C:\ps-test\date.csv". -Confirm[:{$true | $false}] Prompts you for confirmation before executing the command. The Confirm parameter overrides the value of the $ConfirmPreference variable for the current command. The default value is High. For more information, type the following command: get-help about_preference_variables Valid values: $true (-WhatIf:$true). Has the same effect as -Confirm. $false(-Confirm:$false). Suppresses automatic confirmation, which occurs when the value of $ConfirmPreference is less than or equal to the estimated risk of the cmdlet. For example, the following command uses the Confirm parameter with a Remove-Item command. Before removing the item, Windows PowerShell lists the operations it would perform and the items that would be affected, and asks for approval. PS C:\ps-test> remove-item tmp*.txt -confirm This command produces the following output: Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target " C:\ps-test\tmp1.txt [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): SEE ALSO about_Preference_Variables Write-Debug Write-Warning Write-Error Write-Verbose about_Comparison_Operators TOPIC about_Comparison_Operators SHORT DESCRIPTION Describes the operators that compare values in Windows PowerShell. LONG DESCRIPTION Comparison operators let you specify conditions for comparing values and finding values that match specified patterns. To use a comparison operator, specify the values that you want to compare together with an operator that separates these values. By default, all comparison operators are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a "c". For example, the case-sensitive version of "-eq" is "-ceq". To make the case-insensitivity explicit, precede the operator with an "i". For example, the explicitly case-insensitive version of "-eq" is "ieq". All comparison operators except the containment operators (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean value when the input to the operator (the value on the left side of the operator) is a single value (a scalar). When the input is a collection of values, the containment operators and the type operators return any matching values. If there are no matches in a collection, these operators do not return anything. The containment operators and type operators always return a Boolean value. Windows PowerShell supports the following comparison operators. -eq Description: Equal to. Includes an identical value. Example: C:\PS> "abc", "def" -eq "abc" abc -ne Description: Not equal to. Includes a different value. Example: C:\PS> "abc", "def" -ne "abc" def -gt Description: Greater-than. Example: C:\PS> 8 -gt 6 True -ge Description: Greater-than or equal to. Example: C:\PS> 8 -ge 8 True -lt Description: Less-than. Example: C:\PS> 8 -lt 6 False -le Description: Less-than or equal to. Example: C:\PS> 6 -le 8 True -like Description: Match using the wildcard character (*). Example: C:\PS> "Windows PowerShell" -like "*shell" True -notlike Description: Does not match using the wildcard character (*). Example: C:\PS> "Windows PowerShell" -notlike "*shell" False -match Description: Matches a string using regular expressions. When the input is scalar, it populates the $Matches automatic variable. Example: C:\PS> "Sunday" -match "sun" True C:\PS> $matches Name Value ---- ----- 0 sun -notmatch Description: Does not match a string. Uses regular expressions. When the input is scalar, it populates the $Matches automatic variable. Example: C:\PS> "Sunday" -notmatch "sun" False C:\PS> $matches Name Value ---- ----- 0 sun -contains Description: Containment operator. Includes an identical value that is not part of a value. Always returns a Boolean value. Example: C:PS> "abc", "def" -contains "def" True -notcontains Description: Containment operator. Does not include an identical value. Always returns Boolean. Example: C:PS> "Windows", "PowerShell" -notcontains "Shell" True -replace Description: Replace operator. Changes the specified elements of a value. Example: C:\PS> "Get-Process" -replace "Get", "Stop" Stop-Process Equality Operators The equality operators (-eq, -ne) return a value of TRUE or the matches when one or more of the input values is identical to the specified pattern. The entire pattern must match an entire value. The following examples show the effect of the equal to operator: C:PS> 1,2,3 -eq 2 2 C:PS> "PowerShell" -eq "Shell" False C:PS> "Windows", "PowerShell" -eq "Shell" C:PS> C:\PS> "abc", "def", "123" -eq "def" def Containment Operators The containment operators (-contains and -notcontains) are similar to the equality operators. However, the containment operators always return a Boolean value, even when the input is a collection. Also, unlike the equality operators, the containment operators return a value as soon as they detect the first match. The equality operators evaluate all input and then return all the matches in the collection. The following examples show the effect of the -contains operator: C:PS> 1,2,3 -contains 2 True C:PS> "PowerShell" -contains "Shell" False C:PS> "Windows", "PowerShell" -contains "Shell" False C:\PS> "abc", "def", "123" -contains "def" True C:\PS> "true", "blue", "six" -contains "true" True The following example shows how the containment operators differ from the equal to operator. The containment operators return a value of TRUE on th e first match. C:\PS> 1,2,3,4,5,4,3,2,1 -eq 2 2 2 C:\PS> 1,2,3,4,5,4,3,2,1 -contains 2 True In a very large collection, the -contains operator returns results quicker than the equal to operator. Match Operators The match operators (-match and -notmatch) find elements that match or do not match a specified pattern using regular expressions. The syntax is: <string[]> -match <regular-expression> <string[]> -notmatch <regular-expression> The following examples show some uses of the -match operator: C:\PS> "Windows", "PowerShell" -match ".shell" PowerShell C:\PS> (get-command get-member -syntax) -match "-view" True C:\PS> (get-command get-member -syntax) -notmatch "-path" True C:\PS> (get-content servers.txt) -match "^Server\d\d" Server01 Server02 The match operators search only in strings. They cannot search in arrays of integers or other objects. The -match and -notmatch operators populate the $Matches automatic variable when the input (the left-side argument) to the operator is a single scalar object. When the input is scalar, the -match and -notmatch operators return a Boolean value and set the value of the $Matches automatic variable to the matched components of the argument. If the input is a collection, the -match and -notmatch operators return the matching members of that collection, but the operator does not populate the $Matches variable. For example, the following command submits a collection of strings to the -match operator. The -match operator returns the items in the collect ion that match. It does not populate the $Matches automatic variable. C:\PS> "Sunday", "Monday", "Tuesday" -match "sun" Sunday C:\PS> $matches C:\PS> In contrast, the following command submits a single string to the -match operator. The -match operator returns a Boolean value and populates the $Matches automatic variable. C:\PS> "Sunday" -match "sun" True C:\PS> $matches Name Value ---- ----- 0 Sun The -notmatch operator populates the $Matches automatic variable when the input is scalar and the result is False, that it, when it detects a match. C:\PS> "Sunday" -notmatch "rain" True C:\PS> $matches C:\PS> C:\PS> "Sunday" -notmatch "day" False C:\PS> $matches C:\PS> Name Value ---- ----- 0 day Replace Operator The -replace operator replaces all or part of a value with the specified value using regular expressions. You can use the -replace operator for many administrative tasks, such as renaming files. For example, the following command changes the file name extensions of all .gif files to .jpg: Get-ChildItem | Rename-Item -NewName { $_ -replace '.gif$','.jpg$' } The syntax of the -replace operator is as follows, where the <original> placeholder represents the characters to be replaced, and the <substitute> placeholder represents the characters that will replace them: <input> <operator> <original>, By default, the -replace operator is case-insensitive. To make it case sensitive, use -creplace. To make it explicitly case-insensitive, use -ireplace. Consider the following examples: C:\PS> "book" -replace "B", "C" Cook C:\PS> "book" -ireplace "B", "C" Cook C:\PS> "book" -creplace "B", "C" book Bitwise Operators Windows PowerShell supports the standard bitwise operators, including bitwise-AND (-band), and inclusive and exclusive bitwise-OR operators (-bor and -bxor). Beginning in Windows PowerShell 2.0, all bitwise operators work with 64-bit integers. Windows PowerShell supports the following bitwise operators. Operator Description Example -------- ---------------------- ------------------- -band Bitwise AND C:\PS> 10 -band 3 2 -bor Bitwise OR (inclusive) C:\PS> 10 -bor 3 11 -bxor Bitwise OR (exclusive) C:\PS> 10 -bxor 3 9 Bitwise operators act on the binary format of a value. For example, the bit structure for the number 10 is 00001010 (based on 1 byte), and the bit structure for the number 3 is 00000011. When you use a bitwise operator to compare 10 to 3, the individual bits in each byte are compared. In a bitwise AND operation, the resulting bit is set to 1 only when both input bits are 1. 00001010 (10) 00000011 ( 3) ------------------ bAND 00000010 ( 2) In a bitwise OR (inclusive) operation, the resulting bit is set to 1 when either or both input bits are 1. The resulting bit is set to 0 only when both input bits are set to 0. 00001010 (10) 00000011 ( 3) ------------------ bOR (inclusive) 00001011 (11) In a bitwise OR (exclusive) operation, the resulting bit is set to 1 only when one input bit is 1. 00001010 (10) 00000011 ( 3) ------------------ bXOR (exclusive) 00001001 ( 9) SEE ALSO about_Operators about_Regular_Expressions about_Wildcards Compare-Object about_Continue TOPIC about_Continue SHORT DESCRIPTION Describes how the Continue statement immediately returns the program flow to the top of a program loop. LONG DESCRIPTION In a script, the Continue statement immediately returns the program flow to the top of the innermost loop that is controlled by a For, Foreach, or While statement. The Continue keyword supports labels. A label is a name you assign to a statement in a script. For information about labels, see about_Break. In the following example, program flow returns to the top of the While loop if the $ctr variable is equal to 5. As a result, all the numbers between 1 and 10 are displayed except for 5: while ($ctr -lt 10) { $ctr +=1 if ($ctr -eq 5) {continue} Write-Host $ctr } Note that in a For loop, execution continues at the first line in the loop. If the arguments of the For statement test a value that is modified by the For statement, an infinite loop may result. SEE ALSO about_Comparison_Operators about_Core_Commands TOPIC about_Core_Commands SHORT DESCRIPTION Lists the cmdlets that are designed for use with Windows PowerShell providers. LONG DESCRIPTION Windows PowerShell includes a set of cmdlets that are specifically designed to manage the items in the data stores that are exposed by Windows PowerShell providers. You can use these cmdlets in the same ways to manage all the different types of data that the providers make available to you. For more information about providers, type "get-help about_providers". For example, you can use the Get-ChildItem cmdlet to list the files in a file system directory, the keys under a registry key, or the items that are exposed by a provider that you write or download. The following is a list of the Windows PowerShell cmdlets that are designed for use with providers: ChildItem cmdlets Get-ChildItem Content cmdlets Add-Content Clear-Content Get-Content Set-Content Item cmdlets Clear-Item Copy-Item Get-Item Invoke-Item Move-Item New-Item Remove-Item Rename-Item Set-Item ItemProperty cmdlets Clear-ItemProperty Copy-ItemProperty Get-ItemProperty Move-ItemProperty New-ItemProperty Remove-ItemProperty Rename-ItemProperty Set-ItemProperty Location cmdlets Get-Location Pop-Location Push-Location Set-Location Path cmdlets Join-Path Convert-Path Split-Path Resolve-Path Test-Path PSDrive cmdlets Get-PSDrive New-PSDrive Remove-PSDrive PSProvider cmdlets Get-PSProvider For more information about a cmdlet, type "get-help <cmdlet-name>". SEE ALSO about_Providers about_data_sections TOPIC about_Data_Sections SHORT DESCRIPTION Explains Data sections, which isolate text strings and other read-only data from script logic. LONG DESCRIPTION Scripts that are designed for Windows PowerShell can have one or more Data sections that contain only data. You can include one or more Data sections in any script, function, or advanced function. The content of the Data section is restricted to a specified subset of the Windows PowerShell scripting language. Separating data from code logic makes it easier to identify and manage both logic and data. It lets you have separate string resource files for text, such as error messages and Help strings. It also isolates the code logic, which facilitates security and validation tests. In Windows PowerShell, the Data section is used to support script internationalization. You can use Data sections to make it easier to isolate, locate, and process strings that will be translated into many user interface (UI) languages. The Data section is a Windows PowerShell 2.0 feature. Scripts with Data sections will not run in Windows PowerShell 1.0 without revision. Syntax The syntax for a Data section is as follows: DATA [-supportedCommand <cmdlet-name>] { <Permitted content> } The Data keyword is required. It is not case-sensitive. The permitted content is limited to the following elements: - All Windows PowerShell operators, except -match - If, Else, and ElseIf statements - The following automatic variables: $PsCulture, $PsUICulture, $True, $False, and $Null - Comments - Pipelines - Statements separated by semicolons (;) - Literals, such as the following: a 1 1,2,3 "Windows PowerShell 2.0" @( "red", "green", "blue" ) @{ a = 0x1; b = "great"; c ="script" } [XML] @' <p> Hello, World </p> '@ - Cmdlets that are permitted in a Data section. By default, only the ConvertFrom-StringData cmdlet is permitted. - Cmdlets that you permit in a Data section by using the SupportedCommand parameter. When you use the ConvertFrom-StringData cmdlet in a Data section, you can enclose the key/value pairs in single-quoted or double-quoted strings or in single-quoted or double-quoted here-strings. However, strings that contain variables and subexpressions must be enclosed in single-quoted strings or in single-quoted here-strings so that the variables are not expanded and th e subexpressions are not executable. SupportedCommand The SupportedCommand parameter allows you to indicate that a cmdlet or function generates only data. It is designed to allow users to include cmdlets and functions in a data section that they have written or tested. The value of SupportedCommand is a comma-separated list of one or more cmdlet or function names. For example, the following data section includes a user-written cmdlet, Format-XML, that formats data in an XML file: DATA -supportedCommand Format-XML { Format-XML -strings string1, string2, string3 } Using a Data Section To use the content of a Data section, assign it to a variable and use variable notation to access the content. For example, the following data section contains a ConvertFrom-StringData command that converts the here-string into a hash table. The hash table is assigned to the $TextMsgs variable. The $TextMsgs variable is not part of the data section. $TextMsgs = DATA { ConvertFrom-StringData -stringdata @' Text001 = Windows 7 Text002 = Windows Server 2008 R2 '@ } To access the keys and values in hash table in $TextMsgs, use the following commands. $TextMsgs.Text001 $TextMsgs.Text002 EXAMPLES Simple data strings. DATA { "Thank you for using my Windows PowerShell Organize.pst script." "It is provided free of charge to the community." "I appreciate your comments and feedback." } Strings that include permitted variables. DATA { if ($null) { "To get help for this cmdlet, type get-help new-dictionary." } } A single-quoted here-string that uses the ConvertFrom-StringData cmdlet: DATA { ConvertFrom-StringData -stringdata @' Text001 = Windows 7 Text002 = Windows Server 2008 R2 '@ } A double-quoted here-string that uses the ConvertFrom-StringData cmdlet: DATA { ConvertFrom-StringData -stringdata @" Msg1 = To start, press any key. Msg2 = To exit, type "quit". "@ } A data section that includes a user-written cmdlet that generates data: DATA -supportedCommand Format-XML { Format-XML -strings string1, string2, string3 } SEE ALSO about_Automatic_Variables about_Comparison_Operators about_Hash_Tables about_If about_Operators about_Quoting_Rules about_Script_Internationalization ConvertFrom-StringData Import-LocalizedData about_debuggers TOPIC about_Debuggers SHORT DESCRIPTION Describes the Windows PowerShell debugger. LONG DESCRIPTION Debugging is the process of examining a script while it is running in order to identify and correct errors in the script instructions. The Windows PowerShell debugger is designed to help you examine and identify errors and inefficiencies in your scripts. Note: The Windows PowerShell debugger does not run remotely. To debug a script on a remote computer, copy the script to the local computer. You can use the features of the Windows PowerShell debugger to examine a Windows PowerShell script, function, command, or expression while it is running. The Windows PowerShell debugger includes a set of cmdlets that let you set breakpoints, manage breakpoints, and view the call stack. Windows PowerShell offers several methods that you can use to debug scripts, functions, and commands. Method 1: The Set-PsDebug cmdlet offers basic script debugging features, including stepping and tracing. For more information, type: "get-help set-psdebug". Method 2: Use the Set-StrictMode cmdlet to detect references to uninitialized variables, to references to non-existent properties of an object, and to function syntax that is not valid. Method 3: Add diagnostic statements to a script, such as statements that display the value of variables, statements that read input from the command line, or statements that report the current instruction. Use the cmdlets that contain the Write verb for this task, such as Write-Host, Write-Debug, Write-Warning, and Write-Verbose. Method 4: Use the Windows PowerShell debugger to debug a script. Or, use the debugger to debug a function or script block that you typed at the command prompt. You can set breakpoints, step through the script, examine the values of variables, run diagnostics and logging commands, and display the call stack. Debugger Cmdlets The Windows PowerShell debugger includes the following set of cmdlets: Set-PsBreakpoint: Sets breakpoints on lines, variables, and commands. Get-PsBreakpoint: Gets breakpoints in the current session. Disable-PsBreakpoint: Turns off breakpoints in the current session. Enable-PsBreakpoint: Re-enables breakpoints in the current session. Remove-PsBreakpoint: Deletes breakpoints from the current session. Get-PsCallStack: Displays the current call stack. Starting and Stopping the Debugger To start the debugger, set one or more breakpoints. Then, run the script, command, or function that you want to debug. When you reach a breakpoint, execution stops, and control is turned over to the debugger. To stop the debugger, run the script, command, or function until it is complete. Or, type "stop" or "t". Debugger Commands When you use the debugger in the Windows PowerShell console, use the following commands to control the execution. Note: For information about how to use the debugger in other host applications, see the host application documentation. s, Step-into Executes the next statement and then stops. v, Step-over Executes the next statement, but skips functions and invocations. The skipped statements are executed, but not stepped through. o, Step-out Steps out of the current function; up one level if nested. If in the main body, it continues to the end or the next breakpoint. The skipped statements are executed, but not stepped through. c, Continue Continues to run until the script is complete or until the next breakpoint is reached. The skipped statements are executed, but not stepped through. l, List Displays the part of the script that is executing. By default, it displays the current line, five previous lines, and 10 subsequent lines. To continu e listing the script, press ENTER. l <m>, List Displays 16 lines of the script beginning with the line number specified by <m>. l <m> <n>, List Displays <n> lines of the script, beginning with th e line number specified by <m>. q, Stop Stops executing the script, and exits the debugger. k, Get-PsCallStack Displays the current call stack. <Enter> Repeats the last command if it was Step (s), Step-over (v), or List (l). Otherwise, represents a submit action. ?, h Displays the debugger command Help. To exit the debugger, use Stop (q). While in the debugger, you can also enter commands, display the value of variables, use cmdlets, and run scripts. By using these debugger commands, you can run a script, stop on a point of concern, examine the values of variables and the state of the system, and continue running the script until you have identified a problem. The Debugger Environment When you reach a breakpoint, you enter the debugger environment. The command prompt changes so that it begins with "[DBG]:". You can customize the prompt. Also, in some host applications, such as the Windows PowerShell console, (but not in Windows PowerShell Integrated Scripting Environment [ISE]), a nested prompt opens for debugging. You can detect the nested prompt by the repeating greater-than characters (ASCII 62) that appear at the command prompt. For example, the following is the default debugging prompt in the Windows PowerShell console: [DBG]: PS (get-location)>>> You can find the nesting level by using the $NestedPromptLevel automatic variable. Additionally, an automatic variable, $PSDebugContext, is defined in the local scope. You can use the presence of the $PsDebugContext variable to determine whether you are in the debugger. For example: if ($psdebugcontext) {"Debugging"} else {"Not Debugging"} You can use the value of the $PSDebugContext variable in your debugging. [DBG]: PS>>> $psdebugcontext.invocationinfo Name CommandLineParameters UnboundArguments Location ---- --------------------- ---------------- -------- = {} {} C:\ps-test\vote.ps1 (1) Debugging and Scope Breaking into the debugger does not change the scope in which you are operating, but when you reach a breakpoint in a script, you move into the script scope. The script scope is a child of the scope in which you ran the debugger. To find the variables and aliases that are defined in the script scope, use the Scope parameter of the Get-Alias or Get-Variable cmdlets. For example, the following command gets the variables in the local (script) scope: get-variable -scope 0 You can abbreviate the command as: gv -s 0 This is a useful way to see only the variables that you defined in the script and that you defined while debugging. Debugging at the Command Line When you set a variable breakpoint or a command breakpoint, you can set the breakpoint only in a script file. However, by default, the breakpoint is set on anything that runs in the current session. For example, if you set a breakpoint on the $name variable, the debugger breaks on any $name variable in any script, command, function, script cmdlet or expression that you run until you disable or remove the breakpoint. This allows you to debug your scripts in a more realistic context in which they might be affected by functions, variables, and other scripts in the session and in the user's profile. Line breakpoints are specific to script files, so they are set only in script files. Debugging Functions When you set a breakpoint on a function that has Begin, Process, and End sections, the debugger breaks at the first line of each section. For example: function test-cmdlet { begin { write-output "Begin" } process { write-output "Process" } end { write-output "End" } } C:\PS> set-psbreakpoint -command test-cmdlet C:\PS> test-cmdlet Begin Entering debug mode. Use h or ? for help. Hit Command breakpoint on 'prompt:test-cmdlet' test-cmdlet [DBG]: C:\PS> c Process Entering debug mode. Use h or ? for help. Hit Command breakpoint on 'prompt:test-cmdlet' test-cmdlet [DBG]: C:\PS> c End Entering debug mode. Use h or ? for help. Hit Command breakpoint on 'prompt:test-cmdlet' test-cmdlet [DBG]: C:\PS> Debugging Remote Scripts You cannot run the Windows PowerShell debugger in a remote session. To debug a script on a remote computer, copy the script to the local computer. The following command copies the Test.ps1 script from the Server01 remote computer to the local computer: invoke-command -computername Server01 ` {get-content c:\ps-test\test.ps1} | set-location c:\ps-test\test.ps1 Examples This test script detects the version of the operating system and displays a system-appropriate message. It includes a function, a function call, and a variable. The following command displays the contents of the test script file: c:>\PS-test> get-content test.ps1 function psversion { "Windows Powershell " + $psversiontable.psversion if ($psversiontable.psversion.major -lt 2) { "Upgrade to Windows PowerShell 2.0" } else { "Have you run a background job today (start-job)?" } } $scriptname = $MyInvocation.MyCommand.Path psversion "Done $scriptname." To start, set a breakpoint at a point of interest in the script, such as a line, command, variable, or function. Start by creating a line breakpoint on the first line of the Test.ps1 script in the current directory. PS C:\ps-test> set-psbreakpoint -line 1 -script test.ps1 You can abbreviate this command as: PS C:\ps-test> spb 1 -s test.ps1 The command returns a line-breakpoint object (System.Management.Automation.LineBreakpoint). Column : 0 Line : 1 Action : Enabled : True HitCount : 0 Id : 0 Script : C:\ps-test\test.ps1 ScriptName : C:\ps-test\test.ps1 Now, start the script. PS C:\ps-test> .\test.ps1 When the script reaches the first breakpoint, the breakpoint message indicates that the debugger is active. It describes the breakpoint and previews the first line of the script, which is a function declaration. The command prompt also changes to indicate that the debugger has control. The preview line includes the script name and the line number of the previewed command. Entering debug mode. Use h or ? for help. Hit Line breakpoint on 'C:\ps-test\test.ps1:1' test.ps1:1 function psversion { DBG> Use the Step command (s) to execute the first statement in the script and to preview the next statement. The next statement uses the $MyInvocation automatic variable to set the value of the $ScriptName variable to the path and file name of the script file. DBG> s test.ps1:11 $scriptname = $MyInvocation.MyCommand.Path At this point, the $ScriptName variable is not populated, but you can verify the value of the variable by displaying its value. In this case, the value is $null. DBG> $scriptname DBG> Use another Step command (s) to execute the current statement and to preview the next statement in the script. The next statement calls the PsVersion function. DBG> s test.ps1:12 psversion At this point, the $ScriptName variable is populated, but you verify the value of the variable by displaying its value. In this case, the value is set to the script path. DBG> $scriptname C:\ps-test\test.ps1 Use another Step command to execute the function call. Press ENTER, or type "s" for Step. DBG> s test.ps1:2 "Windows Powershell " + $psversiontable.psversion The debug message includes a preview of the statement in the function. To execute this statement and to preview the next statement in the function, you can use a Step command. But, in this case, use a Step-Out command (o). It completes the execution of the function (unless it reaches a breakpoint) and steps to the next statement in the script. DBG> o Windows Powershell 2.0 Have you run a background job today (start-job)? test.ps1:13 "Done $scriptname" Because we are on the last statement in the script, the Step, Step-Out, and Continue commands have the same effect. In this case, use Step-Out (o). Done C:\ps-test\test.ps1 PS C:\ps-test> The Step-Out command executes the last command. The standard command prompt indicates that the debugger has exited and returned control to the command processor. Now, run the debugger again. First, to delete the current breakpoint, use the Get-PsBreakpoint and Remove-PsBreakpoint cmdlets. (If you think you might reuse the breakpoint, use the Disable-PsBreakpoint cmdlet instead of Remove-PsBreakpoint.) PS C:\ps-test> Get-PsBreakpoint | Remove-PSBreakpoint You can abbreviate this command as: PS C:\ps-test> gbp | rbp Or, run the command by writing a function, such as the following function: function delbr { gbp | rbp } Now, create a breakpoint on the $scriptname variable. PS C:\ps-test> set-psbreakpoint -variable scriptname -script test.ps1 You can abbreviate the command as: PS C:\ps-test> sbp -v scriptname -s test.ps1 Now, start the script. The script reaches the variable breakpoint. The default mode is Write, so execution stops just before the statement that changes the value of the variable. PS C:\ps-test> .\test.ps1 Hit Variable breakpoint on 'C:\ps-test\test.ps1:$scriptname' (Write access) test.ps1:11 $scriptname = $MyInvocation.mycommand.path DBG> Display the current value of the $scriptname variable, which is $null. DBG> $scriptname DBG> Use a Step command (s) to execute the statement that populates the variable. Then, display the new value of the $scriptname variable. DBG> $scriptname C:\ps-test\test.ps1 Use a Step command (s) to preview the next statement in the script. DBG> s test.ps1:12 psversion The next statement is a call to the PsVersion function. To skip the function but still execute it, use a Step-Over command (v). If you are already in the function when you use Step-Over, it is not effective. The function call is displayed, but it is not executed. DBG> v Windows Powershell 2.0 Have you run a background job today (start-job)? test.ps1:13 "Done $scriptname" The Step-Over command executes the function, and it previews the next statement in the script, which prints the final line. Use a Stop command (t) to exit the debugger. The command prompt reverts to the standard command prompt. C:\ps-test> To delete the breakpoints, use the Get-PsBreakpoint and Remove-PsBreakpoint cmdlets. PS C:\ps-test> Get-PsBreakpoint | Remove-PSBreakpoint Create a new command breakpoint on the PsVersion function. PS C:\ps-test> Set-PsBreakpoint -command psversion -script test.ps1 You can abbreviate this command to: PS C:\ps-test> sbp -c psversion -s test.ps1 Now, run the script. PS C:\ps-test> .\test.ps1 Hit Command breakpoint on 'C:\ps-test\test.ps1:psversion' test.ps1:12 psversion DBG> The script reaches the breakpoint at the function call. At this point, the function has not yet been called. This gives you the opportunity to use the Action parameter of Set-PsBreakpoint to set conditions for the execution of the breakpoint or to perform preparatory or diagnostic tasks, such as starting a log or invoking a diagnostic or security script. To set an action, use a Continue command (c) to exit the script, and a Remove-PsBreakpoint command to delete the current breakpoint. (Breakpoints are read-only, so you cannot add an action to the current breakpoint.) DBG> c Windows PowerShell 2.0 Have you run a background job today (start-job)? Done C:\ps-test\test.ps1 PS C:\ps-test> get-psbreakpoint | remove-psbreakpoint PS C:\ps-test> Now, create a new command breakpoint with an action. The following command sets a command breakpoint with an action that logs the value of the $scriptname variable when the function is called. Because the Break keyword is not used in the action, execution does not stop. (The backtick (`) is the line-continuation character.) PS C:\ps-test> set-psbreakpoint -command psversion -script test.ps1 ` -action { add-content "The value of `$scriptname is $scriptname." ` -path action.log} You can also add actions that set conditions for the breakpoint. In the following command, the command breakpoint is executed only if the execution policy is set to RemoteSigned, the most restrictive policy that still permits you to run scripts. (The backtick (`) is the continuation character.) PS C:\ps-test> set-psbreakpoint -script test.ps1 -command psversion ` -action { if ((get-executionpolicy) -eq "RemoteSigned") { break }} The Break keyword in the action directs the debugger to execute the breakpoint. You can also use the Continue keyword to direct the debugger to execute without breaking. Because the default keyword is Continue, you must specify Break to stop execution. Now, run the script. PS C:\ps-test> .\test.ps1 Hit Command breakpoint on 'C:\ps-test\test.ps1:psversion' test.ps1:12 psversion Because the execution policy is set to RemoteSigned, execution stops at the function call. At this point, you might want to check the call stack. Use the Get-PsCallStack cmdlet or the Get-PsCallStack debugger command (k). The following command gets the current call stack. DBG> k 2: prompt 1: .\test.ps1: $args=[] 0: prompt: $args=[] This example demonstrates just a few of the many ways to use the Windows PowerShell debugger. For more information about the debugger cmdlets, type the following command: help <cmdlet-name> -full For example, type: help set-psbreakpoint -full SEE ALSO Disable-PsBreakpoint Get-PsBreakpoint Remove-PsBreakpoint Set-PsBreakpoint Set-PsDebug Set-Strictmode Write-Debug Write-Verbose Enable-PsBreakpoint Get-PsCallStack about_do TOPIC about_Do SHORT DESCRIPTION Runs a statement list one or more times, subject to a While or Until condition. LONG DESCRIPTION The Do keyword works with the While keyword or the Until keyword to run the statements in a script block, subject to a condition. Unlike the related While loop, the script block in a Do loop always runs at least once. A Do-While loop is a variety of the While loop. In a Do-While loop, the condition is evaluated after the script block has run. As in a While loop, the script block is repeated as long as the condition evaluates to true. Like a Do-While loop, a Do-Until loop always runs at least once before the condition is evaluated. However, the script block runs only while the condition is false. The Continue and Break flow control keywords can be used in a Do-While loop or in a Do-Until loop. Syntax The following shows the syntax of the Do-While statement: do {<statement list>} while (<condition>) The following shows the syntax of the Do-Until statement: do {<statement list>} until (<condition>) The statment list contains one or more statements that run each time the loop is entered or repeated. The condition portion of the statement resolves to true or false. Example The following example of a Do statement counts the items in an array until it reaches an item with a value of 0. C:\PS> $x = 1,2,78,0 C:\PS> do { $count++; $a++; } while ($x[$a] -ne 0) C:\PS> $count 3 The following example uses the Until keyword. Notice that the not equal to operator (-ne) is replaced by the equal to operator (-eq). C:\PS> $x = 1,2,78,0 C:\PS> do { $count++; $a++; } until ($x[$a] -eq 0) C:\PS> $count 3 The following example writes all the values of an array, skipping any value that is less than zero. do { if ($x[$a] -lt 0) { continue } Write-Host $x[$a] } while (++$a -lt 10) SEE ALSO about_While about_Operators about_Assignment_Operators about_Comparison_Operators about_Break about_Continue 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 proces s by making it easy to view and change the environment variables. Unlike other types of variables in Windows PowerShell, environment variable s 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:<variable-name> 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:<variable-name> = "<new-value>" 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,AllHos ts 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_var iables. The environment variables that store preferences include: PSModulePath Stores the paths to the default module directories. Windows PowerSh ell looks for modules in the specified directories when you do not spec ify 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 regis try. It sets the value of "$home\Documents\WindowsPowerShell\Modules" ea ch time you start Windows PowerShell. In addition, setup programs that install modules in other directori es, such as the Program Files directory, append their locations to the value of PSModulePath. To change the default module directories, change the value of the PSModulePath environment variable. For example, to add the "C:\ps-test\Modules" directory to the value of the PSModulePath environment variable, type: $env:PSModulePath = $env:PSModulePath + ";c:\ps-test\Modules" The semi-colon (;) in the command separates the new path from the path that precedes it in the list. Your changes affect only the current session unless you 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_escape_characters TOPIC about_Escape_Characters SHORT DESCRIPTION Introduces the escape character in Windows PowerShell and explains its effect. LONG DESCRIPTION Escape characters are used to assign a special interpretation to the characters that follow it. In Windows PowerShell, the escape character is the backtick (`), also called the grave accent (ASCII 96). The escape character can be used to indicate a literal, to indicate line continuation, and to indicate special characters. Indicating a Literal When an escape character precedes a variable, it prevents a value from being substituted for the variable. When an escape character precedes a double quotation mark, Windows PowerShell interprets the double quotation mark as a character, not as a string delimiter. For example: C:\>$a = 5 C:\>"The value is stored in $a." The value is stored in 5. C:\>$a = 5 C:\>"The value is stored in `$a." The value is stored in $a. C:\> "Use quotation marks (") to indicate a string." Unexpected token ')' in expression or statement. At line:1 char:25 + "Use quotation marks (") < to indicate a string." C:\> "Use quotation marks (`") to indicate a string." Use quotation marks (") to indicate a string. Indicating Line Continuation The escape character tells Windows PowerShell that the command continues on the next line. For example: C:\> get-process ` >> powershell Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 340 8 34556 31864 149 0.98 2036 powershell Indicating Special Characters When used within quotation marks, the escape character indicates a special character that provides instructions to the command parser. The following special characters are recognized by Windows PowerShell: `0 Null `a Alert `b Backspace `f Form feed `n New line `r Carriage return `t Horizontal tab `v Vertical tab For example: C:\> "12345678123456781`nCol1`tColumn2`tCol3" 12345678123456781 Col1 Column2 Col3 For more information, type: get-help about_special_characters SEE ALSO about_Quoting_Rules about_eventlogs TOPIC about_EventLogs SHORT DESCRIPTION Windows PowerShell creates a Windows event log that is named "Windows PowerShell" to record Windows PowerShell events. You can view this log in Event Viewer or by using cmdlets that get events, such as the Get-EventLog cmdlet. By default, Windows PowerShell engine and provider events are recorded in the event log, but you can use the event log preference variables to customize the event log. For example, you can add events about Windows PowerShell commands. LONG DESCRIPTION The Windows PowerShell event log records details of Windows PowerShell operations, such as starting and stopping the program engine and starting and stopping the Windows PowerShell providers. You can also log details about Windows PowerShell commands. In Windows Vista and later versions, the Windows PowerShell event log is in the Application and Services Logs group. The Windows PowerShell log is a classic event log that does not use the Windows Eventing technology. To view the log, use the cmdlets designed for classic event logs, such as Get-EventLog. Viewing the Windows PowerShell Event Log You can view the Windows PowerShell event log in Event Viewer or by using the Get-EventLog and Get-WmiObject cmdlets. To view the contents of the Windows PowerShell log, type: get-eventlog -logname "Windows PowerShell" To examine the events and their properties, use the Sort-Object cmdlet, the Group-Object cmdlet, and the cmdlets that contain the Format verb (the Format cmdlets). For example, to view the events in the log grouped by the event ID, type: get-eventlog "Windows PowerShell" | format-table -groupby eventid Or, type: get-eventlog "Windows PowerShell" | sort-object eventid ` | group-object eventid To view all the classic event logs, type: get-eventlog -list You can also use the Get-WmiObject cmdlet to use the event-related Windows Management Instumentation (WMI) classes to examine the event log. For example, to view all the properties of the event log file, type: get-wmiobject win32_nteventlogfile | where ` {$_.logfilename -eq "Windows PowerShell"} | format-list -property * To find the Win32 event-related WMI classes, type: get-wmiobject -list | where {$_.name -like "win32*event*"} For more information, type "get-help get-eventlog" and "get-help get-wmiobject". Selecting Events for the Windows PowerShell Event Log You can use the event log preference variables to determine which events are recorded in the Windows PowerShell event log. There are six event log preference variables; two variables for each of the three logging components: the engine (the Windows PowerShell program), the providers, and the commands. The LifeCycleEvent variables log normal starting and stopping events. The Health variables log error events. The following table lists the event log preference variables. Variable Description -------------------------- ---------------------------------------- $LogEngineLifeCycleEvent Logs starting and stopping of Windows PowerShell. $LogEngineHealthEvent Logs Windows PowerShell program errors. $LogProviderLifeCycleEvent Logs starting and stopping of Windows PowerShell providers. $LogProviderHealthEvent Logs Windows PowerShell provider errors. $LogCommandLifeCycleEvent Logs starting and completion of commands. $LogCommandHealthEvent Logs command errors. (For information about Windows PowerShell providers, type: "get-help about_providers".) By default, only the following event types are enabled: $LogEngineLifeCycleEvent $LogEngineHealthEvent $LogProviderLifeCycleEvent $LogProviderHealthEvent To enable an event type, set the preference variable for that event type to $true. For example, to enable command life-cycle events, type: $LogCommandLifeCycleEvent Or, type: $LogCommandLifeCycleEvent = $true To disable an event type, set the preference variable for that event type to $false. For example, to disable command life-cycle events, type: $LogProviderLifeCycleEvent = $false The variable settings apply only for the current Windows PowerShell session. To apply them to all Windows PowerShell sessions, add them to your Windows PowerShell profile. Security and Auditing The Windows PowerShell event log is designed to indicate activity and to provide operational details for troubleshooting. However, like most Windows-based application event logs, the Windows PowerShell event log is not designed to be secure. It should not be used to audit security or to record confidential or proprietary information. Event logs are designed to be read and understood by users. Users can read from and write to the log. A malicious user could read an event log on a local or remote computer, record false data, and then prevent the logging of their activities. SEE ALSO Get-EventLog Get-WmiObject about_Preference_Variables about_execution_policies TOPIC about_Execution_Policies SHORT DESCRIPTION Describes the Windows PowerShell execution policies and explains how to manage them. LONG DESCRIPTION Windows PowerShell execution policies let you determine the conditions under which Windows PowerShell loads configuration files and runs scripts. You can set an execution policy for the local computer, for the current user, or for a particular session. You can also use a Group Policy setting to set execution policy for computers and users. Execution policies for the local computer and current user are stored in the registry. You do not need to set execution policies in your Windows PowerShell profile. The execution policy for a particular session is stored only in memory and is lost when the session is closed. The execution policy is not a security system that restricts user actions. For example, users can easily circumvent a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating them unintentionally. WINDOWS POWERSHELL EXECUTION POLICIES ------------------------------------- The Windows PowerShell execution policies are as follows: "Restricted" is the default policy. Restricted - Default execution policy. - Permits individual commands, but will not run scripts. - Prevents running of all script files, including formatting and configuration files (.ps1xml), module script files (.psm1), and Windows PowerShell profiles (.ps1). AllSigned - Scripts can run. - Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on the local computer. - Prompts you before running scripts from publishers that you have not yet classified as trusted or untrusted. - Risks running unsigned scripts from sources other than the Internet and signed, but malicious, scripts. RemoteSigned - Scripts can run. - Requires a digital signature from a trusted publisher on scripts and configuration files that are downloaded from the Internet (including e-mail and instant messaging programs). - Does not require digital signatures on scripts that you have run and that you have written on the local computer (not downloaded from the Internet). - Risks running signed, but malicious, scripts. Unrestricted - Unsigned scripts can run. (This risks running malicious scripts.) - Warns the user before running srcipts and configuration files that are downloaded from the Internet. Bypass - Nothing is blocked and there are no warnings or prompts. - This execution policy is designed for configurations in which a Windows PowerShell script is built in to a a larger application or for configurations in which Windows PowerShell is the foundation for a program that has its own security model. Undefined - There is no execution policy set in the current scope. - If the execution policy in all scopes is Undefined, the effective execution policy is Restricted, which is the default execution policy. Note: On systems that do not distinguish Universal Naming Convention (UNC) paths from Internet paths, scripts that are identified by a UNC path might not be permitted to run with the RemoteSigned execution policy. EXECUTION POLICY SCOPE ---------------------- You can set an execution policy that is effective only in a particular scope. The valid values for Scope are Process, CurrentUser, and LocalMachine. LocalMachine is the default when setting an execution policy. The Scope values are listed in precedence order. - Process The execution policy affects only the current session (the current Windows PowerShell process). The execution policy is stored in the $PSExecutionPolicyPreference environment variable. This value is deleted when the session in which the policy is set is closed. - CurrentUser The execution policy affects only the current user. It is stored in the HKEY_CURRENT_USER registry subkey. - LocalMachine The execution policy affects all users on the current computer. It is stored in the HKEY_LOCAL_MACHINE registry subkey. The policy that takes precedence is effective in the current session, even if a more restrictive policy was set at a lower level of precedence. For more information, see Set-ExecutionPolicy. GET YOUR EXECUTION POLICY ------------------------------ To get the Windows PowerShell execution policy that is in effect in the current session, use the Get-ExecutionPolicy cmdlet. The following command gets the current execution policy: get-executionpolicy To get all of the execution policies that affect the current session and displays them in precedence order, type: get-executionpolicy -list The result will look similar to the following sample output: Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser RemoteSigned LocalMachine AllSigned In this case, the effective execution policy is RemoteSigned because the execution policy for the current user takes precedence over the execution policy set for the local computer. To get the execution policy set for a particular scope, use the Scope parameter of Get-ExecutionPolicy. For example, the following command gets the execution policy for the current user scope. get-executionpolicy -scope CurrentUser CHANGE YOUR EXECUTION POLICY ------------------------------ To change the Windows PowerShell execution policy on your computer, use the Set-ExecutionPolicy cmdlet. The change is effective immediately; you do not need to restart Windows PowerShell. If you set the execution policy for the local computer (the default) or the current user, the change is saved in the registry and remains effective until you change it again. If you set the execution policy for the current process, it is not saved in the registry. It is retained until the current process and any child processes are closed. Note: In Windows Vista and later versions of Windows, to run commands that change the execution policy for the local computer (the default), start Windows PowerShell with the "Run as administrator" option. To change your execution policy, type: Set-ExecutionPolicy <policy-name> For example: Set-ExecutionPolicy RemoteSigned To set the execution policy in a particular scope, type: Set-ExecutionPolicy <policy-name> -scope <scope> For example: Set-ExecutionPolicy RemoteSigned -scope CurrentUser A command to change an execution policy can succeed but still not change the effective execution policy. For example, a command that sets the execution policy for the local computer can succeed but be overridden by the execution policy for the current user. REMOVE YOUR EXECUTION POLICY ---------------------------- To remove the execution policy for a particular scope, set the value of the value of the execution policy to Undefined. For example, to remove the execution policy for all the users of the local computer, type: set-executionpolicy Undefined Or, type: set-executionpolicy Undefined -scope LocalMachine If no execution policy is set in any scope, the effective execution policy is Restricted, which is the default. SET AN EXECUTION POLICY IN POWERSHELL.EXE ----------------------------------------- You can use the ExecutionPolicy parameter of PowerShell.exe to set an execution policy for a new Windows PowerShell session. The policy affects only the current session and child sessions. To set the execution policy for a new session, start Windows PowerShell at the command line (such as Cmd.exe or Windows PowerShell), and then use the ExecutionPolicy parameter of PowerShell.exe to set the execution policy. For example: powershell.exe -executionpolicy -allsigned The execution policy that you set is not stored in the registry. Instead, it is stored in the $PSExecutionPolicyPreference environment variable. The variable is deleted when you close the session in which the policy is set. During the session, the execution policy that is set for the session takes precedence over an execution policy that is set in the registry for the local computer or current user. However, it does not take precedence over the execution policy set by using a Group Policy setting (discussed below). USE GROUP POLICY TO MANAGE EXECUTION POLICY ------------------------------------------- You can use the "Turn on Script Execution" Group Policy setting to manage the execution policy of computers in your enterprise. The Group Policy setting overrides the execution policies set in Windows PowerShell in all scopes. The "Turn on Script Execution" policy settings are as follows: -- If you disable "Turn on Script Execution", scripts do not run. This is equivalent to the "Restricted" execution policy. -- If you enable "Turn on Script Execution", you can select an execution policy. The Group Policy settings are equivalent to the following execution policy settings. Group Policy Execution Policy ------------ ---------------- Allow all scripts. Unrestricted Allow local scripts RemoteSigned and remote signed scripts. Allow only signed AllSigned scripts. -- If "Turn on Script Execution" is not configured, it has no effect. The execution policy set in Windows PowerShell is effective. The PowerShellExecutionPolicy.adm file adds the "Turn on Script Execution" policy to the Computer Configuration and User Configuration nodes in Group Policy Editor in the following paths. For Windows XP and Windows Server 2003: Administrative Templates\Windows Components\Windows PowerShell For Windows Vista and later versions of Windows: Administrative Templates\Classic Administrative Templates\ Windows Components\Windows PowerShell Policies set in the Computer Configuration node take precedence over policies set in the User Configuration node. The PowerShellExecutionPolicy.adm file is available on the Microsoft Download Center. For more information, see "Administrative Templates for Windows PowerShell" at http://go.microsoft.com/fwlink/?LinkId=131786. EXECUTION POLICY PRECEDENCE --------------------------- When determining the effective execution policy for a session, Windows PowerShell evaluates the execution policies in the following precedence order: - Group Policy: Computer Configuration - Group Policy: User Configuration - Execution Policy: Process (or PowerShell.exe -ExecutionPolicy) - Execution Policy: CurrentUser - Execution Policy: LocalMachine MANAGE SIGNED AND UNSIGNED SCRIPTS ---------------------------------- If your Windows PowerShell execution policy is RemoteSigned, Windows PowerShell will not run unsigned scripts that are downloaded from the Internet (including e-mail and instant messaging programs). You can sign the script or elect to run an unsigned script without changing the execution policy. For more information, see about_Signing. SEE ALSO Get-ExecutionPolicy Set-ExecutionPolicy about_Signing "Administrative Templates for Windows PowerShell" (http://go.microsoft.com/fwlink/?LinkId=131786) about_For TOPIC about_For SHORT DESCRIPTION Describes a language command you can use to run statements based on a conditional test. LONG DESCRIPTION The For statement (also known as a For loop) is a language construct you can use to create a loop that runs commands in a command block while a specified condition evaluates to true. A typical use of the For loop is to iterate an array of values and to operate on a subset of these values. In most cases, if you want to iterate all the values in an array, consider using a Foreach statement. Syntax The following shows the For statement syntax. for (<init>; <condition>; <repeat>) {<statement list>} The <init> placeholder represents one or more commands, separated by commas, that are run before the loop begins. You typically use the <init> portion of the statement to create and initialize a variable with a starting value. This variable will then be the basis for the condition to be tested in the next portion of the For statement. The <condition> placeholder represents the portion of the For statement that resolves to a true or false Boolean value. Windows PowerShell evaluates the condition each time the For loop runs. If the statement is true, the commands in the command block run, and the statement is evaluated again. If the condition is still true, the commands in the statement list run again. The loop is repeated until the condition becomes false. The <repeat> placeholder represents one or more commands, separated by commas, that are executed each time the loop repeats. Typically, this is used to modify a variable that is tested inside the <condition> part of the statement. The <statement list> placeholder represents a set of one or more commands that are run each time the loop is entered or repeated. The contents of the statement list are surrounded by braces. Examples At a minimum, a For statement requires the parenthesis surrounding the <init>, <condition>, and <repeat> part of the statement and a command surrounded by braces in the <statement list> part of the statement. Note that the upcoming examples intentionally show code outside the For statement. In later examples, code is integrated into the for statement. For example, the following For statement continually displays the value of the $i variable until you manually break out of the command by pressing CTRL+C. $i = 1 for (;;){Write-Host $i} You can add additional commands to the statement list so that the value of $i is incremented by 1 each time the loop is run, as the following example shows. for (;;){$i++; Write-Host $i} Until you break out of the command by pressing CTRL+C, this statement will continually display the value of the $i variable as it is incremented by 1 each time the loop is run. Rather than change the value of the variable in the statement list part of the For statement, you can use the <repeat> portion of the For statement instead, as follows. $i=1 for (;;$i++){Write-Host $i} This statement will still repeat indefinitely until you break out of the command by pressing CTRL+C. By setting a condition (using the <condition> portion of the For statement), you can end the For loop when the condition evaluates to false. In the following example, the For loop runs while the value of $i is less than or equal to 10. $i=1 for(;$i -le 10;$i++){Write-Host $i} Instead of creating and initializing the variable outside the For statement, you can perform this task inside the For loop by using the <init> portion of the For statement. for($i=1; $i -le 10; $i++){Write-Host $i} You can use carriage returns instead of semicolons to delimit the <init>, <condition>, and <repeat> portions of the For statement. The following example shows the For statement syntax in this alternative form. for (<init> <condition> <repeat>){ <statement list> } This alternative form of the For statement works in Windows PowerShell script files and at the Windows PowerShell command prompt. However, it is easier to use the For statement syntax with semicolons when you enter interactive commands at the command prompt. The For loop is more flexible than the Foreach loop because it allows you to increment values in an array or collection by using patterns. In the following example, the $i variable is incremented by 2 in the <repeat> portion of the for statement. for ($i = 0; $i -ile 20; $i += 2) {Write-Host $i} SEE ALSO about_Comparison_Operators about_Foreach about_Foreach TOPIC about_Foreach SHORT DESCRIPTION Describes a language command you can use to traverse all the items in a collection of items. LONG DESCRIPTION The Foreach statement (also known as a Foreach loop) is a language construct for stepping through (iterating) a series of values in a collection of items. The simplest and most typical type of collection to traverse is an array. Within a Foreach loop, it is common to run one or more commands against each item in an array. Syntax The following shows the Foreach syntax: foreach ($<item> in $<collection>){<statement list>} The Foreach Statement Outside a Command Pipeline The part of the Foreach statement enclosed in parenthesis represents a variable and a collection to iterate. Windows PowerShell creates the variable ($<item>) automatically when the Foreach loop runs. Prior to each iteration through the loop, the variable is set to a value in the collection. The block following a Foreach statement {<statement list>} contains a set of commands to execute against each item in a collection. Examples For example, the Foreach loop in the following example displays the values in the $letterArray array. $letterArray = "a","b","c","d" foreach ($letter in $letterArray) { Write-Host $letter } In this example, the $letterArray array is created and initialized with the string values "a", "b", "c", and "d". The first time the Foreach statement runs, it sets the $letter variable equal to the first item in $letterArray ("a"). Then, it uses the Write-Host cmdlet to display the letter a. The next time through the loop, $letter is set to "b", and so on. After the Foreach loop displays the letter d, Windows PowerShell exits the loop. The entire Foreach statement must appear on a single line to run it as a command at the Windows PowerShell command prompt. The entire Foreach statement does not have to appear on a single line if you place the command in a .ps1 script file instead. Foreach statements can also be used together with cmdlets that return a collection of items. In the following example, the Foreach statement steps through the list of items that is returned by the Get-ChildItem cmdlet. foreach ($file in Get-ChildItem) { Write-Host $file } You can refine the example by using an If statement to limit the results that are returned. In the following example, the Foreach statement performs the same looping operation as the previous example, but it adds an If statement to limit the results to files that are greater than 100 kilobytes (KB): foreach ($file in Get-ChildItem) { if ($file.length -gt 100k) { Write-Host $file } } In this example, the Foreach loop uses a property of the $file variable to perform a comparison operation ($file.length -gt 100k). The $file variable contains all the properties in the object that is returned by the Get-ChildItem cmdlet. Therefore, you can return more than just a file name. In the next example, Windows PowerShell returns the length and the last access time inside the statement list: foreach ($file in Get-ChildItem) { if ($file.length -gt 100k) { Write-Host $file Write-Host $file.length Write-Host $file.lastaccesstime } } In this example, you are not limited to running a single command in a statement list. You can also use a variable outside a Foreach loop and increment the variable inside the loop. The following example counts files over 100 KB in size: $i = 0 foreach ($file in Get-ChildItem) { if ($file.length -gt 100k) { Write-Host $file "file size:" ($file.length / 1024).ToString("F0") KB $i = $i + 1 } } if ($i -ne 0) { Write-Host Write-Host $i " file(s) over 100 KB in the current directory."} else { Write-Host "No files greater than 100 KB in the current directory." } In the preceding example, the $i variable is set to 0 outside the loop, and the variable is incremented inside the loop for each file that is found that is larger than 100 KB. When the loop exits, an If statement evaluates the value of $i to display a count of all the files over 100 KB. Or, it displays a message stating that no files over 100 KB were found. The previous example also demonstrates how to format the file length results: ($file.length / 1024).ToString("F0") The value is divided by 1,024 to show the results in kilobytes rather than bytes, and the resulting value is then formatted using the fixed-point format specifier to remove any decimal values from the result. The 0 makes the format specifier show no decimal places. The Foreach Statement Inside a Command Pipeline When Foreach appears in a command pipeline, Windows PowerShell uses the foreach alias, which calls the ForEach-Object command. When you use the foreach alias in a command pipeline, you do not include the ($<item> in $<collection>) syntax as you do with the Foreach statement. This is because the prior command in the pipeline provides this information. The syntax of the foreach alias when used in a command pipeline is as follows: <command> | foreach {<command_block>} For example, the Foreach loop in the following command pipeline displays any processes whose working set (memory usage) is greater than 20 megabytes (MB). Windows PowerShell pipes the output from the Get-Process command to the foreach alias. Inside the foreach alias command block, the $_.WS variable contains the value of the WS (working set) property passed to it by the Get-Process cmdlet. (The $_ portion of the declaration is a Windows Script Host [WSH] automatic variable, and the WS portion is a property). The If statement uses a conditional statement to determine whether the working set is greater than 20 MB (20,000,000 bytes). If so, the name of the process that is stored in the $_.name variable and the working-set size in megabytes are displayed. If no process working set is over 20 MB, nothing is displayed. Write-Host "Processes with working-sets greater than 20 MB" Get-Process | foreach { if ($_.WS -gt 20m) { Write-Host $_.name ": " ($_.WS/1m).ToString("F0") MB -Separator "" } } The foreach alias also supports beginning command blocks, middle command blocks, and end command blocks. The beginning and end command blocks run once, and the middle command block runs every time the Foreach loop steps through a collection or array. The syntax of the foreach alias when used in a command pipeline with a beginning, middle, and ending set of command blocks is as follows: <command> | foreach {<beginning command_block>}{<middle command_block>}{<ending command_block>} The following example demonstrates the use of the beginning, middle, and end command blocks. Get-ChildItem | foreach { $fileCount = $directoryCount = 0}{ if ($_.PsIsContainer) {$directoryCount++} else {$fileCount++}}{ "$directoryCount directories and $fileCount files"} The beginning block creates and initializes two variables to 0: {$fileCount = $directoryCount = 0} The middle block evaluates whether each item returned by Get-ChildItem is a directory or a file: {if ($_.PsIsContainer) {$directoryCount++} else {$fileCount++}} If the item that is returned is a directory, the $directoryCount variable is incremented by 1. If the item is not a directory, the $fileCount variable is incremented by 1. The ending block runs after the middle block completes its looping operation and then returns the results of the operation: {"$directoryCount directories and $fileCount files"} By using the beginning, middle, and ending command block structure and the pipeline operator, you can rewrite the earlier example to find any files that are greater than 100 KB, as follows: Get-ChildItem | foreach{ $i = 0}{ if ($_.length -gt 100k) { Write-Host $_.name "file size:" ($_.length / 1024).ToString("F0") KB $i++ } }{ if ($i -ne 0) { Write-Host Write-Host "$i file(s) over 100 KB in the current directory." } else { Write-Host "No files greater than 100 KB in the current directory."} } SEE ALSO about_Automatic_Variables about_If Foreach-Object about_format.ps1xml TOPIC about_Format.ps1xml SHORT DESCRIPTION The Format.ps1xml files in Windows PowerShell define the default display of objects in the Windows PowerShell console. You can create your own Format.ps1xml files to change the display of objects or to define default displays for new object types that you create in Windows PowerShell. LONG DESCRIPTION The Format.ps1xml files in Windows PowerShell define the default display of objects in Windows PowerShell. You can create your own Format.ps1xml files to change the display of objects or to define default displays for new object types that you create in Windows PowerShell. When Windows PowerShell displays an object, it uses the data in structured formatting files to determine the default display of the object. The data in the formatting files determines whether the object is rendered in a table or in a list, and it determines which properties are displayed by default. The formatting affects the display only. It does not affect which object properties are passed down the pipeline or how they are passed. Windows PowerShell includes seven formatting files. These files are located in the installation directory ($pshome). Each file defines the display of a group of Microsoft .NET Framework objects: Certificate.Format.ps1xml Objects in the Certificate store, such as X.509 certificates and certificate stores. DotNetTypes.Format.ps1xml Other .NET Framework types, such as CultureInfo, FileVersionInfo, and EventLogEntry objects. FileSystem.Format.ps1xml File system objects, such as files and directories. Help.Format.ps1xml Help views, such as detailed and full views, parameters, and examples. PowerShellCore.format.ps1xml Objects generated by Windows PowerShell core cmdlets, such as Get-Member and Get-History. PowerShellTrace.format.ps1xml Trace objects, such as those generated by the Trace-Command cmdlet. Registry.format.ps1xml Registry objects, such as keys and entries. A formatting file can define four different views of each object: table, list, wide, and complex. For example, when the output of a Get-ChildItem command is piped to a Format-List command, Format-List uses the view in the FileSystem.format.ps1xml file to determine how to display the file and folder objects as a list. In a Format.ps1xml file, a view is defined by a set of XML tags that describe the name of the view, the type of object to which it can be applied, the column headers, and the properties that are displayed in the body of the view. The format in Format.ps1xml files is applied just before the data is presented to the user. Creating New Format.ps1xml Files The .ps1xml files that are installed with Windows PowerShell are digitally signed to prevent tampering because the formatting can include script blocks. Therefore, to change the display format of an existing object view, or to add views for new objects, create your own Format.ps1xml files, and then add them to your Windows PowerShell session. To create a new file, copy an existing Format.ps1xml file. The new file can have any name, but it must have a .ps1xml file name extension. You can place the new file in any directory that is accessible to Windows PowerShell, but it is useful to place the files in the Windows PowerShell installation directory ($pshome) or in a subdirectory of the installation directory. To change the formatting of a current view, locate the view in the formatting file, and then use the tags to change the view. To create a view for a new object type, create a new view, or use an existing view as a model. (The tags are described in the next section of this topic.) You can then delete all the other views in the file so that the changes are obvious to anyone examining the file. When you have saved the changes, use the Update-FormatData cmdlet to add the new file to your Windows PowerShell session. If you want your view to take precedence over a view defined in the built-in files, use the PrependData parameter of Update-FormatData. Update-FormatData affects only the current session. To make the change to all future sessions, add the Update-FormatData command to your Windows PowerShell profile. Example: Adding Calendar Data to Culture Objects This example shows how to change the formatting of the culture objects (System.Globalization.CultureInfo) generated by the Get-Culture cmdlet. The commands in the example add the calendar property to the default table view display of culture objects. The first step is to find the Format.ps1xml file that contains the current view of the culture objects. The following Select-String command finds the file: select-string -path $pshome\*format.ps1xml ` -pattern System.Globalization.CultureInfo This command reveals that the definition is in the DotNetTypes.Format.ps1xml file. The next command copies the file contents to a new file, MyDotNetTypes.Format.ps1xml. copy-item DotNetTypes.Format.ps1xml MyDotNetTypes.Format.ps1xml Next, open the MyDotNetTypes.Format.ps1xml file in any XML or text editor, such as Notepad. Find the System.Globalization.CultureInfo object section. The following XML defines the views of the CultureInfo object. The object has only a TableControl view. <View> <Name>System.Globalization.CultureInfo</Name> <ViewSelectedBy> <TypeName>Deserialized.System.Globalization.CultureInfo</TypeName> <TypeName>System.Globalization.CultureInfo</TypeName> </ViewSelectedBy> <TableControl> <TableHeaders> <TableColumnHeader> <Width>16</Width> </TableColumnHeader> <TableColumnHeader> <Width>16</Width> </TableColumnHeader> <TableColumnHeader/> </TableHeaders> <TableRowEntries> <TableRowEntry> <TableColumnItems> <TableColumnItem> <PropertyName>LCID</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>Name</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>DisplayName</PropertyName> </TableColumnItem> </TableColumnItems> </TableRowEntry> </TableRowEntries> </TableControl> </View> Delete the remainder of the file, except for the opening <?XML>, <Configuration>, and <ViewDefinitions> tags and the closing <ViewDefintions> and <Configuration> tags. You must also delete the digital signature whenever you change the file. <?xml version="1.0" encoding="utf-8" ?> <Configuration> <ViewDefinitions> <View> <Name>System.Globalization.CultureInfo</Name> <ViewSelectedBy> <TypeName>Deserialized.System.Globalization.CultureInfo</ TypeName> <TypeName>System.Globalization.CultureInfo</TypeName> </ViewSelectedBy> <TableControl> <TableHeaders> <TableColumnHeader> <Width>16</Width> </TableColumnHeader> <TableColumnHeader> <Width>16</Width> </TableColumnHeader> <TableColumnHeader/> </TableHeaders> <TableRowEntries> <TableRowEntry> <TableColumnItems> <TableColumnItem> <PropertyName>LCID</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>Name</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>DisplayName</PropertyName> </TableColumnItem> </TableColumnItems> </TableRowEntry> </TableRowEntries> </TableControl> </View> </ViewDefinitions> </Configuration> Next, create a new column for the Calendar property by adding a new set of <TableColumnHeader> tags. The value of the Calendar property can be long, so a value of 45 characters is used, as follows: <TableControl> <TableHeaders> <TableColumnHeader> <Width>16</Width> </TableColumnHeader> <TableColumnHeader> <Width>16</Width> </TableColumnHeader> <TableColumnHeader> <Width>45</Width> </TableColumnHeader> <TableColumnHeader/> </TableHeaders> Now, add a new column item in the table rows, as follows: <TableRowEntries> <TableRowEntry> <TableColumnItems> <TableColumnItem> <PropertyName>LCID</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>Name</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>Calendar</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>DisplayName</PropertyName> </TableColumnItem> </TableColumnItems> </TableRowEntry> </TableRowEntries> After saving the file and closing it, use an Update-FormatData command, such as the following command, to add the new format file to the current session. The command uses the PrependData parameter to place the new file in a higher precedence order than the original file. (For more information about Update-FormatData, type "get-help update-formatdata".) update-formatdata -prependpath $pshome\MyDotNetTypes.format.ps1xml To test the change, type "get-culture", and then review the output, which includes the Calendar property. C:\PS> get-culture LCID Name Calendar DisplayName ---- ---- -------- ----------- 1033 en-US System.Globalization.GregorianCalendar English (United States) The XML in Format.ps1xml Files The ViewDefinitions section of each Format.ps1xml file contains the <View> tags that define each view. A typical <View> tag includes the following tags: <Name> The <Name> tag identifies the name of the view. <ViewSelectedBy> The <ViewSelectedBy> tag specifies the object type or types to which the view applies. <GroupBy> The <GroupBy> tag specifies how items in the view will be combined in groups. <TableControl> <ListControl> <WideControl> <ComplexControl> These tags contain the tags that specify how each item will be displayed. The <ViewSelectedBy> tag can contain a <TypeName> tag for each object type to which the view applies. Or, it can contain a <SelectionSetName> tag that references a selection set that is defined elsewhere by using a <SelectionSet> tag. The <GroupBy> tag contains a <PropertyName> tag that specifies the object property by which items are to be grouped. It also contains either a <Label> tag that specifies a string to be used as a label for each group or a <ComplexControlName> tag that references a complex control defined elsewhere using a <Control> tag. The <Control> tag contains a <Name> tag and a <ComplexControl> tag. The <TableControl> tag typically contains <TableHeaders> and <TableRowEntries> tags that define the formatting for the table's heads and rows. The <TableHeaders> tag typically contains <TableColumnHeader> tags that contain <Label>, <Width>, and <Alignment> tags. The <TableRowEntries> tag contains <TableRowEntry> tags for each row in the table. The <TableRowEntry> tag contains a <TableColumnItems> tag that contains a <TableColumnItem> tag for each column in the row. Typically, the <TableColumnItem> tag contains either a <PropertyName> tag that identifies the object property to be displayed in the defined location, or a <ScriptBlock> tag that contains script code that calculates a result that is to be displayed in the location. Note: Script blocks can also be used elsewhere in locations where calculated results can be useful. The <TableColumnItem> tag can also contain a <FormatString> tag that specifies how the property or the calculated results will be displayed. The <ListControl> tag typically contains a <ListEntries> tag. The <ListEntries> tag contains a <ListItems> tag. The <ListItems> tag contains <ListItem> tags, which contain <PropertyName> tags. The <PropertyName> tags specify the object property to be displayed at the specified location in the list. If the view selection is defined using a selection set, the <ListControl> tag can also contain an <EntrySelectedBy> tag that contains one or more <TypeName> tags. These <TypeName> tags specify the object type that the <ListControl> tag is intended to display. The <WideControl> tag typically contains a <WideEntries> tag. The <WideEntries> tag contains one or more <WideEntry> tags. A <WideEntry> tag typically contains a <PropertyName> tag that specifies the property to be displayed at the specified location in the view. The <PropertyName> tag can contain a <FormatString> tag that specifies how the property is to be displayed. The <ComplexControl> tag contains more complex combinations of tags than other view types. A <ComplexControl> tag typically contains a <ComplexEntries> tag. A <ComplexEntries> tag contains multiple <ComplexEntry> tags. A <ComplexEntry> tag typically contains a <ComplexItem> tag. This tag, in turn, can contain a variety of tags that specify contents and formatting for the specified location in the view, including <Text>, <Indentation>, <ExpressionBinding>, and Update-FormatData To load your Format.ps1xml files into a Windows PowerShell session, use the Update-FormatData cmdlet. If you want the views in your file to take precedence over the views in the built-in Format.ps1xml file, use the PrependData parameter of Update-FormatData. Update-FormatData affects only the current session. To make the change to all future sessions, add the Update-FormatData command to your Windows PowerShell profile. Default Displays in Types.ps1xml The default displays of some basic object types are defined in the Types.ps1xml file in the $pshome directory. The nodes are named PsStandardMembers, and the subnodes use one of the following tags: <DefaultDisplayProperty> <DefaultDisplayPropertySet> <DefaultKeyPropertySet> For more information, type the following command: get-help about_types.ps1xml Tracing Format.ps1xml File Use To detect errors in the loading or application of Format.ps1xml files, use the Trace-Command cmdlet with any of the following format components as the value of the Name parameter: FormatFileLoading UpdateFormatData FormatViewBinding For more information, type the following commands: get-help trace-command get-help get-tracesource Signing a Format.ps1xml File To protect the users of your Format.ps1xml file, sign the file using a digital signature. For more information, type: get-help about_signing SEE ALSO Update-FormatData Trace-Command Get-TraceSource about_functions TOPIC about_Functions SHORT DESCRIPTION Describes how to create and use functions in Windows PowerShell. LONG DESCRIPTION A function is a list of statements that has a name that you assign. When you run a function, you type the function name. The statements in the list run as if you had typed them at the command prompt. Like cmdlets, functions can have parameters. The parameters can be named, positional, switch, or dynamic parameters. Function parameters can be read from the command line or from the pipeline. Functions can return values that can be displayed, assigned to variables, or passed to other functions or cmdlets. The function's statement list can contain different types of statement lists with the keywords Begin, Process, and End. These statement lists handle input from the pipeline differently. A filter is a special kind of function that uses the Filter keyword. Functions can also act like cmdlets. You can create a function that works just like a cmdlet without using C# programming. For more information, see about_Functions_Advanced. Syntax The following is the syntax for a function: function [<scope:>]<name> [([type]$parameter1[,[type]$parameter2])] { param([type]$parameter1 [,[type]$parameter2]) dynamicparam {<statement list>} begin {<statement list>} process {<statement list>} end {<statement list>} } A function includes the following items: - A Function keyword - A scope (optional) - A name that you select - Any number of named parameters (optional) - One or more Windows PowerShell commands enclosed in braces ({}) For more information about the Dynamicparam keyword and dynamic parameters in functions, see about_Functions_Advanced_Parameters. Simple Functions Functions do not have to be complicated to be useful. The following function gets the environment variables that do not belong to the System account of the current system: function other_env { get-wmiObject win32_environment | where {$_.username -ne "<System>"} } To run the function, type "other_env". You can create a toolbox of useful small functions. Add these functions to your Windows PowerShell profile, as described in about_Profiles and later in this topic. Functions with Parameters You can use parameters with functions, including named parameters, positional parameters, switch parameters, and dynamic parameters. For more information about dynamic parameters in functions, see about_Functions_Advanced_Parameters. Named Parameters You can define any number of named parameters. You can include a default value for named parameters, as described later in this topic. You can define parameters inside the braces using the Param keyword, as shown in the following sample syntax: function <name> { param ([type]$parameter1[,[type]$parameter2]) <statement list> } You can also define parameters outside the braces without the Param keyword, as shown in the following sample syntax: function <name> [([type]$parameter1[,[type]$parameter2])] { <statement list> } There is no difference between these two methods. Use the method that you prefer. When you run the function, the value you supply for a parameter is assigned to a variable that contains the parameter name. The value of that variable can be used in the function. The following example is a function called Small_files. This function has a $size parameter. The function displays all the files that are smaller than the value of the $size parameter, and it excludes directories: function small_files { param ($size) Get-ChildItem c:\ | where { $_.length -lt $size -and $_.PSIsContainer} } In the function, you can use the $size variable, which is the name defined for the parameter. To use this function, type the following command: C:\PS> function small_files -size 50 You can also enter a value for a named parameter without the parameter name. For example, the following command gives the same result as a command that names the Size parameter: C:\PS> function small_files 50 To define a default value for a parameter, type an equal sign and the value after the parameter name, as shown in the following variation of the Small_files example: function small_files ($size = 100) { Get-ChildItem c:\ | where { $_.length -lt $size -and $_.PSIsContainer} } If you type "small_files" without a value, the function assigns 100 to $size. If you provide a value, the function uses that value. Positional Parameters A positional parameter is a parameter without a parameter name. Windows PowerShell uses the parameter value order to associate each parameter value with a parameter in the function. When you use positional parameters, type one or more values after the function name. Positional parameter values are assigned to the $args array variable. The value that follows the function name is assigned to the first position in the $args array, $args[0]. The following Extension function adds the .txt file name extension to a file name that you supply: function extension { $name = $args[0] + ".txt" $name } C:\PS> extension myTextFile myTextFile.txt Functions can take more than one positional parameter. The following example displays any values entered with the function name. function repeat { foreach ($arg in $args) { "The input is $arg" } } C:\PS>repeat one The input is one C:\PS> repeat one two three The input is one The input is two The input is three This function can be used with any number of values. The function assigns each value to a position in the $args array. Switch Parameters A switch is a parameter that does not require a value. Instead, you type the function name followed by the name of the switch parameter. To define a switch parameter, specify the type [switch] before the parameter name, as shown in the following example: function switchExample { param ([switch]$on) if ($on) { "Switch on" } else { "Switch off" } } When you type the On switch parameter after the function name, the function displays "Switch on". Without the switch parameter, it displays "Switch off". C:\PS> SwitchExample -on Switch on C:\PS> SwitchExample Switch off You can also assign a Boolean value to a switch when you run the function, as shown in the following example: C:\PS> SwitchExample -on:$true Switch on C:\PS> SwitchExample -on:$false Switch off Piping Objects to Functions Any function can take input from the pipeline. You can control how a function processes input from the pipeline using Begin, Process, and End keywords. The following sample syntax shows the three keywords: function <name> { begin {<statement list>} process {<statement list>} end {<statement list>} } The Begin statement list runs one time only, at the beginning of the function. The Process statement list runs one time for each object in the pipeline. While the Process block is running, each pipeline object is assigned to the $_ automatic variable, one pipeline object at a time. After the function receives all the objects in the pipeline, the End statement list runs one time. If no Begin, Process, or End keywords are used, all the statements are treated like an End statement list. The following function uses the Process keyword. The function displays examples from the pipeline: function pipelineFunction { process {"The value is: $_"} } To demonstrate this function, enter an array of numbers created with commas, as shown in the following example: C:\PS> 1,2,4 | pipelineFunction The value is: 1 The value is: 2 The value is: 4 When you use a function in a pipeline, the objects piped to the function are assigned to the $input automatic variable. The function runs statements with the Begin keyword before any objects come from the pipeline. The function runs statements with the End keyword after all the objects have been received from the pipeline. The following example shows the $input automatic variable with Begin and End keywords. function PipelineBeginEnd { begin {"Begin: The input is $input"} end {"End: The input is $input" } } If this function is run by using the pipeline, it displays the following results: C:\PS> 1,2,4 | PipelineBeginEnd Begin: The input is End: The input is 1 2 4 When the Begin statement runs, the function does not have the input from the pipeline. The End statement runs after the function has the values. If the function has a Process keyword, the function reads the data in $input. The following example has a Process statement list: function PipelineInput { process {"Processing: $_ " } end {"End: The input is: $input" } } In this example, each object that is piped to the function is sent to the Process statement list. The Process statements run on each object, one object at a time. The $input automatic variable is empty when the function reaches the End keyword. C:\PS> 1,2,4 | PipelineInput Processing: 1 Processing: 2 Processing: 4 End: The input is: Filters A filter is a type of function that runs on each object in the pipeline. A filter resembles a function with all its statements in a Process block. The syntax of a filter is as follows: filter [<scope:>]<name> {<statement list>} The following filter takes log entries from the pipeline and then displays either the whole entry or only the message portion of the entry: filter ErrorLog ([switch]$message) { if ($message) { out-host -inputobject $_.Message } else { $_ } } Function Scope A function exists in the scope in which it was created. If a function is part of a script, the function is available to statements within that script. By default, a function in a script is not available at the command prompt. You can specify the scope of a function. For example, the function is added to the global scope in the following example: function global:get-dependentsvs { get-service | where {$_.dependentservices} } When a function is in the global scope, you can use the function in scripts, in functions, and at the command line. Functions normally create a scope. The items created in a function, such as variables, exist only in the function scope. For more information about scope in Windows PowerShell, see about_Scope. Finding and Managing Functions Using the Function: Drive All the functions and filters in Windows PowerShell are automatically stored in the Function: drive. This drive is exposed by the Windows PowerShell Function provider. When referring to the Function: drive, type a colon after Function, just as you would do when referencing the C or D drive of a computer. The following command displays all the functions in the current session of Windows PowerShell: C:\PS> dir function: The commands in the function are stored as a script block in the definition property of the function. For example, to display the commands in the Help function that comes with Windows PowerShell, type: (dir function:help).definition For more information about the Function: drive, see Function. Reusing Functions in New Sessions When you type a function at the Windows PowerShell command prompt, the function becomes part of the current session. It is available until the session ends. To use your function in all Windows PowerShell sessions, add the function to your Windows PowerShell profile. For more information about profiles, see about_Profiles. You can also save your function in a Windows PowerShell script file. Type your function in a text file, and then save the file with the .ps1 file name extension. Writing Help for Functions The Get-Help cmdlet gets help for functions, as well as for cmdlets, providers, and scripts. To get help for a function, type Get-Help followed by the function name. For example, to get help for the MyDisks function, type: get-help MyDisks You can write help for a function by using either of the two following meth ods: -- Comment-Based Help for Functions Create a help topic by using special keywords in the comments. To creat e comment-based help for a function, the comments must be placed at the beginning or end of the function body or on the lines preceding the fun ction keyword. For more information about comment-based help, see about_Comment_Based_Help. -- XML-Based Help for Functions Create an XML-based help topic, such as the type that is typically created for cmdlets. XML-based help is required if you are localizing help topics into multiple languages. To associate the function with the XML-based help topic, use the .ExternalHelp help comment keyword. For more information about the ExternalHelp keyword, see about_Comment_Based_Help. For more informatio n about XML-based help, see "How to Write Cmdlet Help" in MSDN. SEE ALSO about_Automatic_Variables about_Comment_Based_Help about_Functions_Advanced about_Functions_CmdletBindingAttribute about_Parameters about_Profiles about_Scopes about_Script_Blocks Function (provider) about_functions_advanced TOPIC about_Functions_Advanced SHORT DESCRIPTION Introduces advanced functions that act similar to cmdlets. LONG DESCRIPTION Advanced functions allow you to write functions that can perform operations that are similar to the operations you can perform with cmdlets. Advanced functions are helpful when you want to quickly write a function without having to write a compiled cmdlet using a Microsoft .NET Framework language. These functions are also helpful when you want to restrict the functionality of a compiled cmdlet or when you want to write a function that is similar to a compiled cmdlet. There is a difference between authoring a compiled cmdlet and an advanced function. Compiled cmdlets are .NET Framework classes that must be written in a .NET Framework language such as C#. In contrast, advanced functions are written in the Windows PowerShell script language in the same way that other functions or script blocks are written. Advanced functions use the CmdletBinding attribute to identify them as functions that act similar to cmdlets. The CmdletBinding attribute is similar to the Cmdlet attribute that is used in compiled cmdlet classes to identify the class as a cmdlet. For more information about this attribute, see about_Functions_CmdletBindingAttribute. The following example shows a function that accepts a name and then prints a greeting using the supplied name. Also notice that this function defines a name that includes a verb (Send) and noun (Greeting) pair similar to the verb-noun pair of a compiled cmdlet. However, functions are not required to have a verb-noun name. function Send-Greeting { [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [string] $Name ) Process { write-host ("Hello " + $Name + "") } } The parameters of the function are declared by using the Parameter attribute. This attribute can be used alone, or it can be combined with the Alias attribute or with several other parameter validation attributes. For more information about how to declare parameters (including dynamic parameters that are added at runtime), see about_Functions_Advanced_Parameters. The actual work of the previous function is performed in the Process block, which is equivalent to the ProcessingRecord method that is used by compiled cmdlets to process the data that is passed to the cmdlet. This block, along with the Begin and End blocks, is described in the about_Functions_Advanced_Methods topic. Advanced functions differ from compiled cmdlets in the following ways: - Advanced function parameter binding does not throw an exception when an array of strings is bound to a Boolean parameter. - The ValidateSet attribute and the ValidatePattern attribute cannot pass named parameters. - Advanced functions cannot be used in transactions. SEE ALSO about_Functions_Advanced_CmdletBindingAttribute about_Functions_Advanced_Methods about_Functions_Advanced_Parameters Windows PowerShell Cmdlets (http://go.microsoft.com/fwlink/?LinkID=135279) about_functions_advanced_methods TOPIC about_Functions_Advanced_Methods SHORT DESCRIPTION Describes how functions that specify the CmdletBinding attribute can use the methods and properties that are available to compiled cmdlets. LONG DESCRIPTION Functions that specify the CmdletBinding attribute can access a number of methods and properties through the $pscmdlet variable. These methods include the following methods: - Input-processing methods that compiled cmdlets use to do their work. - The ShouldProcess and ShouldContinue methods that are used to get user feedback before an action is performed. - The ThrowTerminatingError method for generating error records. - Several Write methods that return different types of output. - Several Write methods that return different types of output. All the methods and properties of the PSCmdlet class are available to advanced functions. For more information about these methods and properties, see System.Management.Automation.PSCmdlet in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=142139. Input Processing Methods The methods described in this section are referred to as the input processing methods. For functions, these three methods are represented by the Begin, Process, and End blocks of the function. Each function must include one or more of these blocks. The Windows PowerShell runtime uses the code within these blocks when it is running a function. (These blocks are also available to functions that do not use the CmdletBinding attribute.) Begin This block is used to provide optional one-time preprocessing for the function. The Windows PowerShell runtime uses the code in this block one time for each instance of the function in the pipeline. Process This block is used to provide record-by-record processing for the function. This block might be used any number of times, or not at all, depending on the input to the function. For example, if the function is the first command in the pipeline, the Process block will be used one time. If the function is not the first command in the pipeline, the Process block is used one time for every input that the function receives from the pipeline. If there is no pipeline input, the Process block is not used. This block must be defined if a function parameter is set to accept pipeline input. If this block is not defined and the parameter accepts input from the pipeline, the function will miss the values that are passed to the function through the pipeline. Also, when the function supports confirmation requests (when the SupportsShouldProcess parameter of the Parameter attribute is set to $True), the call to the ShouldProcess method must be made from within the Process block. End This block is used to provide optional one-time post-processing for the function. The following example shows the outline of a function that contains a Begin block for one-time preprocessing, a Process block for multiple record processing, and an End block for one-time post-processing. Function Test-ScriptCmdlet { [CmdletBinding(SupportsShouldProcess=$True)] Param ($Parameter1) Begin{} Process{} End{} } Confirmation Methods ShouldProcess This method is called to request confirmation from the user before the function performs an action that would change the system. The function can continue based on the Boolean value returned by the method. This method can be called only from within the Process{} block of the function. And, the CmdletBinding attribute must declare that the function supports ShouldProcess (as shown in the previous example). For more information about this method, see System.Management.Automation.Cmdlet.ShouldProcess in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142142. For more information about how to request confirmation, see "Requesting Confirmation" in the MSDN library at http://go.microsoft.com/fwlink/?LinkID=136658. ShouldContinue This method is called to request a second confirmation message. It should be called when the ShouldProcess method returns $true. For more information about this method, see System.Management.Automation.Cmdlet.ShouldContinue in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142143. Error Methods Functions can call two different methods when errors occur. When a nonterminating error occurs, the function should call the WriteError method, which is described in the "Write Methods" section. When a terminating error occurs and the function cannot continue, it should call the ThrowTerminatingError method. You can also use the Throw statement for terminating errors and the Write-Error cmdlet for nonterminating errors. For more information, see System.Management.Automation.Cmdlet. ThrowTerminatingError in the MSDN libray at http://go.microsoft.com/fwlink/?LinkId=142144. Write Methods A function can call the following methods to return different types of output. Notice that not all the output goes to the next command in the pipeline. You can also use the various Write cmdlets, such as Write-Error. WriteCommandDetail For information about the WriteCommandDetails method, see System.Management.Automation.Cmdlet.WriteCommandDetail in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142155. WriteDebug To provide information that can be used to troubleshoot a function, make the function call the WriteDebug method. This displays debug messages to the user. For more information, see System.Management.Automation.Cmdlet.WriteDebug in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142156. WriteError Functions should call this method when nonterminating errors occur and the function is designed to continue processing records. For more information, see System.Management.Automation.Cmdlet.WriteError in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142157. Note: If a terminating error occurs, the function should call the ThrowTerminatingError method. WriteObject This method allows the function to send an object to the next command in the pipeline. In most cases, this is the method to use when the function returns data. For more information, see System.Management.Automation.PSCmdlet.WriteObject in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142158. WriteProgress For functions whose actions take a long time to complete, this method allows the function to call the WriteProgress method so that progress information is displayed. For example, you can display the percent completed. For more information, see System.Management.Automation.PSCmdlet.WriteProgress in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142160. WriteVerbose To provide detailed information about what the function is doing, make the function call the WriteVerbose method to display verbose messages to the user. By default, verbose messages are not displayed. For more information, see System.Management.Automation.PSCmdlet.WriteVerbose in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142162. WriteWarning To provide information about conditions that may cause unexpected results, make the function call the WriteWarning method to display warning messages to the user. By default, warning messages are displayed. For more information, see System.Management.Automation.PSCmdlet.WriteWarning in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142164. Note: You can also display warning messages by configuring the WarningPreference variable or by using the Verbose and Debug command-line options. Other Methods and Properties For information about the other methods and properties that can be accessed through the $PSCmdlet variable, see System.Management.Automation.PSCmdlet in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142139. For example, the ParameterSetName property allows you to see the paramete r set that is being used. Parameter sets allow you to create a function tha t performs different tasks based on the parameters that are specified when the function is run. SEE ALSO about_Functions_Advanced about_Functions_CmdletBindingAttributes about_Functions_Advanced_Parameters about_functions_advanced_param... TOPIC about_Functions_Advanced_Parameters SHORT DESCRIPTION Explains how to add static and dynamic parameters to functions that declare the CmdletBinding attribute. LONG DESCRIPTION You can declare your own parameters when you write functions, and you can write functions so that they can access the common parameters that are available to compiled cmdlets. For more information about the Windows PowerShell common parameters, see about_CommonParameters. Static Parameters The following example shows a parameter declaration that defines a ComputerName parameter. This parameter has the following characteristics: - It is required. - It takes input from the pipeline. - It takes an array of strings as input. Param ( [parameter(Mandatory=$true, ValueFromPipeline=$true)] [String[]] $ComputerName ) The only required attribute that must be used when you declare a parameter is the Parameter attribute. However, you can also declare the Alias attribute and several validation arguments. There are no limits to the number of attributes that you can add to a parameter declaration. Parameter Attribute The Parameter attribute is used to declare a parameter of the function. This attribute has the following named arguments that are used to define the characteristics of the parameter, such as whether the parameter is required or optional. Mandatory Named Argument The Mandatory argument indicates that the parameter is required when the function is run. If this argument is not specified, the parameter is an optional parameter. The following example shows the declaration of a parameter that is required when the function is run. Param ( [parameter(Mandatory=$true)] [String[]] $ComputerName ) Position Named Argument The Position argument specifies the position of the parameter. If this argument is not specified, the parameter name or its alias must be explicitly specified when the parameter is set. Also, if none of the parameters of a function have positions, the Windows PowerShell runtime assigns positions to each parameter based on the order in which the parameters are received. The following example shows the declaration of a parameter whose value must be specified as the first argument when the cmdlet is run. Notice that this function could be run with or without specifying the name of the parameter. Param ( [parameter(Position=0)] [String[]] $ComputerName ) ParameterSetName Named Argument The ParameterSetName argument specifies the parameter set to which a parameter belongs. If no parameter set is specified, the parameter belongs to all the parameter sets defined by the function. This behavior means that each parameter set must have one unique parameter that is not a member of any other parameter set. The following example shows the parameter declaration of two parameters that belong to two different parameter sets. Param ( [parameter(Mandatory=$true, ParameterSetName="Computer")] [String[]] $ComputerName ) Param ( [parameter(Mandatory=$true, ParameterSetName="User")] [String[]] $UserName ) For more information about parameter sets, see "Cmdlet Parameter Sets" in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142183. ValueFromPipeline Named Argument The ValueFromPipeline argument specifies that the parameter accepts input from a pipeline object. Specify this argument if the cmdlet accesses the complete object, not just a property of the object. The following example shows the parameter declaration of a mandatory ComputerName parameter that accepts the input object that is passed to the function from the pipeline. Param ( [parameter(Mandatory=$true, ValueFromPipeline=$true)] [String[]] $ComputerName ) ValueFromPipelineByPropertyName Named Argument The valueFromPipelineByPropertyName argument specifies that the parameter accepts input from a property of a pipeline object. Specify this attribute if the following conditions are true: - The parameter accesses a property of the piped object. - The property has the same name as the parameter, or the property has the same alias as the parameter. For example, if the function has a ComputerName parameter, and the piped object has a ComputerName property, the value of the ComputerName property is assigned to the ComputerName parameter of the function. The following example shows the parameter declaration of a ComputerName parameter that accepts input from the ComputerName property of the input object that is passed to the cmdlet. Param ( [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [String[]] $ComputerName ) ValueFromRemainingArguments Named Argument The ValueFromRemainingArguments argument specifies that the parameter accepts all of the remaining arguments that are not bound to the parameters of the function. The following example shows the parameter declaration of a ComputerName parameter that accepts all the remaining arguments of the input object that is passed to the function. Param ( [parameter(Mandatory=$true, ValueFromRemainingArguments=$true)] [String[]] $ComputerName ) HelpMessage Named Argument The HelpMessage argument specifies a message that contains a short description of the parameter. The following example shows a parameter declaration that provides a description of the parameter. Param ( [parameter(Mandatory=$true, HelpMessage="An array of computer names.")] [String[]] $ComputerName ) Alias Attribute The Alias attribute specifies another name for the parameter. There is no limit to the number of aliases that can be assigned to a parameter. The following example shows a mandatory parameter declaration that adds the "CN" alias to the ComputerName parameter. Param ( [parameter(Mandatory=$true)] [alias("CN")] [String[]] $ComputerName ) Parameter Validation Attributes These attributes define how the Windows PowerShell runtime validates the arguments of advanced functions. AllowNull Validation Attribute The AllowNull attribute allows the argument of a mandatory cmdlet parameter to be set to Null. In the following example, the ComputerName parameter can contain a value of Null even though this parameter is a mandatory parameter. Param ( [parameter(Mandatory=$true)] [String] [AllowNull()] $ComputerName ) AllowEmptyString Validation Attribute The AllowEmptyString attribute allows an empty string as the argument of a mandatory cmdlet parameter. In the following example, the ComputerName parameter can contain an empty string ("") even though this parameter is a mandatory parameter. Param ( [parameter(Mandatory=$true)] [String] [AllowEmptyString()] $ComputerName ) AllowEmptyCollection Validation Attribute The AllowEmptyCollection attribute allows an empty collection as the argument of a mandatory parameter. Param ( [parameter(Mandatory=$true)] [String[]] [AllowEmptyCollection()] $ComputerName ) ValidateCount Validation Attribute The ValidateCount attribute specifies the minimum and maximum number of arguments that the parameter can accept. The Windows PowerShell runtime generates an error if the number of arguments is outside that range. In the following example, the ComputerName parameter can have one to five arguments. Param ( [parameter(Mandatory=$true)] [String[]] [ValidateCount(1,5)] $ComputerName ) ValidateLength Validation Attribute The ValidateLength attribute specifies the minimum and maximum length of the parameter argument. The Windows PowerShell runtime generates an error if the length of the parameter argument is outside that range. In the following example, the specified computer names must have one to 10 characters. Param ( [parameter(Mandatory=$true)] [String[]] [ValidateLength(1,10)] $ComputerName ) ValidatePattern Validation Attribute The ValidatePattern attribute specifies a regular expression that validates the pattern of the parameter argument. The Windows PowerShell runtime generates an error if the parameter argument does not match this pattern. In the following example, the argument of the parameter must be a four-digit number, and each digit must be a number 0 to 9. Param ( [parameter(Mandatory=$true)] [String[]] [ValidatePattern("[0-9][0-9][0-9][0-9]")] $ComputerName ) ValidateRange Validation Attribute The ValidateRange attribute specifies the minimum and maximum values of the parameter argument. The Windows PowerShell runtime generates an error if the parameter argument is outside that range. In the following example, the argument of the parameter cannot be less than 0 or greater than 10. Param ( [parameter(Mandatory=$true)] [Int[]] [ValidateRange(0,10)] $Count ) ValidateScript Validation Attribute The ValidateScript attribute specifies a script that is used to validate the parameter argument. The Windows PowerShell runtime generates an error if the script result is false or if the script throws an exception. In the following example the value of the Count parameter must be less than 4. Param ( [parameter()] [Int] [ValidateScript({$_ -lt 4})] $Count ) ValidateSet Attribute The ValidateSet attribute secifies a set of valid values for the argument of the parameter. The Windows PowerShell runtime generates an error if the parameter argument does not match a value in the set. In the following example, the argument of the parameter can contain only the names Steve, Mary, and Carl. Param ( [parameter(Mandatory=$true)] [String[]] [ValidateRange("Steve", "Mary", "Carl")] $UserName ) ValidateNotNull Validation Attribute The ValidateNotNull attribute specifies that the argument of the parameter cannot be set to Null. The Windows PowerShell runtime generates an error if the parameter value is Null. Param ( [parameter(Mandatory=$true)] [String[]] [ValidateNotNull()] $UserName ) ValidateNotNullOrEmpty Validation Attribute The ValidateNotNullOrEmpty attribute specifies that the argument of the parameter cannot be set to Null or it cannot be empty. The Windows PowerShell runtime generates an error if the parameter is specified but its value is Null, an empty string, or an empty array. Param ( [parameter(Mandatory=$true)] [String[]] [ValidateNotNullOrEmpty()] $UserName ) Dynamic Parameters Dynamic parameters are parameters of a cmdlet, function, or script that are available only under certain conditions. For example, several provider cmdlets have parameters that are available only when the cmdlet is used in the provider path. One familiar dynamic parameter is the Encoding parameter of the Set-Item, cmdlet, which is available only when the Set-Item cmdlet is used in a FileSystem provider path. To create a dynamic parameter for a function or script, use the DynamicParam keyword. The syntax is as follows. DynamicParam {<statement-list>} In the statement list, use an If statement to specify the conditions under which the parameter is available in the function. Use the New-Object cmdlet to create a System.Management.Automation.RuntimeDefinedParameter object to represent the parameter and specify its name. You can also use a New-Object command to create a System.Management.Automation.ParameterAttribute object to represent attributes of the parameter, such as Mandatory, Position, or ValueFromPipeline or its parameter set. The following example shows a sample function with standard parameters called Name and Path, and an optional dynamic parameter named DP1. The DP1 parameter is in the PSet1 parameter set and has a type of Int32. The DP1 parameter is available in the Sample function only when the value of the Path parameter contains "HKLM:", indicating that it is being used in the HKEY_LOCAL_MACHINE registry drive. function Sample { Param ([String]$Name, [String]$Path) DynamicParam { if ($path -match "*HKLM*:") { $dynParam1 = new-object System.Management.Automation.RuntimeDefinedParameter("dp1", [Int32], $attributeCollection) $attributes = new-object System.Management.Automation.ParameterAttrib ute $attributes.ParameterSetName = 'pset1' $attributes.Mandatory = $false $attributeCollection = new-object -Type System.Collections.ObjectModel.Collection``1[System.Attribute ] $attributeCollection.Add($attributes) $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("dp1", $dynParam1) return $paramDictionary } End if } } For more information, see "RuntimeDefinedParameter Class" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkID=145130. SEE ALSO about_Advanced Functions about_Functions_Advanced_Methods about_Functions_CmdletBindingAttribute about_functions_cmdletbindinga... TOPIC about_Functions_CmdletBindingAttribute SHORT DESCRIPTION Describes an attribute that declares a function that acts similar to a compiled cmdlet. LONG DESCRIPTION When you write functions, you can add the CmdletBinding attribute so that Windows PowerShell will bind the parameters of the function in the same way that it binds the parameters of compiled cmdlets. When this attribute is declared, Windows PowerShell also sets the $PSCmdlet automatic variable. When you use cmdlet binding, unknown parameters and positional arguments that have no matching positional parameters cause parameter binding to fail. Also, a function or script with cmdlet binding does not use the $args variable. Note: Compiled cmdlets use the required Cmdlet attribute, which is similar to the CmdletBinding attribute that is described in this topic. The following example shows the outline of a function that specifies all the optional arguments of the CmdletBinding attribute. A brief description of each argument follows this example. { [CmdletBinding(SupportsShouldProcess=<Boolean>, ConfirmImpact=<String>, DefaultParameterSetName=<String>)] Param ($Parameter1) Begin{} Process{} End{} } SupportsShouldProcess When the SupportsShouldProcess argument is set to true, it indicates that the function supports calls to the ShouldProcess method, which is used to prompt the user for feedback before the function makes a change to the system. When this argument is specified, the Confirm and WhatIf parameters are enabled for the function. For more information about confirmation requests, see "Requesting Confirmation" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=136658. DefaultParameterSetName The DefaultParameterSetName argument specifies the name of the parameter set that Windows PowerShell will attempt to use when it cannot determine which parameter set to use. You can avoid this issue by making the unique parameter of each parameter set a mandatory parameter. ConfirmImpact The ConfirmImpact argument specifies when the action of the function should be confirmed by a call to the ShouldProcess method. The call to the ShouldProcess method displays a confirmation prompt only when the ConfirmImpact argument is equal to or greater than the value of the $ConfirmPreference preference variable. (The default value of the argument is Medium.) Specify this argument only when the SupportsShouldProcess argument is also specified. SEE ALSO about_Functions_Advanced about_Functions_CmdletBindingAttribute about_Functions_ParameterAttributes about_hash_tables TOPIC about_Hash_Tables SHORT DESCRIPTION Describes how to create, use, and sort hash tables in Windows PowerShell. LONG DESCRIPTION A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more name/value pairs. For example, a hash table might contain a series of names and employee IDs, computer names and IP addresses, or message IDs and message text. Hash tables are frequently used because they are very efficient for finding and retrieving data. You can use hash tables to store lists and to create calculated properties in Windows PowerShell. And, Windows PowerShell has a cmdlet, ConvertFrom-StringData, that converts strings to a hash table. Creating Hash Tables The items in a hash table are arranged in name/value pairs, such as: Msg1="Please enter your password." Msg2="The path parameter is required." Msg3="The alias of Get-Command is gcm." The values are mapped to or associated with the names so that when you submit the name, Windows PowerShell returns the value. In Windows PowerShell, the syntax of a hash table is as follows: @{ <name> = <value>; [<name> = When you create a hash table, follow these guidelines: - Begin the hash table with an at sign (@). - Enclose the hash table in braces ({}). - Enter one or more name-value pairs for the content of the hash table. - Use an equal sign (=) to separate each name from its value. - Use a semicolon (;) to separate the name/value pairs. - If a name or value contains spaces, enclose it in quotation marks. For example, a hash table of the previous user messages looks like this: @{ Msg1="Please enter your password."; Msg2="The path parameter is required."; Msg3="The alias of Get-Command is gcm."; } To use a hash table in scripts and commands, save it in a variable. The value of the variable is a hash table object (System.Collections.Hashtable), and each name in the name/value pairs is a property of the hash table object. The following commands save the user-message hash table in the $a variable and use the dot method to display the values. C:\PS> $a = @{ >> Msg1="Please enter your password."; >> Msg2="The path parameter is required."; >> Msg3="The alias of Get-Command is gcm."; >> } C:\PS> $a Name Value ---- ----- Msg1 Please enter your password. Msg3 The alias of Get-Command is gcm. Msg2 The path parameter is required. C:\PS> $a.Msg1 Please enter your password. Hash tables are not limited to one type of data. You can enter any data type in a hash table, and you can combine data types in a single hash table. For example, you can build a hash table that contains an integer, a call to a cmdlet, and a string. Sorting Hash Tables To sort the hash table alphabetically by keys or values, use the GetEnumerator method of hash tables to get the keys and values in the hash table, and then use the Sort-Object cmdlet to sort them. For example, the following command sorts the hash table in $a alphabetically by keys. C:\PS> $a.getenumerator() | sort-object -property key Name Value ---- ----- Msg1 Please enter your password. Msg2 The path parameter is required. Msg3 The alias of Get-Command is gcm. The following command uses the same method to sort the hash values in descending order. C:\PS> $a.getenumerator() | sort-object -property value -descending Name Value ---- ----- Msg2 The path parameter is required. Msg3 The alias of Get-Command is gcm. Msg1 Please enter your password. ConvertFrom-StringData The ConvertFrom-StringData cmdlet converts a string or a here-string of name/value pairs into a hash table. You can use the ConvertFrom-StringData cmdlet safely in the Data section of a script, and you can use it with the Import-LocalizedData cmdlet to display user messages in the user-interface (UI) culture of the current user. Here-strings are especially useful when the values in the hash table include quotation marks. (For more information about here-strings, see about_Quoting_Rules.) The following example shows how to create a here-string of the user messages in the previous example and how to use ConvertFrom-StringData to convert them from a string into a hash table. The following command creates a here-string of the name/value pairs and then saves it in the $string variable. C:\PS> $string = @" Msg1="Please enter your password." Msg2="The path parameter is required." Msg3="The alias of Get-Command is gcm." "@ This command uses the ConvertFrom-StringData cmdlet to convert the here-string into a hash table. C:\PS> convertfrom-stringdata $string Name Value ---- ----- Msg3 "The alias of Get-Command is gcm." Msg2 "The path parameter is required." Msg1 "Please enter your password." SEE ALSO about_Arrays about_Quoting_Rules about_Script_Internationalization ConvertFrom-StringData Import-LocalizedData about_History TOPIC about_History SHORT DESCRIPTION Describes how to retrieve and run commands in the command history. LONG DESCRIPTION When you enter a command at the command prompt, Windows PowerShell saves the command in the command history. You can use the commands in the history as a record of your work. And, you can recall and run the commands from the command history. History Cmdlets Windows PowerShell has a set of cmdlets that manage the command history. Cmdlet (Alias) Description ------------------- ------------------------------------------ Get-History (h) Gets the command history. Invoke-History (r) Runs a command in the command history. Add-History Adds a command to the command history. Clear-History (clh) Deletes commands from the command history. Keyboard Shortcuts for Managing History In the Windows PowerShell console, you can use the following shortcuts to manage the command history. For other host applications, see the product documentation. Use this key To perform this action ------------- ---------------------------------------------- UP ARROW Displays the previous command. DOWN ARROW Displays the next command. F7 Displays the command history. To hide the history, press ESC. F8 Finds a command. Type one or more characters, and then press F8. For the next instance, press F8 again. F9 Find a command by history ID. Type the history ID, and then press F9. To find the ID, press F7. MaximumHistoryCount The $MaximumHistoryCount preference variable determines the maximum number of commands that Windows PowerShell saves in the command history. The default value is 64, meaning that Windows PowerShell saves the 64 most recent commands, but you can change the value of the variable. For example, the following command raises the $MaximumHistoryCount to 100 commands: $MaximumHistoryCount = 100 To apply the setting, restart Windows PowerShell. To save the new variable value for all your Windows PowerShell sessions, add the assignment statement to a Windows PowerShell profile. For more information, see about_Profiles. Order of Commands in the History Commands are added to the history when the command finishes executing, not when the command is entered. If commands take some time to be completed, or if the commands are executing in a nested prompt, the commands might appear to be out of order in the history. (Commands that are executing in a nested prompt are completed only when you exit the prompt level.) SEE ALSO about_Line_Editing about_Variables about_Preference_Variables about_If TOPIC about_If SHORT DESCRIPTION Describes a language command you can use to run statement lists based on the results of one or more conditional tests. LONG DESCRIPTION You can use the If statement to run code blocks if a specified conditional test evaluates to true. You can also specify one or more additional conditional tests to run if all the prior tests evaluate to false. Finally, you can specify an additional code block that is run if no other prior conditional test evaluates to true. Syntax The following example shows the If statement syntax: if (<test1>) {<statement list 1>} [elseif (<test2>) {<statement list 2>}] [else {<statement list 3>}] When you run an If statement, Windows PowerShell evaluates the <test1> conditional expression as true or false. If <test1> is true, <statement list 1> runs, and Windows PowerShell exits the If statement. If <test1> is false, Windows PowerShell evaluates the condition specified by the <test2> conditional statement. If <test2> is true, <statement list 2> runs, and Windows PowerShell exits the If statement. If both <test1> and <test2> evaluate to false, the <statement list 3> code block runs, and Windows PowerShell exits the If statement. You can use multiple Elseif statements to chain a series of conditional tests so that each test is run only if all the previous tests are false. If you need to create an If statement that contains many Elseif statements, consider using a Switch statement instead. Examples The simplest If statement contains a single command and does not contain any Elseif statements or any Else statements. The following example shows the simplest form of the If statement: if ($a -gt 2) { Write-Host "The value $a is greater than 2." } In this example, if the $a variable is greater than 2, the condition evaluates to true, and the statement list runs. However, if $a is less than or equal to 2 or is not an existing variable, the If statement does not display a message. By adding an Else statement, a message is displayed when $a is less than or equal to 2, as the next example shows: if ($a -gt 2) { Write-Host "The value $a is greater than 2." } else { Write-Host "The value $a is less than or equal to 2, is not created or is not initialized." } To further refine this example, you can use the Elseif statement to display a message when the value of $a is equal to 2, as the next example shows: if ($a -gt 2) { Write-Host "The value $a is greater than 2." } elseif ($a -eq 2) { Write-Host "The value $a is equal to 2." } else { Write-Host "The value $a is less than 2 or was not created or initialized." } SEE ALSO about_Comparison_Operators about_Switch about_job_details TOPIC about_Job_Details SHORT DESCRIPTION Provides details about background jobs on local and remote computers. DETAILED DESCRIPTION This topic explains the concept of a background job and provides technical information about how background jobs work in Windows PowerShell. This topic is a supplement to the about_Jobs and about_Remote_Jobs topics. Important: Background jobs that are started by using Start-Job or the AsJob parameter of Invoke-Command rely on the Windows PowerShell remoting infrastructure. To use these features, Windows PowerShell must be configured for remoting, even if the background job is runs only on the local computer. For more information, see about_Remote_Requirements. ABOUT BACKGROUND JOBS A background job runs a command or expression asynchronously. It might run a cmdlet, a function, a script, or any other command-based task. It is designed to run commands that take an extended period of time, but you can use it to run any command in the background. When a synchronous command runs, the Windows PowerShell command prompt is suppressed until the command is complete. But a background job does not suppress the Windows PowerShell prompt. A command to start a background job returns a job object. The prompt returns immediately so you can work on other tasks while the background job runs. However, when you start a background job, you do not get the results immediately even if the job runs very quickly. The job object that is returned contains useful information about the job, but it does not contain the job results. You must run a separate command to get the job results. You can also run commands to stop the job, to wait for the job to be completed, and to delete the job. To make the timing of a background job independent of other commands, each background job runs in its own Windows PowerShell environment (a "session"). However, this can be a temporary connection that is created only to run the job and is then destroyed, or it can be a persistent session (a PSSession) that you can use to run several related jobs or commands. USING THE JOB CMDLETS Use a Start-Job command to start a background job on a local computer. Start-Job returns a job object. You can also get objects representing the jobs that were started on the local computer by using the Get-Job cmdlet. To get the job results, use a Receive-Job command. If the job is not complete, Receive-Job returns partial results. You can also use the Wait-Job cmdlet to suppress the command prompt until one or all of the jobs that were started in the session are complete. To stop a background job, use the Stop-Job cmdlet. To delete a job, use the Remove-Job cmdlet. For more information about how the cmdlets work, see the Help topic for each cmdlet, and see about_Jobs. STARTING BACKGROUND JOBS ON REMOTE COMPUTERS You can create and manage background jobs on a local or remote computer. To run a background job remotely, use the AsJob parameter of a cmdlet such as Invoke-Command, or use the Invoke-Command cmdlet to run a Start-Job command remotely. You can also start a background job in an interactive session. For more information about remote background jobs, see about_Remote_Jobs. CHILD JOBS Each background job consists of a parent job and one or more child jobs. In jobs started by using Start-Job or the AsJob parameter of Invoke-Command, the parent job is an executive. It does not run any commands or return any results. The commands are actually run by the child jobs. (Jobs started by using other cmdlets might work differently.) The child jobs are stored in the ChildJobs property of the parent job object. The ChildJobs property can contain one or many child job objects. The child job objects have a name, ID, and instance ID that differ from the parent job so that you can manage the parent and child jobs individually or as a unit. To see the parent and child jobs in a job, use the Get-Job cmdlet to get the parent job, and then pipe the job to a Format-List command that display s the Name and ChildJobs properties of the objects, as shown in the following command. C:\PS> get-job | format-list -property Name, ChildJobs Name : Job1 ChildJobs : {Job2} You can also use a Get-Job command on the child job, as shown in the following command: C:\PS> get-job job2 Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 2 Job2 Completed True localhost get-process The configuration of the child job depends on the command that you use to start the job. -- When you use Start-Job to start a job on a local computer, the job consists of an executive parent job and a child job that runs the command. -- When you use the AsJob parameter of Invoke-Command to start a job on one or more computers, the job consists of an executive parent job and a child job for each job run on each computer. -- When you use Invoke-Command to run a Start-Job command on one or more remote computers, the result is the same as a local command run on each remote computer. The command returns a job object for each computer. The job object consists of an executive parent job and one child job that runs the command. The parent job represents all of the child jobs. When you manage a parent job, you also manage the associated child jobs. For example, if you stop a parent job, all child jobs are stopped. If you get the results of a parent job, you get the results of all child jobs. However, you can also manage child jobs individually. This is most useful when you want to investigate a problem with a job or get the results of only one of a number of child jobs started by using the AsJob parameter of Invoke-Command. (The backtick character [`] is the continuation character.) The following command uses the AsJob parameter of Invoke-Command to start background jobs on the local computer and two remote computers. The command saves the job in the $j variable. C:\PS> $j = invoke-command -computername localhost, Server01, Server02 ` -command {get-date} -AsJob When you display the Name and ChildJob properties of the job in $j, it shows that the command returned a job object with three child jobs, one for each computer. C:\PS> $j | format-list name, childjobs Name : Job3 ChildJobs : {Job4, Job5, Job6} When you display the parent job, it shows that the job failed. C:\PS> $j Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job3 Failed True localhost,server... get-date But when you run a Get-Job command on each of the child jobs, it shows that only one failed. PS C:\ps-test> get-job job4, job5, job6 Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 4 Job4 Completed True localhost get-date 5 Job5 Failed False Server01 get-date 6 Job6 Completed True Server02 get-date To get the results of all child jobs, use the Receive-Job cmdlet to get the results of the parent job. But you can also get the results of a particular child job, as shown in the following command. C:\PS> receive-job -job6 -keep | format-table ComputerName, DateTime -a uto ComputerName DateTime ------------ -------- Server02 Thursday, March 13, 2008 4:16:03 PM The child jobs feature of Windows PowerShell background jobs gives you more control over the jobs that you run. SEE ALSO about_Jobs about_Remote_Jobs about_Remote Invoke-Command Start-Job Get-Job Wait-Job Stop-Job Remove-Job New-PSSession Enter-PSSession Exit-PSSession about_jobs TOPIC about_Jobs SHORT DESCRIPTION Provides information about how Windows PowerShell background jobs run a command or expression in the background without interacting with the current session. LONG DESCRIPTION This topic explains how to run background jobs in Windows PowerShell on a local computer. For information about running background jobs on remote computers, see about_Remote_Jobs. When you start a background job, the command prompt returns immediately, even if the job takes an extended time to complete. You can continue to work in the session without interruption while the job runs. Important: Background jobs that are started by using Start-Job or the AsJob parameter of Invoke-Command rely on the Windows PowerShell remoting infrastructure. To use these features, Windows PowerShell must be configured for remoting, even if the background job is run only on the local computer. For more information, see about_Remote_Requirements. HOW TO START A JOB ON THE LOCAL COMPUTER To start a background job on the local computer, use the Start-Job cmdlet. To write a Start-Job command, enclose the command that the job runs in braces ( { } ). Use the ScriptBlock parameter to specify the command. The following command starts a background job that runs a Get-Process command on the local computer. start-job -scriptblock {get-process} The Start-Job command returns an object that represents the job. The job object contains useful information about the job, but it does not contain the job results. Save the job object in a variable, and then use it with the other Job cmdlets to manage the background job. The following command starts a job object and saves the resulting job object in the $job variable. $job = start-job -scriptblock {get-process} You can also use the Get-Job cmdlet to get objects that represent the jobs started in the current session. Get-Job returns the same job object that Start-Job returns. GETTING JOB OBJECTS To get object that represent the background jobs that were started in the current session, use the Get-Job cmdlet. Without parameters, Get-Job returns all of the jobs that were started in the current session. For example, the following command gets the jobs in the current session. get-job Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job1 Running True localhost get-process You can also save the job object in a variable and use it to represent the job in a later command. The following command gets the job with ID 1 and saves it in the $job variable. $job = get-job -id 1 The job object contains the state of the job, which indicates whether the job has finished. A finished job has a state of "Complete" or "Failed". A job might also be blocked or running. get-job Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job1 Complete True localhost get-process GETTING THE RESULTS OF A JOB When you run a background job, the results do not appear immediately. Instead, the Start-Job cmdlet returns a job object that represents the job, but it does not contain the results. To get the results of a background job, use the Receive-Job cmdlet. The following command uses the Receive-Job cmdlet to get the results of the job. It uses a job object saved in the $job variable to identify the job. receive-job -job $job The Receive-Job cmdlet returns the results of the job. Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 103 4 11328 9692 56 1176 audiodg 804 14 12228 14108 100 101.74 1740 CcmExec 668 7 2672 6168 104 32.26 488 csrss ... You can also save the results of a job in a variable. The following command saves the results of the job in the $job variable to the $results variable. $results = receive-job -job $job And, you can save the results of the job in a file by using the redirectio n operator (>) or the Out-File cmdlet. The following command uses the redirection operator to save the results of the job in the $job variable i n the Results.txt file. receive-job -job $job > results.txt GETTING AND KEEPING PARTIAL JOB RESULTS The Receive-Job cmdlet returns the results of a background job. If the job is complete, Receive-Job returns the complete results of the job. If the job is still running, Receive-Job gets the results that have been generated thus far. You can run Receive-Job commands again to get the remaining results. When Receive-Job returns results, by default, it deletes the results from the cache where job results are stored. If you run another Receive-Job command, you get only the results that were not yet received. The following commands show the results of Receive-Job commands run before the job is complete. C:\PS> receive-job -job $job Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 103 4 11328 9692 56 1176 audiodg 804 14 12228 14108 100 101.74 1740 CcmExec C:\PS> receive-job -job $job Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 68 3 2632 664 29 0.36 1388 ccmsetup 749 22 21468 19940 203 122.13 3644 communicator 905 7 2980 2628 34 197.97 424 csrss 1121 25 28408 32940 174 430.14 3048 explorer To prevent Receive-Job from deleting the job results that it has returned, use the Keep parameter. As a result, Receive-Job returns all of the results that have been generated until that time. The following commands show the effect of using the Keep parameter on a job that is not yet complete. C:\PS> receive-job -job $job -keep Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 103 4 11328 9692 56 1176 audiodg 804 14 12228 14108 100 101.74 1740 CcmExec C:\PS> receive-job -job $job -keep Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 103 4 11328 9692 56 1176 audiodg 804 14 12228 14108 100 101.74 1740 CcmExec 68 3 2632 664 29 0.36 1388 ccmsetup 749 22 21468 19940 203 122.13 3644 communicator 905 7 2980 2628 34 197.97 424 csrss 1121 25 28408 32940 174 430.14 3048 explorer WAITING FOR THE RESULTS If you run a command that takes a long time to be completed, you can use the properties of the job object to determine when the job is complete. The following command uses the Get-Job object to get all of the background jobs in the current session. get-job The results appear in a table. The status of the job appears in the State column. Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job1 Complete True localhost get-process 2 Job2 Running True localhost get-eventlog -log syst... 3 Job3 Complete True localhost dir -path c:\* -recurse In this case, the State property reveals that Job 2 is still running. If you were to use the Receive-Job cmdlet to get the job results now, the results would be incomplete. You can use the Receive-Job cmdlet repeatedly to get all of the results. By default, each time you use it, you get only the results that were not already received, but you can use the Keep parameter of the Receive-Job cmdlet to retain the results, even though they were already received. At this point, you can write the results to a file and then append the newly received results as they arrive. Or, you can wait and check the state of the job later. Or, you can use the Wait-Job cmdlet to wait for any or all of the results of the job. Wait-Job lets you wait for a particular job, for all jobs, or for any of the jobs to be completed. The following command uses the Wait-Job cmdlet to wait for a job with ID 10. wait-job -ID 10 As a result, the Windows PowerShell prompt is suppressed until the job is completed. You can also wait for a predetermined period of time. This command uses the Timeout parameter to limit the wait to 120 seconds. When the time expires, the command prompt returns, but the job continues to run in the background. wait-job -ID 10 -timeout 120 STOPPING A JOB To stop a background job, use the Stop-Job cmdlet. The following command starts a job to get every entry in the System event log. It saves the job object in the $job variable. $job = start-job -scriptblock {get-eventlog -log system} The following command stops the job. It uses a pipeline operator (|) to send the job in the $job variable to Stop-Job. $job | stop-job DELETING A JOB To delete a background job, use the Remove-Job cmdlet. The following command deletes the job in the $job variable. remove-job -job $job INVESTIGATING A FAILED JOB To find out why a job failed, use the Reason subproperty of the job object. The following command starts a job without the required credentials. It saves the job object in the $job variable. $job = start-job -scriptblock {new-item -path HKLM:\Software\MyCompany } Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job1 Failed False localhost new-item -path HKLM:\S... The following command uses the Reason property to find the error that caused the job to fail. $job.ChildJobs[0].JobStateInfo.Reason In this case, the job failed because the remote computer required explicit credentials to run the command. The value of the Reason property is: Connecting to remote server failed with the following error message : Access is denied. THE JOB CMDLETS Start-Job Starts a background job on a local computer. Get-Job Gets the background jobs that were started in the current session. Receive-Job Gets the results of background jobs. Stop-Job Stops a background job. Wait-Job Suppresses the command prompt until one or all jobs are complete. Remove-Job Deletes a background job. Invoke-Command The AsJob parameter runs any command as a background job o n a remote computer. You can also use Invoke-Command to run any job command remotely, including a Start-Job command. SEE ALSO about_Remote_Jobs about_Job_Details about_Remote about_PSSessions Start-Job Get-Job Receive-Job Stop-Job Wait-Job Remove-Job Invoke-Command about_join TOPIC about_join SHORT DESCRIPTION Describes how the join operator (-join) combines multiple strings into a single string. LONG DESCRIPTION The join operator concatenates a set of strings into a single string. The strings are appended to the resulting string in the order that they appear in the command. Syntax The following diagram shows the syntax for the join operator. -Join <String[]> <String[]> -Join <Delimiter> Parameters String[] Specifies one or more strings to be joined. Delimiter Specifies one or more characters placed between the concatenated strings. The default is no delimiter (""). Remarks The unary join operator (-join <string[]>) has higher precedence than a comma. As a result, if you submit a comma-separated list of strings to the unary join operator, only the first string (before the first comma) is submitted to the join operator. To use the unary join operator, enclose the strings in parentheses, or store the strings in a variable, and then submit the variable to join. For example: -join "a", "b", "c" a b c -join ("a", "b", "c") abc $z = "a", "b", "c" -join $z abc Examples The following statement joins three strings: -join ("Windows", "PowerShell", "2.0") WindowsPowerShell2.0 The following statement joins three strings delimited by a space: "Windows", "PowerShell", "2.0" -join " " Windows PowerShell 2.0 The following statements use a multiple-character delimiter to join three strings: $a = "WIND", "SP", "ERSHELL" $a -join "OW" WINDOWSPOWERSHELL The following statement joins the lines in a here-string into a single string. Because a here-string is one string, the lines in the here-string must be split before they can be joined. You can use this method to rejoin the strings in an XML file that has been saved in a here-string: $a = @' a b c '@ (-split $a) -join " " a b c SEE ALSO about_Operators about_Comparison_Operators about_Split about_Language_Keywords TOPIC about_Language_Keywords SHORT DESCRIPTION Describes the keywords in the Windows PowerShell scripting language. LONG DESCRIPTION Windows PowerShell has the following language keywords. For more information, see the about topic for the keyword and the information that follows the table. Keyword Reference ------- --------- Begin about_Functions, about_Functions_Advanced Break about_Break, about_Trap Catch about_Try_Catch_Finally Continue about_Continue, about_Trap Data about_Data_Sections Do about_Do, about_While Dynamicparam about_Functions_Advanced_Parameters Else about_If Elseif about_If End about_Functions, about_Functions_Advanced_Methods Exit Described in this topic. Filter about_Functions Finally about_Try_Catch_Finally For about_For Foreach about_Foreach From Reserved for future use. Function about_Functions, about_Functions_Advanced If about_If In about_Foreach Param about_Functions Process about_Functions, about_Functions_Advanced Return about_Return Switch about_Switch Throw about_Throw, about_Functions_Advanced_Methods Trap about_Trap, about_Break, about_Try_Catch_Finally Try about_Try_Catch_Finally Until about_Do While about_While, about_Do Language Keywords Begin ----- Specifies one part of the body of a function, along with the Dynamicparam, Process, and End keywords. The Begin statement list runs one time before any objects are received from the pipeline. Syntax: function <name> { dynamicparam {<statement list>} begin {<statement list>} process {<statement list>} end {<statement list>} } Break ----- Causes a script to exit a loop. Syntax: while (<condition>) { <statements> ... break ... <statements> } Catch ----- Specifies a statement list to run if an error occurs in the accompanying Try statement list. An error type requires brackets. The second pair of brackets indicates that the error type is optional. Syntax: try {<statement list>} catch [[<error type>]] {<statement list>} Continue -------- Causes a script to stop running a loop and to go back to the condition. If the condition is met, the script begins the loop again. Syntax: while (<condition>) { <statements> ... continue ... <statements> } Data ---- In a script, defines a section that isolates data from the script logic. Can also include If statements and some limited commands. Syntax: data <variable> [-supportedCommand <cmdlet-name>] {<permitted content>} Do -- Used with the While or Until keyword as a looping construct. Windows PowerShell runs the statement list at least one time, unlike a loop that uses While. Syntax: do {<statement list>} while (<condition>) do {<statement list>} until (<condition>) Dynamicparam ------------ Specifies one part of the body of a function, along with the Begin, Process, and End keywords. Dynamic parameters are added at run time. Syntax: function <name> { dynamicparam {<statement list>} begin {<statement list>} process {<statement list>} end {<statement list>} } Else ---- Used with the If keyword to specify the default statement list. Syntax: if (<condition>) {<statement list>} else {<statement list>} Elseif ------ Used with the If and Else keywords to specify additional conditionals. The Else keyword is optional. Syntax: if (<condition>) {<statement list>} elseif (<condition>) {<statement list>} else {<statement list>} End --- Specifies one part of the body of a function, along with the Dynamicparam, Begin, and End keywords. The End statement list runs one time after all the objects have been received from the pipeline. Syntax: function <name> { dynamicparam {<statement list>} begin {<statement list>} process {<statement list>} end {<statement list>} } Exit ---- Causes Windows PowerShell to exit a script or a Windows PowerShell instance. Syntax: exit Filter ------ Specifies a function in which the statement list runs one time for each input object. It has the same effect as a function that contains only a Process block. Syntax: filter <name> {<statement list>} Finally ------- Defines a statement list that runs after statements that are associated with Try and Catch. A Finally statement list runs even if you press CTRL+C to leave a script or if you use the Exit keyword in the script. Syntax: try {<statement list>} catch [<error type] {<statement list>} finally {<statement list>} For --- Defines a loop by using a condition. Syntax: for (<initialize>; <condition>; <iterate>) { Foreach ------- Defines a loop by using each member of a collection. Syntax: foreach (<item> in <collection>){<statement list>} From ----- Reserved for future use. Function -------- Creates a named statement list of reusable code. You can name the scope a function belongs to. And, you can specify one or more named parameters by using the Param keyword. Within the function statement list, you can include Dynamicparam, Begin, Process, and End statement lists. Syntax: function [<scope:>]<name> { param ([type]<$pname1> [, [type]<$pname2>]) dynamicparam {<statement list>} begin {<statement list>} process {<statement list>} end {<statement list>} } You also have the option of defining one or more parameters outside the statement list after the function name. Syntax: function [<scope:>]<name> [([type]<$pname1>, [[type] dynamicparam {<statement list>} begin {<statement list>} process {<statement list>} end {<statement list>} } If -- Defines a conditional. Syntax: if (<condition>) {<statement list>} In -- Used in a Foreach statement to create a loop that uses each member of a collection. Syntax: foreach (<item> in <collection>){<statement list>} Param ----- Defines the parameters in a function. Syntax: function [<scope:>]<name> { param ([type]<$pname1>[, [[type]<$pname2>]]) <statement list> } Process ------- Specifies a part of the body of a function, along with the Dynamicparam, Begin, and End keywords. When a Process statement list receives input from the pipeline, the Process statement list runs one time for each element from the pipeline. If the pipeline provides no objects, the Process statement list does not run. If the command is the first command in the pipeline, the Process statement list runs one time. Syntax: function <name> { dynamicparam {<statement list>} begin {<statement list>} process {<statement list>} end {<statement list>} } Return ------ Causes Windows PowerShell to leave the current scope, such as a script or function, and writes the optional expression to the output. Syntax: return [<expression>] Switch ------ Specifies a variety of actions to be performed on items from the pipeline or from a file. You can use either of the following syntax models. Syntax 1: switch [-regex|-wildcard|-exact][-casesensitive] ( pipeline ) { <string>|<number>|<variable>|{ <string>|<number>|<variable>|{ ... default {<statement list>} } Syntax 2: switch [-regex|-wildcard|-exact][-casesensitive] -file filename { <string>|<number>|<variable>|{ <string>|<number>|<variable>|{ ... default {<statement list>} } Throw ----- Throws an object as an error. Syntax: throw [<object>] Trap ---- Defines a statement list to be run if an error is encountered. An error type requires brackets. The second pair of brackets indicates that the error type is optional. Syntax: trap [[<error type>]] {<statement list>} Try --- Defines a statement list to be checked for errors while the statements run. If an error occurs, Windows PowerShell continues running in a Catch or Finally statement. An error type requires brackets. The second pair of brackets indicates that the error type is optional. Syntax: try {<statement list>} catch [[<error type]] {<statement list>} finally {<statement list>} Until ----- Used in a Do statement as a looping construct where the statement list is executed at least one time. Syntax: do {<statement list>} until (<condition>) While ----- Used in a Do statement as a looping construct where the statement list is executed at least one time. Syntax: do {<statement list>} while (<condition>) SEE ALSO about_escape_characters about_special_characters about_wildcards about_Line_Editing TOPIC about_Line_Editing SHORT DESCRIPTION Describes how to edit commands at the Windows PowerShell command prompt. LONG DESCRIPTION The Windows PowerShell console has some useful features to help you to edit commands at the Windows PowerShell command prompt. Move Left and Right To move the cursor one character to the left, press the LEFT ARROW key. To move the cursor one word to the left, press CTRL+LEFT ARROW. To move the cursor one character to the right, press the RIGHT ARROW key. To move the cursor one word to the right, press CTRL+RIGHT ARROW. Line Start and End To move to the beginning of a line, press the HOME key. To move to the end of a line, press the END key. Delete Characters To delete the character in behind the cursor, press the BACKSPACE key. To delete the character in front of the cursor, press the DELETE key. Delete the Remainder of a Line To delete all the characters in the line after the cursor, press CTRL+END. Insert/Overstrike Mode To change to overstrike mode, press the INSERT key. To return to insert mode, press INSERT again. Tab Completion To complete a command, such as the name of a cmdlet, a cmdlet parameter, or a path, press the TAB key. If the first suggestion that is displayed is not what you want, press the TAB key again. SEE ALSO about_Command_Syntax about_Path_Syntax about_locations TOPIC about_Locations SHORT DESCRIPTION Describes how to access items from the working location in Windows PowerShell. LONG DESCRIPTION The current working location is the default location to which commands point. In other words, this is the location that Windows PowerShell uses if you do not supply an explicit path to the item or location that is affected by the command. In most cases, the current working location is a drive accessed through the Windows PowerShell FileSystem provider and, in some cases, a directory on that drive. For example, you might set your current working location to the following location: C:\Program Files\Windows PowerShell As a result, all commands are processed from this location unless another path is explicitly provided. Windows PowerShell maintains the current working location for each drive even when the drive is not the current drive. This allows you to access items from the current working location by referring only to the drive of another location. For example, suppose that your current working location is C:\Windows. Now, suppose you use the following command to change your current working location to the HKLM: drive: Set-Location HKLM: Although your current location is now the registry drive, you can still access items in the C:\Windows directory simply by using the C: drive, as shown in the following example: Get-ChildItem C: Windows PowerShell remembers that your current working location for that drive is the Windows directory, so it retrieves items from that directory. The results would be the same if you ran the following command: Get-ChildItem C:\Windows In Windows PowerShell, you can use the Get-Location command to determine the current working location, and you can use the Set-Location command to set the current working location. For example, the following command sets the current working location to the Windows directory of the C: drive: Set-Location c:\windows After you set the current working location, you can still access items from other drives simply by including the drive name (followed by a colon) in the command, as shown in the following example: Get-ChildItem HKLM :\software The example command retrieves a list of items in the Software container of the HKEY Local Machine hive in the registry. Windows PowerShell also allows you to use special characters to represent the current working location and its parent location. To represent the current working location, use a single period. To represent the parent of the current working location, use two periods. For example, the following specifies the System subdirectory in the current working location: Get-ChildItem .\system If the current working location is C:\Windows, this command returns a list of all the items in C:\Windows\System. However, if you use two periods, the parent directory of the current working directory is used, as shown in the following example: Get-ChildItem ..\"program files" In this case, Windows PowerShell treats the two periods as the C: drive, so the command retrieves all the items in the C:\Program Files directory. A path beginning with a slash identifies a path from the root of the current drive. For example, if your current working location is C:\Program Files\Windows PowerShell, the root of your drive is C. Therefore, the following command lists all items in the C:\Windows directory: Get-ChildItem \windows If you do not specify a path beginning with a drive name, slash, or period when supplying the name of a container or item, the container or item is assumed to be located in the current working location. For example, if your current working location is C:\Windows, the following command returns all the items in the C:\Windows\System directory: Get-ChildItem system If you specify a file name rather than a directory name, Windows PowerShell returns details about that file (assuming that file is located in the current working location). SEE ALSO Set-Location about_Providers about_Path_Syntax about_logical_operators TOPIC about_Logical_Operators SHORT DESCRIPTION Describes the operators that connect statements in Windows PowerShell. LONG DESCRIPTION The Windows PowerShell logical operators connect expressions and statements, allowing you to use a single expression to test for multiple conditions. For example, the following statement uses the and operator and the or operator to connect three conditional statements. The statement is true only when the value of $a is greater than the value of $b, and either $a or $b is less than 20. ($a -gt $b) -and (($a -lt 20) -or ($b -lt 20)) Windows PowerShell supports the following logical operators. Operator Description Example -------- ------------------------------ ------------------------ -and Logical and. TRUE only when (1 -eq 1) -and (1 -eq 2) both statements are TRUE. False -or Logical or. TRUE when either (1 -eq 1) -or (1 -eq 2) or both statements are TRUE. True -xor Logical exclusive or. TRUE (1 -eq 1) -xor (2 -eq 2) only when one of the statements False is TRUE and the other is FALSE. -not Logical not. Negates the -not (1 -eq 1) statement that follows it. False (1 -eq 1) statement that follows it. False (Same as -not) Note: The previous examples also use the equal to comparison operator (-eq). For more information, see about_Comparison_Operators. The examples also use the Boolean values of integers. The integer 0 has a value of FALSE. All other integers have a value of TRUE. The syntax of the logical operators is as follows: <statement> {-AND | -OR | -XOR} <statement> { | -NOT} <statement> Statements that use the logical operators return Boolean (TRUE or FALSE) values. The Windows PowerShell logical operators evaluate only the statements required to determine the truth value of the statement. If the left operand in a statement that contains the and operator is FALSE, the right operand is not evaluated. If the left operand in a statement that contains the or statement is TRUE, the right operand is not evaluated. As a result, you can use these statements in the same way that you would use the If statement. SEE ALSO about_Operators Compare-Object about_Comparison_operators about_If about_methods TOPIC about_methods SHORT DESCRIPTION Describes how to use methods to perform actions on objects in Windows PowerShell. LONG DESCRIPTION Windows PowerShell uses structured collections of information, called objects, to represent the items in data stores or the state of the computer. For example, when you access a file in Windows PowerShell, you are not working with the actual file. Instead, you are working with a FileInfo object, a type of object that acts as the file's proxy. Most objects include methods. A method is a set of instructions that specify a particular action you can take with that object. For instance, the FileInfo object includes a method called CopyTo, which allows you to copy the file represented by the object. To view a list of methods and method definitions associated with a particular object, you can use the Get-Member cmdlet. However, to use the cmdlet, the object must already exist in some form, either as represented through a variable, as an object created when you specify a command as an argument to the Get-Member command, or as an object passed down a pipeline. For example, suppose that the $a variable has been assigned a string value, which means that the variable is associated with a string object. To view a list of the object's methods, enter the following command at the Windows PowerShell command prompt: Get-Member -inputobject $a -membertype method If you want to see which methods and method definitions are associated with an object that is passed down the pipeline, you would use a Get-Member command within the pipeline, as shown in the following example: Get-ChildItem c:\final.txt | Get-Member -membertype method The most common way to invoke a method is to specify the method name after an object reference (such as a variable or expression). You must separate the object reference and the method with a period. Additionally, you must use parentheses immediately following the method name to enclose any arguments that should be passed to the method. If no arguments are being passed in a method signature, you must still use a set of empty parentheses. For example, the following command uses the GetType method to return the data type associated with the $a string object: $a.GetType() The GetType method will return the data type for any object, and a variable always represents an object. The type of object depends on the type of data stored within that variable. Every action you take in Windows PowerShell is associated with objects, whether you are declaring a variable or combining commands into a pipeline. As a result, methods can be used in a variety of situations. For example, you can use a method to take an action on a property value, as shown in the following command: (Get-ChildItem c:\final.txt).name.ToUpper() In this case, the object on which the ToUpper method is being invoked is the string object associated with the name property. (Note that the Final.txt file must exist on the root of the C: drive for this example to work.) The name property is actually a property of the FileInfo object returned by the Get-ChildItem command. This demonstrates not only the object-oriented nature of Windows PowerShell, but shows how methods can be called on any accessible object. You can achieve the same results as the last example by using a variable to store the Get-ChildItem command output, as shown in the following example: $a = (Get-ChildItem c:\final.txt).name $a.ToUpper() The command again uses the ToUpper method of the string object associated with the variable, which contains the file name returned by the Get-ChildItem command. In some cases, a method requires an argument to direct the action of that method. For example, the FileInfo object includes the MoveTo method, which provides a way to move a file from one location to another. The method requires an argument that specifies the target location for the file. The following command demonstrates how to include that argument: (Get-ChildItem c:\final.txt).MoveTo("c:\techdocs\final.txt") The Get-ChildItem command returns a FileInfo object for the Final.txt file and then uses the MoveTo method of that object to initiate the action and to specify the file's new location. To determine the arguments associated with a method, review the corresponding method definition. A method definition contains one or more method signatures (also known as overloads in the Microsoft .NET Framework). A method signature contains the name of a method and zero or more parameters that you must supply when you call the method. Each method signature is separated from the prior signature with a comma in the Get-Member cmdlet display. For example, the CopyTo method of the FileInfo class contains the following two method signatures: 1. CopyTo(String destFileName) 2. CopyTo(String destFileName, Boolean overwrite) The first method signature takes the destination file name (including the path) in which to copy the source file. In the following example, the first CopyTo method is used to copy Final.txt to the C:\Bin directory: (Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt") If the file already exists in the destination location, the CopyTo method fails, and Windows PowerShell reports the following error: Exception calling "CopyTo" with "1" argument(s): "The file 'c:\bin\final.txt' already exists.". In the second method signature, you pass the destination file name just as you did in the first case, but you also pass a Boolean value to specify whether you want an existing file of the same name in the destination location to be overwritten, as the following example shows: (Get-ChildItem c:\final.txt).CopyTo("c:\bin\final.txt", $true) When you pass the Boolean value, you must use the $True variable, which is created automatically by Windows PowerShell. The $True variable contains the "true" Boolean value. (As you would expect, the $False variable contains the "false" Boolean value.) SEE ALSO about_Objects Get-Member about_modules TOPIC about_Modules SHORT DESCRIPTION Explains how to install, import, and use Windows PowerShell modules. LONG DESCRIPTION A module is a package that contains Windows PowerShell commands, such as cmdlets, providers, functions, variables, and aliases. People who write commands can use modules to organize their commands and share them with others. People who receive modules can add the commands in the modules to their Windows PowerShell sessions and use them just like the built-in commands. This topic explains how to use Windows PowerShell modules. For information about how to write Windows PowerShell modules, see "Writing a Windows PowerShell Module" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=144916. HOW TO USE A MODULE To use a module, perform the following tasks: 1. Install the module. (This is often done for you.) 2. Import the module into your Windows PowerShell session. 3. Find the commands that the module added. 4. Use the commands that the module added. This topic explains how to perform these tasks. It also includes other useful information about managing modules. HOW TO INSTALL A MODULE If you receive a module as a folder with files in it, you need to install it on your computer before you can import it into Windows PowerShell. Most modules are installed for you. Windows PowerShell comes with several pre-installed modules. In Windows Server 2008 R2, the Add Features Wizard in Server Manager automatically installs the feature modules that you select. Many other modules come in an installer or Setup program that installs the module. To install a module folder: 1. Create a Modules directory for the current user if one does not exist. To create a Modules directory, type: new-item -type directory -path $home\Documents\WindowsPowerShell \Modules 2. Copy the entire module folder into the Modules directory. You can use any method to copy the folder, including Windows Explorer and Cmd.exe, as well as Windows PowerShell. In Windows PowerShell use the Copy-Item cmdlet. For example, to copy the MyModule folder from C:\ps-test\MyModule to the Modules directory, t ype: copy-item -path c:\ps-test\MyModule -dest $home\Documents\Window sPowerShell\Modules You can install a module in any location, but installing your modules in a default module location makes them easier to manage. For more information a bout the default module locations, see the "Module Locations and PSModulePath" s ection. HOW TO FIND INSTALLED MODULEs When a module is installed, you can import it into your Windows PowerShell session. To find modules that are installed in a default module location, at the Windows PowerShell prompt, type: get-module -listAvailable To find the modules that have already been imported into your session, at the Windows PowerShell prompt, type: get-module For more information about the Get-Module cmdlet, see Get-Module. HOW TO IMPORT A MODULE To use the commands in a module, import the module into a Windows PowerShell session. To import modules from a default module location into the current session, use the following command format. import-module <module-name> For example, the following command imports the BitsTransfer module into the current session. import-module BitsTransfer To import a module that is not in a default module location, use the fully qualified path to the module folder in the command. For example, to add the TestCmdlets module in the C:\ps-test directory to your session, type: import-module c:\ps-test\TestCmdlets For more information about adding modules to your session, see Import-Module. HOW TO IMPORT ALL MODULES INTO YOUR WINDOWS POWERSHELL SESSION In Windows 7 and Windows Server 2008 R2, the "Import all modules" task opens a Windows PowerShell session that includes all the available Windows PowerShell modules and snap-ins. To start a Windows PowerShell session with all the available Windows PowerShell modules and snap-ins, use the following procedure. -- Right-click the Windows PowerShell icon in the taskbar, and then click "Import all modules". Note: In Windows Server 2008 R2, the Windows PowerShell icon is pinned to the taskbar by default. However, you must start Windows PowerShell one time to make the "Import all modules" task appear. In other versions of Windows, to import all the available modules into your session, at the Windows PowerShell prompt, type: get-module -listAvailable | import-module HOW TO FIND THE COMMANDS IN A MODULE After you import a module into your Windows PowerShell session, you can use the commands in the module. To find the commands that a module added, at the Windows PowerShell prompt, type: get-command -module <module-name> For example, to find the commands that the BitsTransfer module adds, type: get-command -module BitsTransfer For more information about the Get-Command cmdlet, see Get-Command. HOW TO FIND HELP FOR THE COMMANDS IN A MODULE If the module contains Help topics for the commands that it exports, the Get-Help cmdlet will display the Help topics. Use the same command format that you would use for any Help topic in Windows PowerShell. To find the Help topic for the commands in a module, at the Windows PowerShell prompt, type: get-help <command-name> For more detailed Help, type: get-help <command-name> -detailed For example, to find detailed Help for the Start-BitsTransfer cmdlet, type: get-help Start-BitsTransfer -detailed For more information about the Get-Help module, see Get-Help. HOW TO REMOVE A MODULE When you remove a module, the commands that the module added are deleted from the session. To remove a module from your session, use the following command format. remove-module <module-name> For example, the following command removes the BitsTransfer module from the current session. remove-module BitsTransfer Removing a module reverses the operation of importing a module. Removing a module does not uninstall the module. For more information about the Remove-Module cmdlet, see Remove-Module. HOW TO IMPORT A MODULE INTO EVERY SESSION The Import-Module command imports modules into your current Windows PowerShell session. This command affects only the current session. To import a module into every Windows PowerShell session that you start, add the Import-Module command to your Windows PowerShell profile. For more information about profiles, see about_Profiles. MODULE LOCATIONS AND PSMODULEPATH There are two default locations for Windows PowerShell modules, one for the system and one for the current user. System: $pshome\Modules (%windir%\System32\WindowsPowerShell\v1.0\Modules) Current user: $home\Documents\WindowsPowerShell\Modules (%UserProfile%\Documents\WindowsPowerShell\Modules) - or - $home\My Documents\WindowsPowerShell\Modules (%UserProfile%\My Documents\WindowsPowerShell\Module s) Note: In Windows Vista, Windows Server 2008, and later versions of Windows, to add or change files in the %Windir%\System32 director y, start Windows PowerShell with the "Run as administrator" option. You can change the default module locations on your system by changing the value of the PSModulePath environment variable ($env:psmodulepath). The PSModulePath environment variable is modeled on the Path environment variab le and has the same format. To view the default module locations, type: $env:psmodulepath To add a default module location, use the following command format. $env:psmodulepath = $env:psmodulepath + ";<path>" The semi-colon (;) in the command separates the new path from the path that precedes it in the list. For example, to add the "C:\ps-test\Modules" directory, type: $env:psmodulepath + ";c:\ps-test\Modules" When you add a path to PSModulePath, Get-Module and Import-Module commands include modules in that path. The value that you set affects only the current session. To make the change persistent, add the command to your Windows PowerShell profile or use the System item in Control Panel to change the value of the PSModulePath environment variable in the registry. For more information about the PSModulePath variable, see about_Environment_Variables. MODULES AND NAME CONFLICTS Name conflicts occur when more than one command in the session has the same name. Importing a module causes a name conflict when commands in the module have the same names as commands or items in the session. Name conflicts can result in commands being hidden or replaced. -- Hidden. A command is hidden when it is not the command that runs when you type the command name, but you can run it by using another method, such as by qualifying the command name with the name of the module or snap-in in which it originated. -- Replaced. A command is replaced when you cannot run it because it has been overwritten by a command with the same name. Even when you remove the module that caused the conflict, you cannot run a replaced command unless you restart the session. Import-Module might add commands that hide and replace commands in the current session. Also, commands in your session can hide commands that the module added. To prevent name conflicts, use the Prefix parameter of Import-Command to create unique names for the imported commands. You can also use the Alias, Cmdlet, Function, and Variable parameters of Import-Module to select only the commands that you want to import, and you can exclude commands that cause name conflicts in your session. Even if a command is hidden, you can run it by qualifying the command name with the name of the module or snap-in in which it originated. The Windows PowerShell command precedence rules determine which command runs when the session includes commands with the same name. For example, when a session includes a function and a cmdlet with the same name, Windows PowerShell runs the function by default. When the session includes commands of the same type with the same name, such as two cmdlets with the same name, by default, it runs the most recently added command. For more information, including an explanation of the precedence rules and instructions for running hidden commands, see about_Command_Precedence. MODULES AND SNAP-INS You can add commands to your session from modules and snap-ins. Modules can add all types of commands, including cmdlets, providers, and functions, and items, such as variables, aliases, and Windows PowerShell drives. Snap-ins can add only cmdlets and providers. In fact, although you can add functions, aliases, variables, and drives to your session by typing them or running a script that adds them, all the cmdlets and providers in your session come from a module or a snap-in. Before removing a module or snap-in from your session, use the following commands to determine which commands will be removed. To find the source of a cmdlet in your session, use the following command format: get-command <cmdlet-name> | format-list -property verb, noun, pssnapin, module For example, to find the source of the Get-Date cmdlet, type: get-command get-date | format-list -property verb, noun, pssnapin, modu le For more information about Windows PowerShell snap-ins, see about_PSSnapins . SEE ALSO about_Command_Precedence about_PSSnapins Get-Command Get-Help Get-Module Import-Module Remove-Module about_objects TOPIC about_Objects SHORT DESCRIPTION Provides essential information about objects in Windows PowerShell. LONG DESCRIPTION Every action you take in Windows PowerShell occurs within the context of objects. As data moves from one command to the next, it moves as one or more identifiable objects. An object, then, is a collection of data that represents an item in a namespace. An object is made up of three types of data: the object's type, its methods, and its properties. The data about an object's type provides details about what kind of object it is. For example, an object that represents a file is a FileInfo object. An object's method is an action that you can perform on the item that the object represents. For instance, a FileInfo object includes a method that you can use to cause the file to be copied. That is, when you invoke the copy method of the object, the file that the object represents is copied. An object's property is information about the state of that object. For example, a FileInfo object includes the length property, which specifies the size of the file represented by the object. When working with objects, you can use their methods and properties in your commands to take specific actions and manipulate data. This is especially useful when you combine multiple commands into a single pipeline. When commands are combined in a pipeline, they pass information to each other as objects. When the first command runs, it sends one or more objects down the pipeline to the second command. The second command receives the objects from the first command, processes the objects, and then passes new or revised objects to the next command in the pipeline. This continues until all commands in the pipeline run. The following example demonstrates how objects are passed from one command to the next: Get-ChildItem c: | where {$_.PsIsContainer -eq $false} | Format-List The first command (Get-ChildItem c:) returns an object for each item in the root directory of the file system. Those objects are passed down the pipeline to the second command (where {$_.PsIsContainer -eq $false}). The second command uses the PsIsContainer property of the object to filter the data from the input objects so that no directories (containers) are returned. The command then passes the information as objects to the third command (Format-List), which displays the contents of each piped object in a list format. SEE ALSO about_Methods about_Properties about_Pipelines Get-Member about_operators TOPIC about_Operators SHORT DESCRIPTION Describes the operators that are supported by Windows PowerShell. LONG DESCRIPTION An operator is a language element that you can use in a command or expression. Windows PowerShell supports several types of operators to help you manipulate values. Arithmetic Operators Use arithmetic operators (+, -, *, /, %) to calculate values in a command or expression. With these operators, you can add, subtract, multiply, or divide values, and calculate the remainder (modulus) of a division operation. You can also use arithmetic operators with strings, arrays, and hash tables. The addition operator concatenates elements. The multiplication operator returns the specified number of copies of each element. For more information, see about_Arithmetic_Operators. Assignment Operators Use assignment operators (=, +=, -=, *=, /=, %=) to assign one or more values to variables, to change the values in a variable, and to append values to variables. You can also cast the variable as any Microsoft .NET Framework data type, such as string or DateTime, or Process variable. For more information, see about_Assignment_Operators. Comparison Operators Use comparison operators (-eq, -ne, -gt, -lt, -le, -ge) to compare values and test conditions. For example, you can compare two string values to determine whether they are equal. The comparison operators include the match operators (-match, -notmatch) to find patterns using regular expressions; the replace operator (-replace), which uses regular expressions to change input values; and the like operators (-like, -notlike), which find patterns using wildcard characters (*). They also include the bitwise operators (-bAND, -bOR, -bXOR, -bNOT) to manipulate the bit patterns in values. For more information, see about_Comparison_Operators Logical Operators Use logical operators (-and, -or, -xor, -not, ) to connect conditional statements into a single complex conditional. For example, you can use a logical -and operator to create an object filter with two different conditions. For more information, see about_Logical_Operators. Redirection Operators Use redirection operators (>, >>, 2>, 2>, and 2>&1) to send the output of a command or expression to a text file. The redirection operators work like the Out-File cmdlet (without parameters) but they also let you redirect error output to specified files. You can also use the Tee-Object cmdlet to redirect output. For more information, see about_Redirection. Split and Join Operators The -split and -join operators divide and combine substrings. The -split operator splits a string into substrings. The -join operator concatenates multiple strings into a single string. For more information, see about_Split and about_Join. Type Operators Use the type operators (-is, -isnot, -as) to find or change the .NET Framework type of an object. For more information, see about_Type_Operators. Unary Operators Use unary operators to increment or decrement variables or object properties and to set integers to positive or negative numbers. For example, to increment the variable $a from 9 to 10, you type $a++. Special Operators Use special operators to perform tasks that cannot be performed by the other types of operators. For example, special operators allow you to perform operations such as running commands and changing a value's data type. & Call operator Description: Runs a command, script, or script block. Because the call operator does not parse, it cannot interpret command parameters. The call operator, also known as the "invocation operator, indicates that the value it precedes is a command. This enables you to run commands stored in variables and represented by strings. Examples: & "new cmdlet" $c = "get-executionpolicy" & $c . Property dereference operator Description: Accesses the properties and methods of an object. Examples: $myString.length $myString.substring(1,3) . dot sourcing operator Description: Runs a script so that the items in the script are part of the calling scope. For more information, see about_Scope. Example: . c:\scripts.sample.ps1 Note: The dot (.) symbol is also used as the parent directory symbol, as in this example: .\sample.ps1 This command runs the sample.ps1 script, but not as part of the calling scope. :: Static member operator Description: Calls the static properties operator and methods of a .NET Framework class. To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet. Example: [datetime]::now .. Range operator Description: Represents the sequential integers in an integer array, given an upper and lower boundary. Examples: 1..10 10..1 foreach ($a in 1..$max) {write-host $a} -f Format operator Description: Formats strings by using the format method of string objects. Enter the format string on the left side of the operator and the objects to be formatted on the right side of the operator. Examples: C:\PS> "{0} {1,-10} {2:N}" -f C:\PS> 1,"hello",[math]::pi 1 hello 3.14 $( ) Subexpression operator Description: Returns the result of one or more statements. For a single result, returns a scalar. For multiple results, returns an array. Examples: $($x * 23) $(Get-WMIObject win32_Directory) @( ) Array subexpression operator Description: Returns the result of one or more statements as an array. If there is only one item, the array has only one member. Example: @(Get-WMIObject win32_logicalDisk) , operator Description: As a binary operator, the comma creates an array. As a unary operator, the comma creates an array with one member. Place the comma before the member. Examples: $myArray = 1,2,3 $SingleArray = ,1 SEE ALSO about_Arithmetic_Operators about_Assignment_Operators about_Comparison_Operators about_Logical_Operators about_Type_Operators about_Split about_Join about_Redirection about_parameters TOPIC about_Parameters SHORT DESCRIPTION Describes how to work with cmdlet parameters in Windows PowerShell. LONG DESCRIPTION Most Windows PowerShell cmdlets and functions rely on parameters to allow users to select options or provide input. The parameters follow the cmdlet or function name and typically have the following form: -<parameter_name> <parameter_value> The name of the parameter is preceded by a hyphen (-), which signals to Windows PowerShell that the word following the hyphen is a parameter and not a value being passed to the cmdlet or function. Not all parameters require a value, and not all parameter names must be specified. In some cases, the parameter name is implied and does not need to be included in the command. The type of parameters and the requirements for those parameters vary by cmdlet and by function from cmdlet to cmdlet. To find information about the parameters of a cmdlet, use the Get-Help cmdlet. For example, to find information about the parameters of the Get-ChildItem cmdlet, type: get-help get-childitem To find information about the parameters of a function, review the parameter definitions. Parameters are defined either after the function name or inside the body of the function, using the Param keyword. For more information, see about_Functions. Some functions also contain comment-based Help about parameters. Use the Get-Help cmdlet with these functions. For more information, see the help topic for Get-Help and about_Comment_Based_Help. The Get-Help Cmdlet returns various details about the cmdlet or function, including a description of the cmdlet or function, the command syntax, information about the parameters, and examples showing how to use the cmdlet or function. You can also use the Parameter parameter of the Get-Help cmdlet or function to find information about a particular parameter. Or, you can use the wildcard character (*) with the Parameter parameter to find information about all the parameters of the cmdlet or function. For example, the following command gets information about all the parameters of the Get-Member cmdlet or function: get-help get-member -parameter * This information includes the details you need to know to use the parameter. For example, the Help topic for the Get-ChildItem cmdlet includes the following details about its Path parameter: -path <string[]> Specifies a path of one or more locations. Wildcard characters are permitted. The default location is the current directory (.). Required? false Position? 1 Default value Current directory Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true The parameter information includes the parameter syntax, a description of the parameter, and the parameter attributes. The following sections describe the parameter attributes. Parameter Required? This setting indicates whether the parameter is mandatory, that is, whether all commands that use this cmdlet must include this parameter. When the value is "True" and the parameter is missing from the command, Windows PowerShell prompts you for a value for the parameter. Parameter Position? This setting indicates whether you can supply a parameter's value without preceding it with the parameter name. If set to "0" or "named," a parameter name is required. This type of parameter is referred to as a named parameter. A named parameter can be listed in any position after the cmdlet name. If the "Parameter position?" setting is set to an integer other than 0, the parameter name is not required. This type of parameter is referred to as a positional parameter, and the number indicates the position in which the parameter must appear in relation to other positional parameters. If you include the parameter name for a positional parameter, the parameter can be listed in any position after the cmdlet name. For example, the Get-ChildItem cmdlet has Path and Exclude parameters. The "Parameter position?" setting for Path is 1, which means that it is a positional parameter. The "Parameter position?" setting for Exclude is 0, which means that it is a named parameter. This means that Path does not require the parameter name, but its parameter value must be the first or only unnamed parameter value in the command. However, because the Exclude parameter is a named parameter, you can place it in any position in the command. As a result of the "Parameter position?" settings for these two parameters, you can use any of the following commands: Get-ChildItem -path c:\techdocs -exclude *.ppt Get-ChildItem c:\techdocs -exclude *.ppt Get-ChildItem -exclude *.ppt -path c:\techdocs Get-ChildItem -exclude *.ppt c:\techdocs If you were to include another positional parameter without including the parameter name, that parameter would have to be placed in the order specified by the "Parameter position?" setting. Parameter Type This setting specifies the Microsoft .NET Framework type of the parameter value. For example, if the type is Int32, the parameter value must be an integer. If the type is string, the parameter value must be a character string. If the string contains spaces, the value must be enclosed in quotation marks, or the spaces must be preceded by the escape character (`). Default Value This setting specifies the value that the parameter will assume if no other value is provided. For example, the default value of the Path parameter is often the current directory. Required parameters never have a default value. For many optional parameters, there is no default because the parameter has no effect if it is not used. Accepts Multiple Values? This setting indicates whether a parameter accepts multiple parameter values. When a parameter accepts multiple values, you can type a comma-separated list as the value of the parameter in the command, or save a comma-separated list (an array) in a variable, and then specify the variable as the parameter value. For example, the ServiceName parameter of the Get-Service cmdlet accepts multiple values. The following commands are both valid: get-service -servicename winrm, netlogon $s = "winrm", "netlogon" get-service -servicename $s Accepts Pipeline Input? This setting indicates whether you can use the pipeline operator (|) to send a value to the parameter. Value Description ----- ----------- False Indicates that you cannot pipe a value to the parameter. True (by Value) Indicates that you can pipe any value to the parameter, just so the value has the .NET Framework type specified for the parameter or the value can be converted to the specified .NET Framework type. When a parameter is "True (by Value)", Windows PowerShell tries to associate any piped values with that parameter before it tries other methods to interpret the command. True (by Property Name) Indicates that you can pipe a value to the parameter, but the .NET Framework type of the parameter must include a property with the same name as the parameter. For example, you can pipe a value to a Name parameter only when the value has a property called "Name". Accepts Wildcard Characters? This setting indicates whether the parameter's value can contain wildcard characters so that the parameter value can be matched to more than one existing item in the target container. Common Parameters Common parameters are parameters that you can use with any cmdlet. For more information, about common parameters, type: help about_commonparameters SEE ALSO about_Command_syntax about_Comment_Based_Help about_Functions_Advanced about_Pipelines about_Wildcards about_Parsing TOPIC about_parsing SHORT DESCRIPTION Describes how Windows PowerShell parses commands. LONG DESCRIPTION When you enter a command at the command prompt, Windows PowerShell breaks the command text into a series of segments called tokens and then determines how to interpret each one. For example, Windows PowerShell breaks the following command into two tokens, "Write-Host" and "book", and interprets each token separately: Write-Host book When processing a command, the Windows PowerShell parser operates in expression mode or in argument mode: - In expression mode, character string values must be contained in quotation marks. Numbers not enclosed in quotation marks are treated as numerical values (rather than as a series of characters). - In argument mode, each value is treated as an expandable string unless it begins with one of the following special characters: dollar sign ($), at sign (@), single quotation mark ('), double quotation mark ("), or an opening parenthesis ((). If preceded by one of these characters, the value is treated as a value expression. The following table provides several examples of commands processed in expression mode and argument mode and the results produced by those commands. Example Mode Result ------------------ ---------- ---------------- 2+2 Expression 4 (integer) Write-Output 2+2 Argument "2+2" (string) Write-Output (2+2) Expression 4 (integer) $a = 2+2 Expression $a = 4 (integer) Write-Output $a Expression 4 (integer) Write-Output $a/H Argument "4/H" (string) Every token can be interpreted as some kind of object type, such as Boolean or string. Windows PowerShell attempts to determine the object type from the expression. The object type depends on the type of parameter a command expects and on whether Windows PowerShell knows how to convert the argument to the correct type. The following table shows several examples of the types assigned to values returned by the expressions. Example Mode Result ------------------ ---------- --------------- Write-Output 1" (string) Write-Output (1) expression False (Boolean) Write-Output (2) expression 2 (integer) SEE ALSO about_Command_Syntax about_Path_Syntax TOPIC about_Path_Syntax SHORT DESCRIPTION Describes the full and relative path name formats in Windows PowerShell. LONG DESCRIPTION All items in a data store accessible through a Windows PowerShell provider can be uniquely identified by their path names. A path name is a combination of the item name, the container and subcontainers in which the item is located, and the Windows PowerShell drive through which the containers are accessed. In Windows PowerShell, path names are divided into one of two types: fully qualified and relative. A fully qualified path name consists of all elements that make up a path. The following syntax shows the elements in a fully qualified path name: [<provider>::]<drive>:[\<container>[\ The <provider> placeholder refers to the Windows PowerShell provider through which you access the data store. For example, the FileSystem provider allows you to access the files and directories on your computer. This element of the syntax is optional and is never needed because the drive names are unique across all providers. The <drive> placeholder refers to the Windows PowerShell drive that is supported by a particular Windows PowerShell provider. In the case of the FileSystem provider, the Windows PowerShell drives map to the Windows drives that are configured on your system. For example, if your system includes an A: drive and a C: drive, the FileSystem provider creates the same drives in Windows PowerShell. After you have specified the drive, you must specify any containers and subcontainers that contain the item. The containers must be specified in the hierarchical order in which they exist in the data store. In other words, you must start with the parent container, then the child container in that parent container, and so on. In addition, each container must be preceded by a backslash. (Note that Windows PowerShell allows you to use forward slashes for compatibility with other powershells.) After the container and subcontainers have been specified, you must provide the item name, preceded by a backslash. For example, the fully qualified path name for the Shell.dll file in the C:\Windows\System32 directory is as follows: C:\Windows\System32\Shell.dll In this case, the drive through which the containers are accessed is the C: drive, the top-level container is Windows, the subcontainer is System32 (located within the Windows container), and the item is Shell.dll. In some situations, you do not need to specify a fully qualified path name and can instead use a relative path name. A relative path name is based on the current working location. Windows PowerShell allows you to identify an item based on its location relative to the current working location. You can specify relative path names by using special characters. The following table describes each of these characters and provides examples of relative path names and fully qualified path names. The examples in the table are based on the current working directory being set to C:\Windows. Symbol Description Relative path Fully qualified path ------ -------------------------- ---------------- -------------------- . Current working location .\System c:\Windows\System .. Parent of current working ..\Program Files c:\Program Files location \ Drive root of current \Program Files c:\Program Files working location [none] No special characters System c:\Windows\System When using a path name in a command, you enter that name in the same way whether you use a fully qualified path name or a relative one. For example, suppose that your current working directory is C:\Windows. The following Get-ChildItem command retrieves all items in the C:\Techdocs directory: Get-ChildItem \techdocs The backslash indicates that the drive root of the current working location should be used. Because the working directory is C:\Windows, the drive root is the C: drive. Because the techdocs directory is located off the root, you need to specify only the backslash. You can achieve the same results by using the following command: Get-ChildItem c:\techdocs Regardless of whether you use a fully qualified path name or a relative path name, a path name is important not only because it locates an item but also because it uniquely identifies the item even if that item shares the same name as another item in a different container. For instance, suppose that you have two files that are each named Results.txt. The first file is in a directory named C:\Techdocs\Jan, and the second file is in a directory named C:\Techdocs\Feb. The path name for the first file (C:\Techdocs\Jan\Results.txt) and the path name for the second file (C:\Techdocs\Feb\Results.txt) allow you to clearly distinguish between the two files. SEE ALSO about_Locations about_pipelines TOPIC about_pipelines SHORT DESCRIPTION Combining commands into pipelines in the Windows PowerShell LONG DESCRIPTION A pipeline is a series of commands connected by pipeline operators (|)(ASCII 124). Each pipeline operator sends the results of the preceding command to the next command. You can use pipelines to send the objects that are output by one command to be used as input to another command for processing. And you can send the output of that command to yet another command. The result is a very powerfu l command chain or "pipeline" that is comprised of a series of simple command s. For example, Command-1 | Command-2 | Command-3 In this example, the objects that Command-1 emits are sent to Command-2. Command-2 processes the objects and sends them to Command-3. Command-3 proc esses the objects and send them down the pipeline. Because there are no more comm ands in the pipeline, the results are displayed at the console. In a pipeline, the commands are processed from left to right in the order that they appear. The processing is handled as a single operation and output is displayed as it is generated. Here is a simple example. The following command gets the Notepad process and then stops it. get-process notepad | stop-process The first command uses the Get-Process cmdlet to get an object representing the Notepad process. It uses a pipeline operator (|) to send the process ob ject to the Stop-Process cmdlet, which stops the Notepad process. Notice that th e Stop-Process command does not have a Name or ID parameter to specify the pr ocess, because the specified process is submitted through the pipeline. Here is a practical example. This command pipeline gets the text files in t he current directory, selects only the files that are more than 10,000 bytes l ong, sorts them by length, and displays the name and length of each file in a ta ble. Get-ChildItem -path *.txt | Where-Object {$_.length -gt 10000} | Sort-Object -property Length | Format-Table -property name, length This pipeline is comprised of four commands in the specified order. The com mand is written horizontally, but we will show the process vertically in the fol lowing graphic. Get-ChildItem -path *.txt | | (FileInfo objects ) | ( .txt ) | V Where-Object {$_.length -gt 10000} | | (FileInfo objects ) | ( .txt ) | ( Length > 10000 ) | V Sort-Object -property Length | | (FileInfo objects ) | ( .txt ) | ( Length > 10000 ) | ( Sorted by length ) | V Format-Table -property name, length | | (FileInfo objects ) | ( .txt ) | ( Length > 10000 ) | ( Sorted by length ) | (Formatted in a table ) | V Name Length ---- ------ tmp1.txt 82920 tmp2.txt 114000 tmp3.txt 114000 USING PIPELINES The Windows PowerShell cmdlets were designed to be used in pipelines. For e xample, you can usually pipe the results of a Get cmdlet to an action cmdlet (such as a Set, Start, Stop, or Rename cmdlet) for the same noun. For example, you can pipe any service from the Get-Service cmdlet to the St art-Service or Stop-Service cmdlets (although disabled services cannot be restarted in this way). This command pipeline starts the WMI service on the computer: get-service wmi | start-service The cmdlets that get and set objects of the Windows PowerShell providers, s uch as the Item and ItemProperty cmdlets, are also designed to be used in pipelines. For example, you can pipe the results of a Get-Item or Get-ChildItem comman d in the Windows PowerShell registry provider to the New-ItemProperty cmdlet. This c ommand adds a new registry entry, NoOfEmployees, with a value of 8124, to the MyCompany registry key. get-item -path HKLM:\Software\MyCompany | new-Itemproperty -name NoOfEmp loyees -value 8124 Many of the utility cmdlets, such as Get-Member, Where-Object, Sort-Object, Group-Object, and Measure-Object are used almost exclusively in pipelines. You can pipe a ny objects to these cmdlets. For example, you can pipe all of the processes on the computer to the Sort- Object command and have them sorted by the number of handles in the process. get-process | sort-object -property handles Also, you can pipe any objects to the formatting cmdlets, such as Format-Li st and Format-Table, the Export cmdlets, such as Export-Clixml and Export-CSV, and the Out cmdlets, such as Out-Printer. For example, you can pipe the Winlogon process to the Format-List cmdlet to display all of the properties of the process in a list. get-process winlogon | format-list -property * With a bit of practice, you'll find that combining simple commands into pip elines saves time and typing, and makes your scripting more efficient. HOW PIPELINES WORK When you "pipe" objects, that is send the objects in the output of one com mand to another command, Windows Powershell tries to associate the piped objects with one of the parameters of the receiving cmdlet. To do so, the Windows Powershell "parameter binding" component, which asso ciates input objects with cmdlet parameters, tries to find a parameter that meets the following criteria: -- The parameter must accept input from a pipeline (not all do) -- The parameter must accept the type of object being sent or a type that the object can be converted to. -- The parameter must not already be used in the command. For example, the Start-Service cmdlet has many parameters, but only two of them, Name and InputObject accept pipeline input. The Name parameter takes strings and the InputObjec t parameter takes service objects. Therefore, you can pipe strings and service objects (and objects with properties that can be converted to string and service objects) to Start-Service. If the parameter binding component of Windows PowerShell cannot associate the piped objects with a parameter of the receiving cmdlet, the command fails and Windows Po werShell prompts you for the missing parameter values. You cannot force the parameter binding component to associate the piped ob jects with a particular parameter -- you cannot even suggest a parameter. Instead, the logic of th e component manages the piping as efficiently as possible. ONE-AT-A-TIME PROCESSING Piping objects to a command is much like using a parameter of the command to submit the objects. For example, piping objects representing the services on the computer to a Format-Table command, such as: get-service | format-table -property name, dependentservices is much like saving the service objects in a variable and using the InputO bject parameter of Format-Table to submit the service object. $services = get-service format-table -inputobject $services -property name, dependent services or imbedding the command in the parameter value format-table -inputobject (get-service wmi) -property name, d ependentservices However, there is an important difference. When you pipe multiple objects to a command, Windows PowerShell sends the objects to the command one at a time. When yo u use a command parameter, the objects are sent as a single array object. This seemingly technical difference can have interesting, and sometimes us eful, consequences. For example, if you pipe multiple process objects from the Get-Process cmd let to the Get-Member cmdlet, Windows PowerShell sends each process object, one at a time, to Get-Member. Get-Member displays the .NET class (type) of the process objects, and thei r properties and methods. (Get-Member eliminates duplicates, so if the objects are all of the same t ype, it displays only one object type.) In this case, Get-Member displays the properties and methods of each proce ss object, that is, a System.Diagnostics.Process object. get-process | get-member TypeName: System.Diagnostics.Process Name MemberType Definition ---- ---------- ---------- Handles AliasProperty Handles = Handle count Name AliasProperty Name = ProcessNa me NPM AliasProperty NPM = NonpagedSy stemMemorySize ... However, if you use the InputObject parameter of Get-Member, then Get-Mem ber receives an array of System.Diagnostics.Process objects as a single unit, and it disp lays the properties of an array of objects. (Note the array symbol ([]) after the System.Obje ct type name.) get-member -inputobject (get-process) TypeName: System.Object[] Name MemberType Definition ---- ---------- ---------- Count AliasProperty Count = Length Address Method System.Object& Address(Int32 ) Clone Method System.Object Clone() ... This result might not be what you intended, but after you understand it, y ou can use it. For example, an array of process objects has a Count property that you can use to count the number of processes on the computer. (get-process).count This distinction can be important, so remember that when you pipe objects to a cmdlet, they are delivered one at a time. ACCEPTS PIPELINE INPUT In order to receive objects in a pipeline, the receiving cmdlet must have a parameter that accepts pipeline input. You can use a Get-Help command with the Full o r Parameter parameters to determine which, if any, of a cmdlet's parameters accepts pip eline input. In the Get-Help default display, the "Accepts pipeline input" item appears in a table of parameter attributes. This table is displayed only when you use the Full or Parameter parameters of the Get-Help cmdlet. For example, to determine which of the parameters of the Start-Service cmdl et accepts pipeline input, type: get-help start-service -full get-help start-service -parameter * For example, the help for the Start-Service cmdlet shows that the Name and InputObject parameters accept pipeline input ("true"). All other parameters have a valu e of "false" in the "Accept pipeline input?" row. -name <string[]> Specifies the service names for the service to be started. The parameter name is optional. You can use "-Name" or its alias, "-ServiceName", or you can omit the parameter name. Required? true Position? 1 Default value --> Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true -inputObject <ServiceController[]> Specifies ServiceController objects representing the services to be started. Enter a variable that contains the objects or type a command or expression that gets the objects. Required? false Position? named Default value --> Accept pipeline input? true (ByValue) Accept wildcard characters? false This means that you can send objects (PsObjects) through the pipeline to t he Where-Object cmdlet and Windows PowerShell will associate the object with the InputObject parameter. METHODS OF ACCEPTING PIPELINE INPUT Cmdlets parameters can accept pipeline input in one of two different ways: -- ByValue: Parameters that accept input "by value" can accept piped objec ts that have the same .NET type as their parameter value or objects that c an be converted to that type. For example, the Name parameter of Start-Service accepts pipeline input by value. It can accept string objects or objects that can be converted to strings. -- ByPropertyName: Parameters that accept input "by property name" can acc ept piped objects only when a property of the object has the same name as the par ameter. For example, the Name parameter of Start-Service can accept objects tha t have a Name property. (To list the properties of an object, pipe it to Get-Member.) Some parameters can accept objects by value or by property name. These par ameters are designed to take input from the pipeline easily. INVESTIGATING PIPELINE ERRORS If a command fails because of a pipeline error, you can investigate the fa ilure and rewrite the command. For example, the following command tries to move a registry entry from one registry key to another by using the Get-Item cmdlet to get the destinatio n path and then piping the path to the Move-ItemProperty cmdlet. Specifically, the command uses the Get-Item cmdlet to get the destination path. It uses a pipeline operator to send the result to the Move-ItemProperty cmdlet. Th e Move-ItemProperty command specifies the current path and name of the registry entry to be mo ved. get-item -path hklm:\software\mycompany\sales | move-itemproperty -path hklm:\software\mycompany\design -name product The command fails and Windows PowerShell displays the following error message: Move-ItemProperty : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeli ne input. At line:1 char:23 + $a | move-itemproperty < -path hklm:\software\mycompany\design - name product To investigate, use the Trace-Command cmdlet to trace the Parameter Binding component of Windows PowerShell. The following command traces the Parameter Binding comp onent while the command is processing. It uses the -pshost parameter to display the results at the console and the -filepath command to send them to the debug.txt file for later refe rence. trace-command -name parameterbinding -expression {get-item -path hklm: \software\mycompany\sales | move-itemproperty -path hklm:\software\mycompany\design -name prod uct} -pshost -filepath debug.txt The results of the trace are lengthy, but they show the values being bound to the Get-Item cmdlet and then the named values being bound to the Move-ItemProperty cmdlet. ... BIND NAMED cmd line args [Move-ItemProperty] BIND arg [hklm:\software\mycompany\design] to parameter [Path] ... BIND arg [product] to parameter [Name] .... BIND POSITIONAL cmd line args [Move-ItemProperty] ... Finally, it shows that the attempt to bind the path to the Destination para meter of Move-ItemProperty failed. ... BIND PIPELINE object to parameters: [Move-ItemProperty] PIPELINE object TYPE = [Microsoft.Win32.RegistryKey] RESTORING pipeline parameter's original values Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyN ame NO COERCION Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyNa me NO COERCION ... To investigate the failure, use the Get-Help cmdlet to view the attributes of the Destination parameter. The following command gets detailed information abo ut the Destination parameter. get-help move-itemproperty -parameter destination The results show that Destination takes pipeline input only "by property n ame". That is, the piped object must have a property named Destination. -destination <string> Specifies the path to the destination location. Required? true Position? 2 Default value Accept pipeline input? true (ByPropertyName) Accept wildcard characters? true To see the properties of the object being piped to the Move-ItemProperty c mdlet, pipe it to the Get-Member cmdlet. The following command pipes the results of the first part of the command to the Get-Member cmdlet. get-item -path hklm:\software\mycompany\sales | get-member The output shows that the item is a Microsoft.Win32.RegistryKey that does not have a Destination property. That explains why the command failed. To fix the command, we must specify the destination in the Move-ItemProper ty cmdlet. We can use a Get-ItemProperty command to get the path, but the name and destinati on must be specified in the Move-ItemProperty part of the command. get-item -path hklm:\software\mycompany\design | move-itemproperty -dest hklm:\software\mycompany\design -name prod uct To verify that the command worked, use a Get-ItemProperty command: get-itemproperty hklm:\software\mycompany\sales The results show that the Product registry entry was moved to the Sales ke y. PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\s oftware\mycompany\sales PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\s oftware\mycompany PSChildName : sales PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry Product : 18 SEE ALSO about_objects about_parameters about_command_syntax about_foreach 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 $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 64 $MaximumVariableCount 4096 $OFS (Space character (" ")) $OutputEncoding ASCIIEncoding object $ProgressPreference Continue $PSEmailServer (None) $PSSessionApplicationName WSMAN $PSSessionConfigurationName http://schemas.microsoft.com/powershel l/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 the environment variable s, see about_environment_variables. Variable -------- 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 window. To make them effective in all Windows PowerShell windows, 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 which cmdlet actions automatically request confirmation from the user before they are performed. When the $ConfirmPreference value (High, Medium, Low, None) is greater than or equal to the risk of the cmdlet action (High, Medium, Low, None), Windows PowerShell automatically requests confirmation from the user before performing the action. You can use the Confirm parameter of a cmdlet to override the preference for a specific command. Valid values: None: No cmdlet actions are automatically confirmed. Users must use the Confirm parameter to request confirmation of specific commands. Low: Cmdlet actions with a low, medium, or high risk are automatically confirmed. To suppress confirmation of a specific command, use -Confirm:$false. Medium: Cmdlet actions with a medium or high risk are automatically confirmed. To enable confirmation of a specific command, use -confirm. To suppress confirmation of a specific command, use -confirm:$false. High: Cmdlet actions with a high risk are automatically (default) confirmed. To enable confirmation of a specific command, use -confirm. To suppress confirmation for a specific command, use -confirm:$false. DETAILED EXPLANATION When a cmdlet action significantly affects the system, such as by deleting data or by using a significant amount of system resources, Windows PowerShell can automatically prompt you for confirmation before performing the action. For example, PS> remove-item pref2.txt Confirm Are you sure you want to perform this action? Performing operation "Remove File" on Target "C:\pref2.txt". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] He lp (default is "Y"): The estimate of the risk is part of the cmdlet known as its "ConfirmImpact". You cannot change it. Cmdlet that might pose a risk to the system have a Confirm parameter that you can use to request or suppress confirmation for a specific command. Because most cmdlets use the default risk value 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 cmdlet actions. Since most actions are of medium risk, they are not automatically confirmed, although you can use the Confirm parameter of the cmdlet to request confirmation of a specific command. 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 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"): This example shows the effect of changing the value of $ConfirmPrefernce to Medium. Because most cmdlet actions are medium-risk, they are automatically confirmed, and you have to use the Confirm parameter with a value of $false to suppress the confirmation prompt for a specific command. 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. 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 is requested. displayed and confirmation Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (defau lt 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 "Deb ugPreference" 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 (defau lt 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. For more information, type: "get-help about_commonparameters". 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 executing. SilentlyContinue: No effect. The error message is not (Default) displayed and execution continues without interruption. 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, type "get-help about_commonparameters". 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 ex ist. 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 (defau lt is "Y"): y Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not ex ist. 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 (defau lt 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}):[{Activ ity}], {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 ex ist. 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], ItemNotFoundExc eption 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: Cann ot find path 'C:\nofile.txt' because it does not exist. at System.Management.Automation.SessionStateInternal.Get ChildItems(String path, Boolean recurse, CmdletProviderContext context) at System.Management.Automation.ChildItemCmdletProviderI ntrinsics.Get(String path, Boolean recurse, CmdletProviderContext context) at Microsoft.PowerShell.Commands.GetChildItemCommand.Pro cessRecord() TargetObject : C:\nofile.txt CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-Chi ldItem], ItemNotFoundException FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetC hildItemCommand 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, Audi oSrv...} 41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Sm art...} # 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, CcmEx ec... 41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiS vc... 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, Ccm Exec, Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver, Dnscach e, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc, HidServ, IIS ADMIN, InoRPC, InoRT, InoTask, lanmanserver, lanmanworkstatio n, LmHosts, MDM, Netlogon, Netman, Nla, NtLmSsp, PlugPlay, PolicyA gent, ProtectedStorage, RasMan, RemoteRegistry, RpcSs, SamSs , Schedule, seclogon, SENS, SharedAccess, ShellHWDetection, SMT PS VC, Spooler, srservice, SSDPSRV, stisvc, TapiSrv, TermService, Them es, TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc, wua userv, WZCSVC, zzInterix} 41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, C iSvc, ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp, Cr onService, dmadmin, FastUserSwitchingCompatibility, HTTPFilter, I mapiService, Mapsvc, Messenger, mnmsrvc, MSDTC, MSIServer, msvsmon8 0, NetDDE, NetDDEdsdm, NtmsSvc, NVSvc, ose, RasAuto, RDSessMgr, R emoteAccess, RpcLocator, RSVP, SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS, WmdmPmSN, Wmi, WmiApSrv, xmlprov} $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 initi alization and processing. Default = $false (not logged). $LogCommandLifecycleEvent: Logs the starting and stopping of commands and command pipeline s and security exceptions in command discovery. Default = $false (not logged). $LogEngineHealthEvent: Logs errors and failures of sessions. Defaul t = $true (logged). $LogEngineLifecycleEvent: Logs the opening and closing of sessions. Default = $true (logged). $LogProviderHealthEvent: Logs provider errors, such as read and wri te errors, lookup errors, and invocation errors. Default = $true (logged). $LogProviderLifecycleEvent: Logs adding and removing of Windows Pow erShell providers. Default = $true (logged). (For information about Windows PowerS hell providers, type: "get-help about_provider". To enable a Log*Event, type the variable with a value of $true, for exa mple: $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 P owerShell 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: 64 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, type: "get-help about_history". $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 used by Windows PowerShell 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 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 <Unicode-characters> # 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 <Unicode-characters> test.txt: <Unicode-characters> # 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 executin g. 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. $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. You can also set custom options for a particular remote session by using the SessionOption parameter in cmdlets that create a session, such as New-PSSession, Enter-PSSession, and Invoke-Command. The SessionOption parameter value takes precedence over the system defaults and the defaults that are set in this variable. 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. To create the $PSSessionOption preference variable, use the New-PSSessionOption cmdlet. 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. 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 $VerbosePreferenc e 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 d efault. 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 "V erbosePreference" 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 (defaul t 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 sil entlycontinue 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 sto p # 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 variabl e "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 (de fault is "Y"): y PS> PS> Write-Warning "This action can delete data." -warningaction sile ntlycontinue PS> # Use the WarningAction parameter to cha nge 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 inqu ire WARNING: This action can delete data. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (de fault is "Y"): # Use the WarningAction parameter to cha nge 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.tx t". # 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 ProcessNa me ------- ------ ----- ----- ----- ------ -- --------- -- 234 8 6324 15060 154 0.36 2312 WINWORD PS> stop-process -name winword What if: Performing operation "Stop-Process" on Target "WINWORD (231 2)". # 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 about_profiles TOPIC about_Profiles SHORT DESCRIPTION Describes how to create and use a Windows PowerShell profile. LONG DESCRIPTION You can create a Windows PowerShell profile to customize your environment and to add session-specific elements to every Windows PowerShell session that you start. A Windows PowerShell profile is a script that runs when Windows PowerShell starts. You can use the profile as a logon script to customize the environment. You can add commands, aliases, functions, variables, snap-ins, modules, and Windows PowerShell drives. You can also add other session-specific elements to your profile so they are available in every session without having to import or re-create them. Windows PowerShell supports several profiles for users and host programs. However, it does not create the profiles for you. This topic describes the profiles, and it describes how to create and maintain profiles on your computer. It explains how to use the NoProfile parameter of the Windows PowerShell console (PowerShell.exe) to start Windows PowerShell without any profiles. And, it explains the effect of the Windows PowerShell execution policy on profiles. THE PROFILE FILES Windows PowerShell supports several profile files. Also, Windows PowerShell host programs can support their own host-specific profiles. For example, the Windows PowerShell console supports the following basic profile files. The profiles are listed in precedence order. The first profile has the highest precedence. Description Path ----------- ---- Current User, Current Host $Home\[My ]Documents\WindowsPowerShell\Profi le.ps1 Current User, All Hosts $Home\[My ]Documents\Profile.ps1 All Users, Current Host $PsHome\Microsoft.PowerShell_profile.ps1 All Users, All Hosts $PsHome\Profile.ps1 The profile paths include the following variables: - The $PsHome variable, which stores the installation directory for Windows PowerShell. - The $Home variable, which stores the current user's home directory. In addition, other programs that host Windows PowerShell can support their own profiles. For example, Windows PowerShell Integrated Scripting Environment (ISE) supports the following host-specific profiles. Description Path ----------- ----- Current user, Current Host $Home\[My ]Documents\WindowsPowerShell\Micro soft.PowerShellISE_profile.ps1 All users, Current Host $PsHome\Microsoft.PowerShellISE_profile.ps1 In Windows PowerShell Help, the "CurrentUser, Current Host" profile is the profile most often referred to as "your Windows PowerShell profile". THE $PROFILE VARIABLE The $Profile automatic variable stores the paths to the Windows PowerShell profiles that are available in the current session. To view a profile path, display the value of the $Profile variable. You can also use the $Profile variable in a command to represent a path. The $Profile variable stores the path to the "Current User, Current Host" profile. The other profiles are saved in note properties of the $profile variable. For example, the $Profile variable has the following values in the Windows PowerShell console. Name Description ----------- ----------- $Profile Current User,Current Host $Profile.CurrentUserCurrentHost Current User,Current Host $Profile.CurrentUserAllHosts Current User,All Hosts $Profile.AllUsersCurrentHost All Users, Current Host $Profile.AllUsersAllHosts All Users, All Hosts Because the values of the $Profile variable change for each user and in each host application, ensure that you display the values of the profile variables in each Windows PowerShell host application that you use. To see the current values of the $Profile variable, type: $profile | get-member -type noteproperty You can use the $Profile variable in many commands. For example, the following command opens the "Current User, Current Host" profile in Notepad: notepad $profile The following command determines whether an "All Users, All Hosts" profile has been created on the local computer: test-path $profile.AllUsersAllHosts HOW TO CREATE A PROFILE To create a Windows PowerShell profile, use the following command format: if ((test-path <profile-name>)) {new-item -type file -path <profile-name> -force} For example, to create a profile for the current user in the current Windows PowerShell host application, use the following command: if ((test-path $profile)) {new-item -type file -path $profile -force} In this command, the If statement prevents you from overwriting an existing profile. Replace the value of the <profile-path> placeholder with the path to the profile file that you want to create. Note: To create "All Users" profiles in Windows Vista and later versions of Windows, start Windows PowerShell with the "Run as administrator" option. HOW TO EDIT A PROFILE You can open any Windows PowerShell profile in a text editor, such as Notepad. To open the profile of the current user in the current Windows PowerShell host application in Notepad, type: notepad $profile To open other profiles, specify the profile name. For example, to open the profile for all the users of all the host applications, type: notepad $profile.AllUsersAllHosts To apply the changes, save the profile file, and then restart Windows PowerShell. HOW TO CHOOSE A PROFILE If you use multiple host applications, put the items that you use in all the host applications into your $Profile.CurrentUserAllHosts profile. Put items that are specific to a host application, such as a command that sets the background color for a host application, in a profile that is specific to that host application. If you are an administrator who is customizing Windows PowerShell for many users, follow these guidelines: -- Store the common items in the $profile.AllUsersAllHosts profile. -- Store items that are specific to a host application in $profile.AllUsersCurrentHost profiles that are specific to the host application. -- Store items for particular users in the user-specific profiles. Be sure to check the host application documentation for any special implementation of Windows PowerShell profiles. HOW TO USE A PROFILE Many of the items that you create in Windows PowerShell and most commands that you run affect only the current session. When you end the session, the items are deleted. The session-specific commands and items include variables, preference variables, aliases, functions, commands (except for Set-ExecutionPolicy), and Windows PowerShell snap-ins that you add to the session. To save these items and make them available in all future sessions, add them to a Windows PowerShell profile. Another common use for profiles is to save frequently-used functions, aliases, and variables. When you save the items in a profile, you can use them in any applicable session without re-creating them. HOW TO START A PROFILE When you open the profile file, it is blank. However, you can fill it with the variables, aliases, and commands that you use frequently. Here are a few suggestions to get you started. -- Add commands that make it easy to open your profile. This is especially useful if you use a profile other than the "Current User, Current Host" profile. For example, add the following command: function pro {notepad $profile.CurrentUserAllHosts} -- Add a function that opens Windows PowerShell Help in a compiled HTML Help file (.chm). function Get-CHM { (invoke-item $env:windir\help\mui\0409\WindowsPowerShellHelp.chm ) } This function opens the English version of the .chm file. However, you can replace the language code (0409) to open other versions of the .chm file. -- Add a function that lists the aliases for any cmdlet. function Get-CmdletAlias ($cmdletname) { get-alias | Where {$_.definition -like "*$cmdletname*"} | ft Defi nition, Name -auto } -- Add an Add-PsSnapin command to add any Windows PowerShell snap-ins that you use. -- Customize your console. function Color-Console { $host.ui.rawui.backgroundcolor = "white" $host.ui.rawui.foregroundcolor = "black" $hosttime = (dir $pshome\powershell.exe).creationtime $Host.UI.RawUI.WindowTitle = "Windows PowerShell $hostversion ( $hosttime)" clear-host } Color-console -- Add a customized Windows PowerShell prompt that includes the computer name and the current path. function prompt { $env:computername + "\" + (get-location) + "> " } For more information about the Windows PowerShell prompt, see about_Prompts. THE NOPROFILE PARAMETER To start Windows Powershell without profiles, use the NoProfile parameter of PowerShell.exe, the program that starts Windows PowerShell. To begin, open a program that can start Windows PowerShell, such as Cmd.exe or Windows PowerShell itself. You can also use the Run dialog box in Windows. Type: powershell -noprofile For a complete list of the parameters of PowerShell.exe, type: powershell -? PROFILES AND EXECUTION POLICY The Windows PowerShell execution policy determines, in part, whether you can run scripts and load configuration files, including the profiles. The Restricted execution policy is the default. It prevents all scripts from running, including the profiles. If you use the Restricted policy, the profile does not run, and its contents are not applied. A Set-ExecutionPolicy command sets and changes your execution policy. It is one of the few commands that applies in all Windows PowerShell sessions because the value is saved in the registry. You do not have to set it when you open the console, and you do not have to store a Set-ExecutionPolicy command in your profile. PROFILES AND REMOTE SESSIONS Windows PowerShell profiles are not run automatically in remote sessions, so the commands that the profileS add are not present in the remote session . In addition, the $profile automatic variable is not populated in remote ses sions. To run a profile in a session, use the Invoke-Command cmdlet. For example, the following command runs the CurrentUserCurrentHost profile from the local computer in the session in $s. invoke-command -session $s -filepath $profile The following command runs the CurrentUserCurrentHost profile from the remo te computer in the session in $s. Because the $profile variable is not populat ed, the command uses the explicit path to the profile. invoke-command -session $s {invoke-expression "$home\Documents\WindowsP owerShell\Microsoft.PowerShell_profile.ps1"} After running this command, the commands that the profile adds to the sessi on are available in $s. SEE ALSO about_Automatic_Variables about_Functions about_Prompts about_Execution_Policies about_Signing about_Remote Set-ExecutionPolicy about_prompts TOPIC about_Prompts SHORT DESCRIPTION Describes the Prompt function and demonstrates how to create a custom Prompt function. LONG DESCRIPTION The Windows PowerShell command prompt indicates that Windows PowerShell is ready to run a command: PS C:\> The Windows PowerShell prompt is determined by the Prompt function. You can customize the prompt by creating your own Prompt function. Then, you can save this function in your Windows PowerShell profile. The Prompt Function The Prompt function determines the appearance of the Windows PowerShell prompt. Windows PowerShell comes with a built-in Prompt function, but you can override it by defining your own Prompt function. The Prompt function has the following syntax: function prompt { <function-body> } The Prompt function must return an object, typically a string. We recommend that it return a string or an object that is formatted as a string. The string should fit on an 80-character line. For example: PS C:\> function prompt {"Hello, World > "} Hello, World > Like all functions, the Prompt function is stored in the Function: drive. To display the code in the current Prompt function, type: (get-item function:prompt).definition This command uses the Get-Item cmdlet to display the Prompt item in the Function: drive. Then, it uses dot notation to display the value of the Definition property of the Prompt function. The Default Prompt The default Windows PowerShell prompt is: PS> This prompt appears only when the prompt function generates an error or when the prompt function does not return a string or object. PS C:\> function prompt {$null} PS> Because Windows PowerShell comes with a built-in prompt, you usually do not see the default prompt until you write your own prompt function. The Built-in Prompt Windows PowerShell includes a built-in prompt function that creates the familiar prompts. The built-in prompt function is: function prompt { $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' }) + 'PS ' + $(Get-Location) ` + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' } The function uses the Test-Path cmdlet to determine whether the $PSDebugContext automatic variable is populated. If $PSDebugContext is populated, you are in debugging mode, and "[DBG]" is added to the prompt, as follows: [DBG] PS C:\ps-test> If $PSDebugContext is not populated, the function adds "PS" to the prompt. And, the function uses the Get-Location cmdlet to get the current file system directory location. Then, it adds a right angle bracket (>). For example: PS C:\ps-test> If you are in a nested prompt, the function adds two angle brackets (>>) to the prompt. (You are in a nested prompt if the value of the $NestedPromptLevel automatic variable is greater than 1.) For example, when you are debugging in a nested prompt, the prompt resembles the following prompt: [DBG] PS C:\ps-test>>> The Enter-PSSession cmdlet prepends the name of the remote computer to the current Prompt function. When you use the Enter-PSSession cmdlet to start a session with a remote computer, the command prompt changes to include the name of the remote computer. For example: PS Hello, World> Enter-PSSession Server01 [Server01]: PS Hello, World> Other Windows PowerShell host applications and alternate shells might have their own custom command prompts. For more information about the $PSDebugContext and $NestedPromptLevel automatic variables, see about_Automatic_Variables. Customizing the Prompt To customize the prompt, write a new Prompt function. The function is not protected, so you can overwrite it. To write a prompt function, type the following: function prompt { } Then, between the curly braces, enter the commands or the string that creates your prompt. For example, the following prompt includes your computer name: function prompt {"PS [$env:COMPUTERNAME]> "} On the Server01 computer, the prompt resembles the following prompt: PS [Server01] > The following prompt function includes the current date and time: function prompt {"$(get-date)> "} The prompt resembles the following prompt: 01/01/2008 17:49:47> You can also modify the default Prompt function: function prompt { $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' }) + "$(get-date)" ` + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' } For example, the following modified Prompt function adds "[ADMIN]:" to the built-in Windows PowerShell prompt when Windows PowerShell is opened by using the "Run as administrator" option: function prompt { $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = [Security.Principal.WindowsPrincipal] $identity $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } elseif($principal.IsInRole([Security.Principal.WindowsBuiltInRole ] "Administrator")) { "[ADMIN]: " } else { '' }) + 'PS ' + $(Get-Location) + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' } When you start Windows PowerShell by using the "Run as administrator" option, a prompt that resembles the following prompt appears: [ADMIN]: PS C:\ps-test> The following Prompt function displays the history ID of the next command. To view the command history, use the Get-History cmdlet. function prompt { # The at sign creates an array in case only one history item exist s. $history = @(get-history) if($history.Count -gt 0) { $lastItem = $history[$history.Count - 1] $lastId = $lastItem.Id } $nextCommand = $lastId + 1 $currentDirectory = get-location "PS: $nextCommand $currentDirectory >" } The following prompt uses the Write-Host and Get-Random cmdlets to create a prompt that changes color randomly. Because Write-Host writes to the current host application but does not return an object, this function includes a Return statement. Without it, Windows PowerShell uses the default prompt, "PS>". function prompt { $color = get-random -min 1 -max 16 write-host ("PS " + $(get-location) +">") -nonewline -foregroundc olor $color return " " } Saving the Prompt Like any function, the Prompt function applies only in the current session. To save the Prompt function for future sessions, add it to your Windows PowerShell profiles. For more information about profiles, see about_Profiles. SEE ALSO Get-Location Enter-PSSession Get-History Get-Random Write-Host about_Profiles about_Functions about_Scopes about_Debuggers about_Automatic_Variables about_properties TOPIC about_Properties SHORT DESCRIPTION Describes how to use object properties in Windows PowerShell. LONG DESCRIPTION Windows PowerShell uses structured collections of information called objects to represent the items in data stores or the state of the computer. Typically, you work with object that are part of the Microsoft .NET Framework, but you can also create custom objects in Windows PowerShell. The association between an item and its object is very close. When you change an object, you change the item that it represents. For example, when you get a file in Windows PowerShell, you do not get the actual file. Instead, you get a FileInfo object that represents the file. When you change the FileInfo object, the file changes too. Most objects have properties. Properties are the data that is associated with an object. This data describes the object. For example, a FileInfo object has a property called Length that describes the size of the file that is represented by the object. Object Properties To list the properties of an object, use the Get-Member cmdlet. For example, to get the properties of a FileInfo object, use the Get-ChildItem cmdlet to get the FileInfo object that represents a file. Then, use a pipeline operator (|) to send the FileInfo object to Get-Member. The following command gets the PowerShell.exe file and sends it to Get-Member. The $Pshome automatic variable contains the path of the Windows PowerShell installation directory. get-childitem $pshome\powershell.exe | get-member The output of the command lists the members of the FileInfo object. Members include both properties and methods. When you work in Windows PowerShell, you have access to all the members of the objects. To get only the properties of an object and not the methods, use the MemberType parameter of the Get-Member cmdlet with a value of "property", as shown in the following example. get-childitem $pshome\powershell.exe | get-member -membertype property TypeName: System.IO.FileInfo Name MemberType Definition ---- ---------- ---------- Attributes Property System.IO.FileAttributes Attributes {get; set;} CreationTime Property System.DateTime CreationTime {get;set;} CreationTimeUtc Property System.DateTime CreationTimeUtc {get;set; } Directory Property System.IO.DirectoryInfo Directory {get;} DirectoryName Property System.String DirectoryName {get;} Exists Property System.Boolean Exists {get;} Extension Property System.String Extension {get;} FullName Property System.String FullName {get;} IsReadOnly Property System.Boolean IsReadOnly {get;set;} LastAccessTime Property System.DateTime LastAccessTime {get;set;} LastAccessTimeUtc Property System.DateTime LastAccessTimeUtc {get;se t;} LastWriteTime Property System.DateTime LastWriteTime {get;set;} LastWriteTimeUtc Property System.DateTime LastWriteTimeUtc {get;set Length Property System.Int64 Length {get;} Name Property System.String Name {get;} After you find the properties, you can use them in your Windows PowerShell commands. Property Values Although every object of a specific type has the same properties, the values of those properties describe the particular object. For example, every FileInfo object has a CreationTime property, but the value of that property differs for each file. The most common way to get the values of the properties of an object is to use the dot method. Type a reference to the object, such as a variable that contains the object, or a command that gets the object. Then, type a dot (.) followed by the property name. For example, the following command displays the value of the CreationTime property of the PowerShell.exe file. The Get-ChildItem command returns a FileInfo object that represents the PowerShell.exe file. The command is enclosed in parentheses to make sure that it is executed before any properties are accessed. The Get-ChildItem command is followed by a dot and the name of the CreationTime property, as follows: C:\PS> (Get-ChildItem $pshome\powershell.exe).creationtime Tuesday, March 18, 2008 12:07:52 AM You can also save an object in a variable and then get its properties by using the dot method, as shown in the following example: C:\PS> $a = Get-ChildItem $pshome\powershell.exe C:\PS> $a.CreationTime Tuesday, March 18, 2008 12:07:52 AM You can also use the Select-Object and Format-List cmdlets to display the property values of an object. Select-Object and Format-List each have a Property parameter. You can use the Property parameter to specify one or more properties and their values. Or, you can use the wildcard character (*) to represent all the properties. For example, the following command displays the values of all the properties of the PowerShell.exe file. C:\PS> Get-ChildItem $pshome\powershell.exe | Format-List -property * PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Windows\s ystem32\WindowsPowerShell\v1.0\powershell.exe PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Windows\s ystem32\WindowsPowerShell\v1.0 PSChildName : powershell.exe PSDrive : C PSProvider : Microsoft.PowerShell.Core\FileSystem PSIsContainer : False VersionInfo : File: C:\Windows\system32\WindowsPower Shell\v1.0\powershell.exe InternalName: POWERSHELL OriginalFilename: PowerShell.EXE.MUI File Version: 6.1.6570.1 (fbl_srv_powershell( nigels).070711-0102) FileDescription: PowerShell.EXE Product: Microsoft© Windows© Operating Sy stem ProductVersion: 6.1.6570.1 Debug: False Patched: False PreRelease: False PrivateBuild: True SpecialBuild: False Language: English (United States) BaseName : powershell Mode : -a--- Name : powershell.exe Length : 160256 DirectoryName : C:\Windows\system32\WindowsPowerShell\v1.0 Directory : C:\Windows\system32\WindowsPowerShell\v1.0 IsReadOnly : False Exists : True FullName : C:\Windows\system32\WindowsPowerShell\v1.0\powersh ell.exe Extension : .exe CreationTime : 3/18/2008 12:07:52 AM CreationTimeUtc : 3/18/2008 7:07:52 AM LastAccessTime : 3/19/2008 8:13:58 AM LastAccessTimeUtc : 3/19/2008 3:13:58 PM LastWriteTime : 3/18/2008 12:07:52 AM LastWriteTimeUtc : 3/18/2008 7:07:52 AM Attributes : Archive SEE ALSO about_Objects Get-Member Select-Object Format-List about_providers TOPIC about_Providers SHORT DESCRIPTION Describes how Windows PowerShell providers provide access to data and components that would not otherwise be easily accessible at the command line. The data is presented in a consistent format that resembles a file system drive. LONG DESCRIPTION Windows PowerShell providers are Microsoft .NET Framework-based programs that make the data in a specialized data store available in Windows PowerShell so that you can view and manage it. The data that a provider exposes appears in a drive, and you access the data in a path like you would on a hard disk drive. You can use any of the built-in cmdlets that the provider supports to manage the data in the provider drive. And, you can use custom cmdlets that are designed especially for the data. The providers can also add dynamic parameters to the built-in cmdlets. These are parameters that are available only when you use the cmdlet with the provider data. BUILT-IN PROVIDERS Windows PowerShell includes a set of built-in providers that you can use to access the different types of data stores. Provider Drive Data store -------- ----- ---------- Alias Alias: Windows PowerShell aliases Certificate Cert: x509 certificates for digital signatures Environment Env: Windows environment variables FileSystem * File system drives, directories, and files Function Function: Windows PowerShell functions Registry HKLM:, HKCU Windows registry Variable Variable: Windows PowerShell variables WS-Management WSMan WS-Management configuration information * The FileSystem drives vary on each system. You can also create your own Windows PowerShell providers, and you can install providers that others develop. To list the providers that are available in your session, type: get-psprovider INSTALLING AND REMOVING PROVIDERS Windows PowerShell providers are delivered to you in Windows PowerShell snap-ins, which are .NET Framework-based programs that are compiled into .dll files. The snap-ins can include providers and cmdlets. Before you use the provider features, you have to install the snap-in and then add it to your Windows PowerShell session. For more information, see about_PsSnapins. You cannot uninstall a provider, although you can remove the Windows PowerShell snap-in for the provider from the current session. If you do, you will remove all the contents of the snap-in, including its cmdlets. To remove a provider from the current session, use the Remove-PsSnapin cmdlet. This cmdlet does not uninstall the provider, but it makes the provider unavailable in the session. You can also use the Remove-PsDrive cmdlet to remove any drive from the current session. This data on the drive is not affected, but the drive is no longer available in that session. VIEWING PROVIDERS To view the Windows PowerShell providers on your computer, type: get-psprovider The output lists the built-in providers and the providers that you added to the session. THE PROVIDER CMDLETS The following cmdlets are designed to work with the data exposed by any provider. You can use the same cmdlets in the same way to manage the different types of data that providers expose. After you learn to manage the data of one provider, you can use the same procedures with the data from any provider. For example, the New-Item cmdlet creates a new item. In the C: drive that is supported by the FileSystem provider, you can use New-Item to create a new file or folder. In the drives that are supported by the Registry provider, you can use New-Item to create a new registry key. In the Alias: drive, you can use New-Item to create a new alias. For detailed information about any of the following cmdlets, type: get-help <cmdlet-name> -detailed CHILDITEM CMDLETS Get-ChildItem CONTENT CMDLETS Add-Content Clear-Content Get-Content Set-Content ITEM CMDLETS Clear-Item Copy-Item Get-Item Invoke-Item Move-Item New-Item Remove-Item Rename-Item Set-Item ITEMPROPERTY CMDLETS Clear-ItemProperty Copy-ItemProperty Get-ItemProperty Move-ItemProperty New-ItemProperty Remove-ItemProperty Rename-ItemProperty Set-ItemProperty LOCATION CMDLETS Get-Location Pop-Location Push-Location Set-Location PATH CMDLETS Join-Path Convert-Path Split-Path Resolve-Path Test-Path PSDRIVE CMDLETS Get-PSDrive New-PSDrive Remove-PSDrive PSPROVIDER CMDLETS Get-PSProvider VIEWING PROVIDER DATA The primary benefit of a provider is that it exposes its data in a familiar and consistent way. The model for data presentation is a file system drive. To use data that the provider exposes, you view it, move through it, and change it as though it were data on a hard drive. Therefore, the most important information about a provider is the name of the drive that it supports. The drive is listed in the default display of the Get-PsProvider cmdlet, but you can get information about the provider drive by using the Get-PsDrive cmdlet. For example, to get all the properties of the Function: drive, type: get-psdrive Function | format-list * You can view and move through the data in a provider drive just as you would on a file system drive. To view the contents of a provider drive, use the Get-Item or Get-ChildItem cmdlets. Type the drive name followed by a colon (:). For example, to view the contents of the Alias: drive, type: get-item alias: You can view and manage the data in any drive from another drive by including the drive name in the path. For example, to view the HKLM\Software registry key in the HKLM: drive from another drive, type: get-childitem hklm:\software To open the drive, use the Set-Location cmdlet. Remember the colon when you specify the drive path. For example, to change your location to the root directory of the Cert: drive, type: set-location cert: Then, to view the contents of the Cert: drive, type: get-childitem MOVING THROUGH HIERARCHICAL DATA You can move through a provider drive just as you would a hard disk drive. If the data is arranged in a hierarchy of items within items, use a backslash (\) to indicate a child item. Use the following format: drive:\location\child-location\... For example, to change your location to the HKLM\Software registry key, type a Set-Location command, such as: set-location hklm:\software You can also use relative references to locations. A dot (.) represents the current location. For example, if you are in the HKLM:\Software\Microsoft registry key, and you want to list the registry subkeys in the HKLM:\Software\Micrsoft\PowerShell key, type the following command: get-childitem .\powershell FINDING DYNAMIC PARAMETERS Dynamic parameters are cmdlet parameters that are added to a cmdlet by a provider. These parameters are available only when the cmdlet is used with the provider that added them. For example, the Cert: drive adds the CodeSigningCert parameter to the Get-Item and Get-ChildItem cmdlets. You can use this parameter only when you use Get-Item or Get-ChildItem in the Cert: drive. For a list of the dynamic parameters that a provider supports, see the Help file for the provider. Type: get-help <provider-name> For example: get-help certificate LEARNING ABOUT PROVIDERS Although all provider data appears in drives, and you use the same methods to move through them, the similarity stops there. The data stores that the provider exposes can be as varied as Active Directory locations and Microsoft Exchange Server mailboxes. For information about individual Windows PowerShell providers, type: get-help <ProviderName> For example: get-help registry For a list of Help topics about the providers, type: get-help * -category provider SEE ALSO about_Locations about_Path_Syntax about_pssession_details TOPIC about_PSSession_Details SHORT DESCRIPTION Provides detailed information about Windows PowerShell sessions and the role they play in remote commands. LONG DESCRIPTION A session is an environment in which Windows PowerShell runs. A session is created for you whenever you start Windows PowerShell. You can create additional sessions, called "Windows PowerShell sessions" or "PSSessions" on your computer or another computer. Unlike the sessions that Windows PowerShell creates for you, you control and manage the PSSessions that you create. PSSessions play an important role in remote computing. When you create a PSSession that is connected to a remote computer, Windows PowerShell establishes a persistent connection to the remote computer to support the PSSession. You can use the PSSession to run a series of commands, functions, and scripts that share data. This topic provides detailed information about sessions and PSSessions in Windows PowerShell. For basic information about the tasks that you can perform with sessions, see about_PSSessions. ABOUT SESSIONS Technically, a session is an execution environment in which Windows PowerShell runs. Each session includes an instance of the System.Management.Automation engine and a host program in which Windows PowerShell runs. The host can be the familiar Windows PowerShell console or another program that runs commands, such as Cmd.exe, or a program built to host Windows PowerShell, such as Windows PowerShell Integrated Scripting Environment (ISE). From a Windows perspective, a session is a Windows process on the target computer. Each session is configured independently. It includes its own properties, its own execution policy, and its own profiles. The environment that exists when the session is created persists for its lifetime even if you change the environment on the computer. All sessions are created in a global scope, even sessions that you create in a script. You can run only one command (or command pipeline) in a session at one time. A second command run synchronously (one at a time) waits up to four minutes for the first command to be completed. A second command run asynchronously (concurrently) fails. ABOUT PSSESSIONS A session is created each time that you start Windows PowerShell. And, Windows PowerShell creates temporary sessions to run individual commands. However, you can also create sessions (called "Windows PowerShell sessions" or "PSSessions") that you control and manage. PSSessions are critical to remote commands. If you use the ComputerName parameter of the Invoke-Command or Enter-PSSession cmdlets, Windows PowerShell establishes a temporary session to run the command and then closes the session as soon as the command or the interactive session is complete. However, if you use the New-PSSession cmdlet to create a PSSession, Windows PowerShell establishes a persistent session on the remote computer in which you can run multiple commands or interactive sessions. The PSSessions that you create remain open and available for use until you delete them or until you close the session in which they were created. When you create a PSSession on a remote computer, the system creates a PowerShell process on the remote computer and establishes a connection from the local computer to the process on the remote computer. When you create a PSSession on the local computer, both the new process and the connections are created on the local computer. WHEN DO I NEED A PSSESSION? The Invoke-Command and Enter-PSSession cmdlets have both ComputerName and Session parameters. You can use either to run a remote command. Use the ComputerName parameter to run a single command or a series of unrelated commands on one or many computers. To run commands that share data, you need a persistent connection to the remote computer. In that case, create a PSSession, and then use the Session parameter to run commands in the PSSession. Many other cmdlets that get data from remote computers, such as Get-Process, Get-Service, Get-EventLog, and Get-WmiObject have only a ComputerName parameter. They use technologies other than Windows PowerShell remoting to gather data remotely. These cmdlets do not have a Session parameter, but you can use the Invoke-Command cmdlet to run these commands in a PSSession. HOW DO I CREATE A PSSESSION? To create a PSSession, use the New-PSSession cmdlet. You can use New-PSSession to create a PSSession on a local or remote computer. CAN I CREATE A PSSESSION ON ANY COMPUTER? To create a PSSession that is connected to a remote computer, the computer must be configured for remoting in Windows PowerShell. The current user must be a member of the Administrators group on the remote computer, or the current user must be able to supply the credentials of a member of the Administrators group. For more information, see about_Remote_Requirements. CAN I SEE THE PSSESSIONS THAT OTHERS HAVE CREATED ON MY COMPUTER? No. You can get and manage only the PSSessions that you have created in the current session. You cannot see PSSessions that others have created, even if they run commands on the local computer. CAN I RUN A BACKGROUND JOB IN A PSSESSION? Yes. A background job is a command that runs asynchronously in the background without interacting with the current session. When you submit a command to start a job, the command returns a job object, but the job continues to run in the background until it is complete. To start a background job on a local computer, use the Start-Job command. You can run the background job in a temporary connection (by using the ComputerName parameter) or in a PSSession (by using the Session parameter). To start a background job on a remote computer, use the Invoke-Command cmdlet with its AsJob parameter, or use the Invoke-Command cmdlet to run a Start-Job command on a remote computer. When using the AsJob parameter, you can use the ComputerName or Session parameters. When using Invoke-Command to run a Start-Job command, you must run the command in a PSSession. If you use the ComputerName parameter, Windows PowerShell ends the connection when the job object returns, and the job is interrupted. For more information, see about_Jobs. CAN I RUN AN INTERACTIVE SESSION? Yes. To start an interactive session with a remote computer, use the Enter-PSSession cmdlet. In an interactive session, the commands that you type run on the remote computer, just as if you typed them directly on the remote computer. You can run an interactive session in a temporary session (by using the ComputerName parameter) or in a PSSession (by using the Session parameter). If you use a PSSession, the PSSession retains the data from previous commands, and the PSSession retains any data generated during the interactive session for use in later commands. When you end the interactive session, the PSSession remains open and available for use. For more information, see Enter-PSSession and Exit-PSSession. MUST I DELETE THE PSSESSIONS? Yes. A PSSession is a process, which is a self-contained environment that uses memory and other resources even when you are not using it. When you ar e finished with a PSSession, delete it. If you create multiple PSSessions, close the ones that you are not using, and maintain only the ones currently in use. To delete PSSessions, use the Remove-PSSession cmdlet. It deletes the PSSessions and releases all of the resources that they were using. You can also use the TimeOut parameter of New-PSSession to close an idle PSSession after an interval that you specify. For more information, see New-PSSession. If you do not delete the PSSession or set a time-out, the PSSession remains open and available for use until you close it, until you close the session in which it was created, or until you exit Windows PowerShell. However, a PSSession on a remote computer will be disconnected if the remote computer does not respond for four minutes. (The remote computer is configured to send a heartbeat pulse every three minutes.) If you save a PSSession object in a variable and then delete the PSSession or let it time out, the variable still contains the PSSession object, but the PSSession is not active and cannot be used or repaired. ARE ALL SESSIONS AND PSSESSIONS ALIKE? No. Developers can create custom sessions that include only selected providers and cmdlets. If a command works in one session but not in another, it might be because the session is restricted. SEE ALSO about_Jobs about_PSSessions about_Remote about_Remote_Requirements Invoke-Command New-PSSession Get-PSSession Remove-PSSession Enter-PSSession Exit-PSSession about_pssessions TOPIC about_PSSessions SHORT DESCRIPTION Describes Windows PowerShell sessions (PSSessions) and explains how to establish a persistent connection to a remote computer. LONG DESCRIPTION To run Windows PowerShell commands on a remote computer, you can use the ComputerName parameter of a cmdlet, or you can create a Windows PowerShell session (PSSession) and run commands in the PSSession. When you create a PSSession, Windows PowerShell establishes a persistent connection to the remote computer. Use a PSSession to run a series of related commands on a remote computer. Commands that run in the same PSSession can share data, such as the values of variables, aliases, and functions. You can also create a PSSession on the local computer and run commands in it. A local PSSession uses the Windows PowerShell remoting infrastructure to create and maintain the PSSession. This topic explains how to create, use, get, and delete PSSessions. For more advanced information, see about_PSSession_Details. Note: PSSessions use the Windows PowerShell remoting infrastructure. To use PSSessions, the local and remote computers must be configured for remoting. For more information, see about_Remote_Requirements. In Windows Vista and later versions of Windows, to create a PSSession on a local computer, you must start Windows PowerShell with the "Run as administrator" option. WHAT IS A SESSION? A session is an environment in which Windows PowerShell runs. Each time you start Windows PowerShell, a session is created for you, and you can run commands in the session. You can also add items to your session , such as modules and snap-ins, and you can create items, such as variables, functions, and aliases. These items exist only in the session and are deleted when the session ends. You can also create additional sessions, known as "Windows PowerShell sessions" or "PSSessions," on the local computer or on a remote computer. Like the default session, you can run commands in a PSSession and add and create items. However, unlike the session that starts automatically, you can control the PSSessions that you create. You can get, create, configure, and remove them , and you can run multiple commands in the same PSSession. The PSSession remains open and available until you delete it from your session. Typically, you create a PSSession to run a series of related commands on a remote computer. When you create a PSSession on a remote computer, Windows PowerShell establishes a persistent connection to the remote computer to support the session. If you use the computerName parameter of the Invoke-Command or Enter-PSSession cmdlet to run a remote command or to start an interactive session, Windows PowerShell creates a temporary session on the remote computer and closes the session as soon as the command is complete or as soon as the interactive session ends. You cannot control these temporary sessions, and you cannot use them for more than a single command or a single interactive session. In Windows PowerShell, the "current session" is the session that you are working in. The "current session" can refer to any session, including a temporary session or a PSSession. WHY USE A PSSESSION? Use a PSSession when you need a persistent connection to a remote computer. With a PSSession, you can run a series of commands that share data, such as the value of variables, the contents of a function, or the definition of an alias. You can run remote commands without creating a PSSession. Use the ComputerName parameter of remote-enabled cmdlets to run a single command or a series of unrelated commands on one or many computers. When you use the ComputerName parameter of Invoke-Expression or Enter-PSSession, Windows PowerShell establishes a temporary connection to the remote computer and then closes the connection as soon as the command is complete. Any data elements that you create are lost when the connection is closed. Other cmdlets that have a ComputerName parameter, such as Get-Eventlog and Get-WmiObject, use different remoting technologies to gather data. None create a persistent connection like a PSSession. HOW TO CREATE A PSSESSION To create a PSSession, use the New-PSSession cmdlet. To create the PSSession on a remote computer, use the ComputerName parameter of the New-PSSession cmdlet. For example, the following command creates a new PSSession on the Server01 computer. new-pssession -computername Server01 When you submit the command, New-PSSession creates the PSSession and returns an object that represents the PSSession. You can save the object in a variable when you create the PSSession, or you can use a Get-PSSession command to get the PSSession at a later time. For example, the following command creates a new PSSession on the Server01 computer and saves the resulting object in the $ps variable. $ps = new-pssession -computername Server01 HOW TO CREATE PSSESSIONS ON MULTIPLE COMPUTERS To create PSSessions on multiple computers, use the ComputerName parameter of the New-PSSession cmdlet. Type the names of the remote computers in a comma-separated list. For example, to create PSSessions on the Server01, Server02, and Server03 computers, type: new-PSSession -computername Server01, Server02, Server03 New-PSSession creates one PSSession on each of the remote computers. HOW TO GET PSSESSIONS To get the PSSessions that were created in your current session, use the Get-PSSession cmdlet. Get-PSSession returns the same type of object that New-PSSession returns. The following command gets all the PSSessions that were created in the current session. get-PSSession The default display of the PSSessions shows their ID and a default display name. You can assign an alternate display name when you create the session. Id Name ComputerName State ConfigurationName --- ---- ------------ ----- --------------------- 1 Session1 Server01 Opened Microsoft.PowerShell 2 Session2 Server02 Opened Microsoft.PowerShell 3 Session3 Server03 Opened Microsoft.PowerShell You can also save the PSSessions in a variable. The following command gets the PSSessions and saves them in the $ps123 variable. $ps123 = get-PSSession When using the PSSession cmdlets, you can refer to a PSSession by its ID, b y its name, or by its instance ID (a GUID). The following command gets a PSSession by its ID and saves it in the $ps01 variable. $ps01 = get-PSSession -id 1 Get-PSSession gets only the PSSessions that were created in the current session. It does not get PSSessions that were created in other sessions or on other computers, even if the sessions are connected to and are running commands on the local computer. HOW TO RUN COMMANDS IN A PSSESSION To run a command in one or more PSSessions, use the Invoke-Command cmdlet. Use the Session parameter to specify the PSSessions and the ScriptBlock parameter to specify the command. For example, to run a Get-ChildItem ("dir") command in each of the three PSSessions saved in the $ps123 variable, type: invoke-command -session $ps123 -scriptblock {get-childitem} HOW TO DELETE PSSESSIONS When you are finished with the PSSession, use the Remove-PSSession cmdlet to delete the PSSession and to release the resources that it was using. remove-PSSession -session $ps - or - remove-PSSession -id 1 If you do not delete the PSSession, the PSSession remains open and available for use until you close the current session or until you exit Windows PowerShell. You can also use the TimeOut parameter of New-PSSession to set an expiration time for an idle PSSession. For more information, see new-PSSession. THE PSSESSION CMDLETS Cmdlet Description ----------------- ----------------------------------------------------- - New-PSSession Creates a new PSSession on a local or remote computer . Get-PSSession Gets the PSSessions in the current session. Remove-PSSession Deletes the PSSessions in the current session. Enter-PSSession Starts an interactive session. Exit-PSSession Ends an interactive session. For a list of PSSession cmdlets, type: get-help *-PSSession FOR MORE INFORMATION For more information about PSSessions, see about_PSSession_Details. SEE ALSO about_Remote about_Remote_Requirements New-PSSession Get-PSSession Remove-PSSession Enter-PSSession Exit-PSSession Invoke-Command about_PSSnapins TOPIC about_PSSnapins SHORT DESCRIPTION Describes Windows PowerShell snap-ins and shows how to use and manage them. LONG DESCRIPTION A Windows PowerShell snap-in is a Microsoft .NET Framework assembly that contains Windows PowerShell providers and/or cmdlets. Windows PowerShell includes a set of basic snap-ins, but you can extend the power and value of Windows PowerShell by adding snap-ins that contain providers and cmdlets that you create or get from others. When you add a snap-in, the cmdlets and providers that it contains are immediately available for use in the current session, but the change affects only the current session. To add the snap-in to all future sessions, save it in your Windows PowerShell profile. You can also use the Export-Console cmdlet to save the snap-in names to a console file and then use it in future sessions. You can even save multiple console files, each with a different set of snap-ins. BUILT-IN SNAP-INS Windows PowerShell includes a set of Windows PowerShell snap-ins that contain the built-in providers and cmdlets. Microsoft.PowerShell.Core Contains providers and cmdlets used to manage the basic features of Windows PowerShell. It includes the FileSystem, Registry, Alias, Environment, Function, and Variable providers and basic cmdlets like Get-Help, Get-Command, and Get-History. Microsoft.PowerShell.Host Contains cmdlets used by the Windows PowerShell host, such as Start-Transcript and Stop-Transcript. Microsoft.PowerShell.Management Contains cmdlets such as Get-Service and Get-ChildItem that are used to manage Windows-based features. Microsoft.PowerShell.Security Contains cmdlets used to manage Windows PowerShell security, such as Get-Acl, Get-AuthenticodeSignature, and ConvertTo-SecureString. Microsoft.PowerShell.Utility Contains cmdlets used to manipulate objects and data, such as Get-Member, Write-Host, and Format-List. FINDING SNAP-INS To get a list of the Windows PowerShell snap-ins on your computer, type: get-pssnapin To get the snap-in for each Windows PowerShell provider, type: get-psprovider | format-list name, pssnapin To get a list of the cmdlets in a Windows PowerShell snap-in, type: get-command -module <snap-in_name> INSTALLING A SNAP-IN The built-in snap-ins are registered in the system and added to the default session when you start Windows PowerShell. However, you have to register snap-ins that you create or obtain from others and then add the snap-ins to your session. REGISTERING A SNAP-IN A Windows PowerShell snap-in is a program written in a .NET Framework language that is compiled into a .dll file. To use the providers and cmdlets in a snap-in, you must first register the snap-in (add it to the registry). Most snap-ins include an installation program (an .exe or .msi file) that registers the .dll file for you. However, if you receive a snap-in as a .dll file, you can register it on your system. For more information, see "How to Register Cmdlets, Providers, and Host Applications" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkID=143619. To get all the registered snap-ins on your system or to verify that a snap-in is registered, type: get-pssnapin -registered ADDING THE SNAP-IN TO THE CURRENT SESSION To add a registered snap-in to the current session, use the Add-PsSnapin cmdlet. For example, to add the Microsoft SQL Server snap-in to the session, type: add-pssnapin sql After the command is completed, the providers and cmdlets in the snap-in are available in the session. However, they are available only in the current session unless you save them. SAVING THE SNAP-INS To use a snap-in in future Windows PowerShell sessions, add the Add-PsSnapin command to your Windows PowerShell profile. Or, export the snap-in names to a console file. If you add the Add-PSSnapin command to your profile, it is available in all future Windows PowerShell sessions. If you export the names of the snap-ins in your session, you can use the export file only when you need the snap-ins. To add the Add-PsSnapin command to your Windows PowerShell profile, open your profile, paste or type the command, and then save the profile. For more information, see about_Profiles. To save the snap-ins from a session in console file (.psc1), use the Export-Console cmdlet. For example, to save the snap-ins in the current session configuration to the NewConsole.psc1 file in the current directory, type: export-console NewConsole For more information, see Export-Console. OPENING WINDOWS POWERSHELL WITH A CONSOLE FILE To use a console file that includes the snap-in, start Windows PowerShell (Powershell.exe) from the command prompt in Cmd.exe or in another Windows PowerShell session. Use the PsConsoleFile parameter to specify the console file that includes the snap-in. For example, the following command starts Windows PowerShell with the NewConsole.psc1 console file: powershell.exe -psconsolefile NewConsole.psc1 The providers and cmdlets in the snapin are now available for use in the session. REMOVING A SNAP-IN To remove a Windows PowerShell snap-in from the current session, use the Remove-PsSnapin cmdlet. For example, to remove the SQL Server snap-in from the current session, type: remove-pssnapin sql This cmdlet removes the snap-in from the session. The snap-in is still loaded, but the providers and cmdlets that it supports are no longer available. SEE ALSO Add-PsSnapin Get-PsSnapin Remove-PsSnapin Export-Console Get-Command about_Profiles about_Quoting_Rules TOPIC about_Quoting_Rules SHORT DESCRIPTION Describes rules for using single and double quotation marks in Windows PowerShell. LONG DESCRIPTION Quotation marks are used to specify a literal string. You can enclose a string in single quotation marks (') or double quotation marks ("). Quotation marks are also used to create a here-string. A here-string is a single-quoted or double-quoted string in which quotation marks are interpreted literally. A here-string can span multiple lines. All the lines in a here-string are interpreted as strings, even though they are not enclosed in quotation marks. In commands to remote computers, quotation marks define the parts of the command that are run on the remote computer. In a remote session, quotation marks also determine whether the variables in a command are interpreted first on the local computer or on the remote computer. Single and Double-Quoted Strings When you enclose a string in double quotation marks (a double-quoted string), variable names that are preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing. For example: $i = 5 "The value of $i is $i." The output of this command is: The value of 5 is 5. Also, in a double-quoted string, expressions are evaluated, and the result is inserted in the string. For example: "The value of $(2+3) is 5." The output of this command is: The value of 5 is 5. When you enclose a string in single-quotation marks (a single-quoted string), the string is passed to the command exactly as you type it. No substitution is performed. For example: $i = 5 'The value of $i is $i.' The output of this command is: The value $i is $i. Similarly, expressions in single-quoted strings are not evaluated. They are interpreted as literals. For example: 'The value of $(2+3) is 5.' The output of this command is: The value of $(2+3) is 5. To prevent the substitution of a variable value in a double-quoted string, use the backtick character (`)(ASCII 96), which is the Windows PowerShell escape character. In the following example, the backtick character that precedes the first $i variable prevents Windows PowerShell from replacing the variable name with its value. For example: $i = 5 "The value of `$i is $i." The output of this command is: The value $i is 5. To make double-quotation marks appear in a string, enclose the entire string in single quotation marks. For example: 'As they say, "live and learn."' The output of this command is: As they say, "live and learn." You can also enclose a single-quoted string in a double-quoted string. For example: "As they say, 'live and learn.'" The output of this command is: As they say, 'live and learn.' Or, double the quotation marks around a double-quoted phrase. For example: "As they say, ""live and learn.""" The output of this command is: As they say, "live and learn." To include a single quotation mark in a single-quoted string, use a second consecutive single quote. For example: 'don''t' The output of this command is: don't To force Windows PowerShell to interpret a double quotation mark literally, use a backtick character. This prevents Windows PowerShell from interpreting the quotation mark as a string delimiter. For example: "Use a quotation mark (`") to begin a string." Because the contents of single-quoted strings are interpreted literally, you cannot use the backtick character to force a literal character interpretation in a single-quoted string. For example, the following command generates an error because Windows PowerShell does not recognize the escape character. Instead, it interprets the second quotation mark as the end of the string. PS C:\> 'Use a quotation mark (`') to begin a string.' Unexpected token ')' in expression or statement. At line:1 char:27 + 'Use a quotation mark (`') < to begin a string.' Single and Double-Quoted Here-Strings The quotation rules for here-strings are slightly different. A here-string is a single-quoted or double-quoted string in which quotation marks are interpreted literally. A here-string can span multiple lines. All the lines in a here-string are interpreted as strings even though they are not enclosed in quotation marks. Like regular strings, variables are replaced by their values in double-quoted here-strings. In single-quoted here-strings, variables are not replaced by their values. You can use here-strings for any text, but they are particularly useful for the following kinds of text: - Text that contains literal quotation marks - Multiple lines of text, such as the text in an HTML or XML document - The Help text for a script or function A here-string can have either of the following formats, where <Enter> represents the linefeed or newline hidden character that is added when you press the ENTER key. Format 1: @"<Enter> <string> [string] ...<Enter> "@ Format 2: @'<Enter> <string> [string] ...<Enter> '@ In either format, the closing quotation mark must be the first character in the line. A here-string contains all the text between the two hidden characters. In the here-string, all quotation marks are interpreted literally. For example: @" For help, type "get-help" "@ The output of this command is: For help, type "get-help" Using a here-string can simplify using a string in a command. For example: @" Use a quotation mark (') to begin a string. "@ The output of this command is: Use a quotation mark (') to begin a string. In single-quoted here-strings, variables are interpreted literally and reproduced exactly. For example: @' The $profile variable contains the path of your Windows PowerShell profile. '@ The output of this command is: The $profile variable contains the path of your Windows PowerShell profile. In double-quoted here-strings, variables are replaced by their values. For example: @" Even if you have not created a profile, the path of the profile file is: $profile. "@ The output of this command is: Even if you have not created a profile, the path of the profile file is: C:\Users\User01\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 . Here-strings are typically used to assign multiple lines to a variable. For example, the following here-string assigns a page of XML to the $page variable. $page = [XML] @" <command:command xmlns:maml="http://schemas.microsoft.com/maml/2004/10" xmlns:command="http://schemas.microsoft.com/maml/dev/command/2004/10" xmlns:dev="http://schemas.microsoft.com/maml/dev/2004/10"> <command:details> <command:name> Format-Table </command:name> <maml:description> <maml:para>Formats the output as a table.</maml:para> </maml:description> <command:verb>format</command:verb> <command:noun>table</command:noun> <dev:version></dev:version> </command:details> ... </command:command> "@ Here-strings are also a convenient format for input to the ConvertFrom-StringData cmdlet, which converts here-strings to hash tables. For more information, see ConvertFrom-StringData. SEE ALSO about_Escape_Characters ConvertFrom-StringData about_Redirection TOPIC about_Redirection SHORT DESCRIPTION Describes how to redirect output from Windows PowerShell to text files. LONG DESCRIPTION By default, Windows PowerShell sends its command output to the Windows PowerShell console. However, you can direct the output to a text file, and you can redirect error output to the regular output stream. You can use the following methods to redirect output: - Use the Out-File cmdlet, which sends command output to a text file. Typically, you use the Out-File cmdlet when you need to use its parameters, such as the Encoding, Force, Width, or NoClobber parameters. - Use the Tee-Object cmdlet, which sends command output to a text file and then sends it to the pipeline. - Use the Windows PowerShell redirection operators. The Windows PowerShell redirection operators are as follows. Operator Description Example -------- ---------------------- ------------------------------ > Sends output to the get-process > process.txt specified file. >> Appends the output to dir *.ps1 >> scripts.txt the contents of the specified file. 2> Sends errors to the get-process none 2> errors.txt specified file. 2>> Appends the errors to get-process none 2>> save-errors.txt the contents of the specified file. 2>&1 Sends errors to the get-process none, powershell 2>&1 success output stream. The syntax of the redirection operators is as follows: <input> <operator> [<path>\] If the specified file already exists, the redirection operators that do not append data (> and 2>) overwrite the current contents of the file without warning. However, if the file is a read-only, hidden, or system file, the redirection fails. The append redirection operators (>> and 2>>) do not write to a read-only file, but they append content to a system or hidden file. To force the redirection of content to a read-only, hidden, or system file, use the Out-File cmdlet with its Force parameter. When you are writing to files, the redirection operators use Unicode encoding. If the file has a different encoding, the output might not be formatted correctly. To redirect content to non-Unicode files, use the Out-File cmdlet with its Encoding parameter. SEE ALSO Out-File Tee-Object about_Operators about_Command_Syntax about_Path_Syntax about_Ref TOPIC about_Ref SHORT DESCRIPTION Describes how to create and use a reference variable type. LONG DESCRIPTION You can use the reference variable type to permit a method to change the value of a variable that is passed to it. When the [ref] type is associated with an object, it returns a reference to that object. If the reference is used with a method, the method can refer to the object that was passed to it. If the object is changed within the method, the change appears as a change in the value of the variable when control returns to the calling method. To use referencing, the parameter must be a reference variable. If it is not, an InvalidArgument exception is thrown. The parameters used in method invocations must match the type required by the methods. Examples: PS> function swap([ref]$a,[ref]$b) >> { >> $a.value,$b.value = $b.value,$a.value >> } PS> $a = 1 PS> $b = 10 PS> $a,$b 1 10 PS> swap ([ref]$a) ([ref]$b) PS> $a,$b 10 1 PS C:\ps-test> function double >> { >> param ([ref]$x) $x.value = $x.value * 2 >> } PS C:> $number = 8 PS C:> $number 8 PS C> double ([ref]$number) PS C> $number 16 The variable must be a reference variable. PS C:\ps-test> double $number double : Reference type is expected in argument. At line:1 char:7 + double < $number SEE ALSO about_Variables about_Environment_Variables about_Functions about_Script_Blocks about_regular_expressions TOPIC about_Regular_Expressions SHORT DESCRIPTION Describes regular expressions in Windows PowerShell. LONG DESCRIPTION Windows PowerShell supports the following regular expression characters. Format Logic Example -------- ------------------------------- ----------------------- value Matches exact characters "book" -match "oo" anywhere in the original value. . Matches any single character. "copy" -match "c..y" [value] Matches at least one of the "big" -match "b[iou]g" characters in the brackets. [range] Matches at least one of the "and" -match "[a-e]nd" characters within the range. The use of a hyphen (-) allows you to specify an adjacent character. [^] Matches any characters except "and" -match "[^brt]nd" those in brackets. ^ Matches the beginning "book" -match "^bo" characters. $ Matches the end characters. "book" -match "ok$" * Matches any instances "baggy" -match "g*" of the preceding character. ? Matches one instance "baggy" -match "g?" of the preceding character. \ Matches the character that "Try$" -match "Try\$" follows as an escaped character. Windows PowerShell supports the character classes available in Microsoft .NET Framework regular expressions. Format Logic Example -------- ------------------------------- ----------------------- \p{name} Matches any character in the "abcd defg" -match "\p{Ll}+" named character class specified by {name}. Supported names are Unicode groups and block ranges such as Ll, Nd, Z, IsGreek, and IsBoxDrawing. \P{name} Matches text not included in 1234 -match "\P{Ll}+" the groups and block ranges specified in {name}. \w Matches any word character. "abcd defg" -match "\w+" Equivalent to the Unicode (this matches abcd) character categories [\p{Ll} \p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}]. If ECMAScript-compliant behavior is specified with the ECMAScript option, \w is equivalent to [a-zA-Z_0-9]. \W Matches any nonword character. "abcd defg" -match "\W+" Equivalent to the Unicode (This matches the space) categories [^\p{Ll}\p{Lu}\p{Lt} \p{Lo}\p{Nd}\p{Pc}]. \s Matches any white-space "abcd defg" -match "\s+" character. Equivalent to the Unicode character categories [\f\n\r\t\v\x85\p{Z}]. \S Matches any non-white-space "abcd defg" -match "\S+" character. Equivalent to the Unicode character categories [^\f\n\r\t\v\x85\p{Z}]. \d Matches any decimal digit. 12345 -match "\d+" Equivalent to \p{Nd} for Unicode and [0-9] for non- Unicode behavior. \D Matches any nondigit. "abcd" -match "\D+" Equivalent to \P{Nd} for Unicode and [^0-9] for non- Unicode behavior. Windows PowerShell supports the quantifiers available in .NET Framework regular expressions. The following are some examples of quantifiers. Format Logic Example -------- ------------------------------- ----------------------- * Specifies zero or more matches; "abc" -match "\w*" for example, \w* or (abc)*. Equivalent to {0,}. + Matches repeating instances of "xyxyxy" -match "xy+" the preceding characters. ? Specifies zero or one matches; "abc" -match "\w?" for example, \w? or (abc)?. Equivalent to {0,1}. {n} Specifies exactly n matches; "abc" -match "\w{2}" for example, (pizza){2}. {n,} Specifies at least n matches; "abc" -match "\w{2,}" for example, (abc){2,}. {n,m} Specifies at least n, but no "abc" -match "\w{2,3}" more than m, matches. All the comparisons shown in the preceding table evaluate to true. Notice that the escape character for regular expressions, a backslash (\), is different from the escape character for Windows PowerShell. The escape character for Windows PowerShell is the backtick character (`) (ASCII 96). For more information, see the "Regular Expression Language Elements" topic in the Microsoft Developer Network (MSDN) library at http://go.microsoft.com/fwlink/?LinkId=133231. SEE ALSO about_Comparison_Operators about_Operators about_remote TOPIC about_Remote SHORT DESCRIPTION Describes how to run remote commands in Windows PowerShell. LONG DESCRIPTION You can run remote commands on a single computer or on multiple computers by using a temporary or persistent connection. You can also start an interactive session with a single remote computer. This topic provides a series of examples to show you how to run different types of remote command. After you try these basic commands, read the Help topics that describe each cmdlet that is used in these commands. The topics provide the details and explain how you can modify the commands to meet your needs. Note: To use Windows PowerShell remoting, the local and remote computers must be configured for remoting. For more information, see about_Remote_Requirements. HOW TO START AN INTERACTIVE SESSION (ENTER-PSSESSION) The easiest way to run remote commands is to start an interactive session with a remote computer. When the session starts, the commands that you type run on the remote computer, just as though you typed them directly on the remote computer. You can connect to only one computer in each interactive session. To start an interactive session, use the Enter-PSSession cmdlet. The following command starts an interactive session with the Server01 computer: enter-pssession server01 The command prompt changes to indicate that you are connected to the Server01 computer. Server01\PS> Now, you can type commands on the Server01 computer. To end the interactive session, type: exit-pssession For more information, see Enter-PSSession. HOW TO USE CMDLETS THAT HAVE A COMPUTERNAME PARAMETER TO GET REMOTE DATA Several cmdlets have a ComputerName parameter that lets you get objects from remote computers. Because these cmdlets do not use WS-Management-based Windows PowerShell remoting, you can use the ComputerName parameter of these cmdlets on any computer that is running Windows PowerShell. The computers do not have to be configured for Windows PowerShell remoting, and the computers do not have to meet the system requirements for remoting. The following cmdlets have a ComputerName parameter: Clear-EventLog Limit-EventLog Get-Counter New-EventLog Get-EventLog Remove-EventLog Get-HotFix Restart-Computer Get-Process Show-EventLog Get-Service Show-Service Get-WinEvent Stop-Computer Get-WmiObject Write-EventLog For example, the following command gets the services on the Server01 remote computer: get-service -computername server01 Typically, cmdlets that support remoting without special configuration have a ComputerName parameter and do not have a Session parameter. To find these cmdlets in your session, type: get-command | where { $_.parameters.keys -contains "ComputerName" -and $_.parameters.keys -notcontains "Session"} HOW TO RUN A REMOTE COMMAND To run other commands on remote computers, use the Invoke-Command cmdlet. To run a single command or a few unrelated commands, use the ComputerName parameter of Invoke-Command to specify the remote computers. Use the ScriptBlock parameter to specify the command. For example, the following command runs a Get-Culture command on the Server01 computer. invoke-command -computername Server01 -scriptblock {get-culture} The ComputerName parameter is designed for situation in which you run a single command or several unrelated commands on one or many computers. To establish a persistent connection to a remote computer, use the Session parameter. HOW TO CREATE A PERSISTENT CONNECTION (PSSESSION) When you use the ComputerName parameter of the Invoke-Command cmdlet, Windows PowerShell establishes a connection just for the command. Then, it closes the connection when the command is complete. Any variables or functions that are defined in the command are lost. To create a persistent connection to a remote computer, use the New-PSSession cmdlet. For example, the following command creates PSSessions on the Server01 and Server02 computers and then saves the PSSessions in the $s variable. $s = new-pssession -computername Server01, Server02 HOW TO RUN COMMANDS IN A PSSESSION With a PSSession, you can run a series of remote commands that share data, like functions, aliases, and the values of variables. To run commands in a PSSession, use the Session parameter of the Invoke-Command cmdlet. For example, the following command uses the Invoke-Command cmdlet to run a Get-Process command in the PSSessions on the Server01 and Server02 computers. The command saves the processes in a $p variable in each PSSession. invoke-command -session $s -scriptblock {$p = get-process} Because the PSSession uses a persistent connection, you can run another command in the same PSSession that uses the $p variable. The following command counts the number of processes saved in $p. invoke-command -session $s -scriptblock {$p.count} HOW TO RUN A REMOTE COMMAND ON MULTIPLE COMPUTERS To run a remote command on multiple computers, type all of the computer names in the value of the ComputerName parameter of Invoke-Command. Separate the names with commas. For example, the following command runs a Get-Culture command on three computers: invoke-command -computername S1, S2, S3 -scriptblock {get-culture} You can also run a command in multiple PSSessions. The following commands create PSSessions on the Server01, Server02, and Server03 computers and then run a Get-Culture command in each of the PSSessions. $s = new-pssession -computername S1, S2, S3 invoke-command -session $s -scriptblock {get-culture} To include the local computer list of computers, type the name of the local computer, type a dot (.), or type "localhost". invoke-command -computername S1, S2, S3, localhost -scriptblock {get-culture} HOW TO RUN A SCRIPT ON REMOTE COMPUTERS To run a local script on remote computers, use the FilePath parameter of Invoke-Command. For example, the following command runs the Sample.ps1 script on the S1 and S2 computers: invoke-command -computername S1, S2 -filepath C:\Test\Sample.ps1 The results of the script are returned to the local computer. You do not need to copy any files. HOW TO STOP A REMOTE COMMAND To interrupt a command, press CTRL+C. The interrupt request is passed to the remote computer where it terminates the remote command. FOR MORE INFORMATION -- For information about the system requirements for remoting, see about_Remote_Requirements. -- For help in formatting remote output, see about_Remote_Output. -- For information about how remoting works, how to manage remote data, special configurations, security issues, and other frequently asked questions, see about_Remote_FAQ. -- For help in resolving remoting errors, see about_Remote_Troubleshooting. -- For information about PSSessions and persistent connections, see about_PSSessions. -- For information about Windows PowerShell background jobs, see about_Jobs. KEYWORDS about_Remoting SEE ALSO about_PSSessions about_Remote_Requirements about_Remote_FAQ about_Remote_TroubleShooting Enter-PSSession Invoke-Command New-PSSession about_remote_FAQ TOPIC about_Remote_FAQ SHORT DESCRIPTION Contains questions and answers about running remote commands in Windows PowerShell. LONG DESCRIPTION When you work remotely, you type commands in Windows PowerShell on one computer (known as the "local computer"), but the commands run on another computer (known as the "remote computer"). The experience of working remotely should be as much like working directly at the remote computer as possible. Note: To use Windows PowerShell remoting, the remote computer must be configured for remoting. For more information, see about_Remote_Requirements. MUST BOTH COMPUTERS HAVE WINDOWS POWERSHELL INSTALLED? Yes. To work remotely, the local and remote computers must have Windows PowerShell, the Microsoft .NET Framework 2.0, and the Web Services for Management (WS-Management) protocol. Any files and other resources that are needed to execute a particular command must be on the remote computer. You must have permission to connect to the remote computer, permission to run Windows PowerShell, and permission to access data stores (such as files and folders), and the registry on the remote computer. For more information, see about_Remote_Requirements. HOW DOES REMOTING WORK? When you submit a remote command, the command is transmitted across the network to the Windows PowerShell engine on the remote computer, and it runs in the Windows PowerShell client on the remote computer. The command results are sent back to the local computer and appear in the Windows PowerShell session on the local computer. To transmit the commands and receive the output, Windows PowerShell uses the WS-Management protocol. For information about the WS-Management protocol, see "WS-Management Protocol" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=144634. IS WINDOWS POWERSHELL REMOTING SECURE? When you connect to a remote computer, the system uses the user name and password credentials on the local computer or the credentials that you supply in the command to log you in to the remote computer. The credentials and the rest of the transmission are encrypted. To add additional protection, you can configure the remote computer to use Secure Sockets Layer (SSL) instead of HTTP to listen for Windows Remote Management (WinRM) requests. Then, users can use the UseSSL parameters of the Invoke-Command, New-PSSession, and Enter-PSSession cmdlets when establishing a connection. This option uses the more secure HTTPS channel instead of HTTP. DO ALL REMOTE COMMANDS REQUIRE WINDOWS POWERSHELL REMOTING? No. Several cmdlets have a ComputerName parameter that lets you get objects from the remote computer. These cmdlets do not use Windows PowerShell remoting. So, you can use them on any computer that is running Windows PowerShell, even if the computer is not configured for Windows PowerShell remoting or if the computer does not meet the requirements for Windows PowerShell remoting. These cmdlets include the following cmdlets: Get-Process Get-Service Get-WinEvent Get-EventLog Get-WmiObject Test-Connection To find all the cmdlets with a ComputerName parameter, type: get-help * -parameter ComputerName To determine whether the ComputerName parameter of a particular cmdlet requires Windows PowerShell remoting, see the parameter description. To display the parameter description, type: get-help <cmdlet-name> -parameter ComputerName For example: get-help get-process -parameter Computername For all other commands, use the Invoke-Command cmdlet. HOW DO I RUN A COMMAND ON A REMOTE COMPUTER? To run a command on a remote computer, use the Invoke-Command cmdlet. Enclose your command in braces ( {} ) to make it a script block. Use the ScriptBlock parameter of Invoke-Command to specify the command. You can use the ComputerName parameter of Invoke-Command to specify a remote computer. Or, you can create a persistent connection to a remote computer (a session) and then use the Session parameter of Invoke-Command to run the command in the session. For example, the following commands run a Get-Process command remotely. invoke-command -computername Server01, Server02 -scriptblock {get-process } - OR - invoke-command -session $s -scriptblock {get-process} To interrupt a remote command, type CTRL+C. The interruption request is passed to the remote computer, where it terminates the remote command. For more information about remote commands, see about_Remote and the Help topics for the cmdlets that support remoting. CAN I JUST "TELNET INTO" A REMOTE COMPUTER? You can use the Enter-PSSession cmdlet to start an interactive session with a remote computer. At the Windows Powershell prompt, type: Enter-PSSession <ComputerName> The command prompt changes to show that you are connected to the remote computer. <ComputerName>\C:> Now, the commands that you type run on the remote computer just as though you typed them directly on the remote computer. To end the interactive session, type: Exit-PSSession An interactive session is a persistent session that uses the WS-Management protocol. It is not the same as using Telnet, but it provides a similar experience. For more information, see Enter-PSSession. CAN I CREATE A PERSISTENT CONNECTION? Yes. You can run remote commands by specifying the name of the remote computer, its NetBIOS name, or its IP address. Or, you can run remote commands by specifying a Windows PowerShell session (PSSession) that is connected to the remote computer. When you use the ComputerName parameter of Invoke-Command or Enter-PSSession, Windows PowerShell establishes a temporary connection. Windows PowerShell uses the connection to run only the current command, and then it closes the connection. This is a very efficient method for running a single command or several unrelated commands, even on many remote computers. When you use the New-PSSession cmdlet to create a PSSession, Windows PowerShell establishes a persistent connection for the PSSession. Then, you can run multiple commands in the PSSession, including commands that share data. Typically, you create a PSSession to run a series of related commands that share data. Otherwise, the temporary connection created by the ComputerName parameter is sufficient for most commands. For more information about sessions, see about_PSSessions. CAN I RUN COMMANDS ON MORE THAN ONE COMPUTER AT A TIME? Yes. The ComputerName parameter of the Invoke-Command cmdlet accepts multiple computer names, and the Session parameter accepts multiple PSSessions. When you run an Invoke-Command command, Windows PowerShell runs the commands on all of the specified computers or in all of the specified PSSessions. Windows PowerShell can manage hundreds of concurrent remote connections. However, the number of remote commands that you can send might be limited by the resources of your computer and its capacity to establish and maintain multiple network connections. For more information, see the example in the Invoke-Command Help topic. WHERE ARE MY PROFILES? Windows PowerShell profiles are not run automatically in remote sessions, so the commands that the profile adds are not present in the session. In addition, the $profile automatic variable is not populated in remote sessions. To run a profile in a session, use the Invoke-Command cmdlet. For example, the following command runs the CurrentUserCurrentHost profile from the local computer in the session in $s. invoke-command -session $s -filepath $profile The following command runs the CurrentUserCurrentHost profile from the remote computer in the session in $s. Because the $profile variable is not populated, the command uses the explicit path to the profile. invoke-command -session $s {. "$home\Documents\WindowsPowerShell\Micros oft.PowerShell_profile.ps1"} After running this command, the commands that the profile adds to the sessi on are available in $s. You can also use a startup script in a session configuration to run a profile in every remote session that uses the session configuration. For more information about Windows PowerShell profiles, see about_Profiles. For more information about session configurations, see Register-PSSessionConfiguration. HOW DOES THROTTLING WORK ON REMOTE COMMANDS? To help you manage the resources on your local computer, Windows PowerShell includes a per-command throttling feature that lets you limit the number of concurrent remote connections that are established for each command. The default is 32 concurrent connections, but you can use the ThrottleLimit parameters of the cmdlets to set a custom throttle limit for particular commands. When you use the throttling feature, remember that it is applied to each command, not to the entire session or to the computer. If you are running commands concurrently in several sessions or PSSessions, the number of concurrent connections is the sum of the concurrent connections in all the sessions. To find cmdlets with a ThrottleLimit parameter, type: get-help * -parameter ThrottleLimit ARE THERE SYSTEM-SPECIFIC DIFFERENCES IN REMOTING? When you run commands on multiple computers, be aware of the differences between the remote computers, such as differences in the operating systems, the file system structure, and the registry. When you connect to a remote computer that is running Windows Vista or Windows Server 2003, the default starting location is the home directory of the current user, which is stored in the %homepath% environment variable ($env:homepath) and the Windows PowerShell $home variable. In Windows Vista, the home directory is typically C:\Users\<UserName>. In Windows Server 2003, the home directory is typically C:\Documents and Settings\<UserName>. When you connect to a remote computer that is running Windows XP, the default starting location is the home directory of the default user, which i s stored in the %homepath% environment variable ($env:homepath) for the defaul t user. The home directory is typically C:\Documents and Setting\Default User. IS THE OUTPUT OF REMOTE COMMANDS DIFFERENT FROM LOCAL OUTPUT? When you use Windows PowerShell locally, you send and receive "live" .NET Framework objects; "live" objects are objects that are associated with actual programs or system components. When you invoke the methods or change the properties of live objects, the changes affect the actual program or component. And, when the properties of a program or component change, the properties of the object that represent them also change. However, because most live objects cannot be transmitted over the network, Windows PowerShell "serializes" most of the objects sent in remote commands, that is, it converts each object into a series of XML (Constraint Language in XML [CLiXML]) data elements for transmission. When Windows PowerShell receives a serialized object, it converts the XML into a deserialized object type. The deserialized object is an accurate record of the properties of the program or component at a previous time, but it is no longer "live", that is, it is no longer directly associated with the component. And, the methods are removed because they are no longer effective. Typically, you can use deserialized objects just as you would use live objects, but you must be aware of their limitations. Also, the objects that are returned by the Invoke-Command cmdlet have additional properties that help you to determine the origin of the command. Some object types, such as DirectoryInfo objects and GUIDs, are converted back into live objects when they are received. These objects do not need any special handling or formatting. For information about interpreting and formatting remote output, see about_Remote_Output. CAN I RUN BACKGROUND JOBS REMOTELY? Yes. A Windows PowerShell background job is a Windows PowerShell command that runs asynchronously without interacting with the session. When you start a background job, the command prompt returns immediately, and you can continue to work in the session while the job runs even if it runs for an extended period of time. You can start a background job even while other commands are running because background jobs always run asynchronously in a temporary session. You can run background jobs on a local or remote computer. By default, a background job runs on the local computer. However, you can use the AsJob parameter of the Invoke-Command cmdlet to run any remote command as a background job. And, you can use Invoke-Command to run a Start-Job command remotely. For more information about background jobs in Windows PowerShell, see about_Jobs and about_Remote_Jobs. CAN I RUN WINDOWS PROGRAMS ON A REMOTE COMPUTER? You can use Windows PowerShell remote commands to run Windows-based programs on remote computers. For example, you can run Shutdown.exe or Ipconfig on a remote computer. However, you cannot use Windows PowerShell commands to open the user interface for any program on a remote computer. When you start a Windows program on a remote computer, the command is not completed, and the Windows PowerShell command prompt does not return, until the program is finished or until you press CTRL+C to interrupt the command. For example, if you run the IpConfig program on a remote computer, the command prompt does not return until IpConfig is completed. If you use remote commands to start a program that has a user interface, the program process starts, but the user interface does not appear. The Windows PowerShell command is not completed, and the command prompt does not return until you stop the program process or until you press CTRL+C, which interrupts the command and stops the process. For example, if you use a Windows PowerShell command to run Notepad on a remote computer, the Notepad process starts on the remote computer, but the Notepad user interface does not appear. To interrupt the command and restore the command prompt, press CTRL+C. CAN I LIMIT THE COMMANDS THAT USERS CAN RUN REMOTELY ON MY COMPUTER? Yes. Every remote session must use one of the session configurations on the remote computer. You can manage the session configurations on your computer (and the permissions to those session configurations) to determine who can run commands remotely on your computer and which commands they can run. A session configuration configures the environment for the session. You can define the configuration by using an assembly that implements a new configuration class or by using a script that runs in the session. The configuration can determine the commands that are available in the session. And, the configuration can include settings that protect the computer, such as settings that limit the amount of data that the session can receive remotely in a single object or command. You can also specify a security descriptor that determines the permissions that are required to use the configuration. The Enable-PSRemoting cmdlet creates a default session configuration on your computer, Microsoft.PowerShell (and Microsoft.PowerShell32 on 64-bit operating systems). Enable-PSRemoting sets the security descriptor for the configuration to allow only members of the Administrators group on your computer to use them. You can use the session configuration cmdlets to edit the default session configurations, to create new session configurations, and to change the security descriptors of all the session configurations. When users use the Invoke-Command, New-PSSession, or Enter-PSSession cmdlets, they can use the ConfigurationName parameter to indicate the session configuration that is used for the session. And, they can change the default configuration that their sessions use by changing the value of the $PSSessionConfigurationName preference variable in the session. For more information about session configurations, see the Help for the session configuration cmdlets. To find the session configuration cmdlets, type: get-command *pssessionconfiguration WHAT ARE FAN-IN AND FAN OUT CONFIGURATIONS? The most common Windows PowerShell remoting scenario involving multiple computers is the one-to-many configuration, in which one local computer (the administrator's computer) runs Windows PowerShell commands on numerous remote computers. This is known as the "fan-out" scenario. However, in some enterprises, the configuration is many-to-one, where many client computers connect to a single remote computer that is running Windows PowerShell, such as a file server or a kiosk. This is known as the "fan-in" configuration. Windows PowerShell remoting supports both fan-out and fan-in configurations. For the fan-out configuration, Windows PowerShell uses the Web Services for Management (WS-Management) protocol and the WinRM service that supports the Microsoft implementation of WS-Management. When a local computer connects to a remote computer, WS-Management establishes a connection and uses a plug-in for Windows PowerShell to start the Windows PowerShell host process (Wsmprovhost.exe) on the remote computer. The user can specify an alternate port, an alternate session configuration, and other features to customize the remote connection. To support the "fan-in" configuration, Windows PowerShell uses Internet Information Services (IIS) to host WS-Management, to load the Windows PowerShell plug-in, and to start Windows PowerShell. In this scenario, instead of starting each Windows PowerShell session in a separate process, all Windows PowerShell sessions run in the same host process. IIS hosting and fan-in remote management is not supported in Windows XP or in Windows Server 2003. In a fan-in configuration, the user can specify a connection URI and an HTTP endpoint, including the transport, computer name, port, and application name. IIS forwards all the requests with a specified application name to the application. The default is WS-Management, which can host Windows PowerShell. You can also specify an authentication mechanism and prohibit or allow redirection from HTTP and HTTPS endpoints. CAN I TEST REMOTING ON A SINGLE COMPUTER (NOT IN A DOMAIN)? Yes. Windows PowerShell remoting is available even when the local computer is not in a domain. You can use the remoting features to connect to sessions and to create sessions on the same computer. The features work the same as they do when you connect to a remote computer. To run remote commands on a computer in a workgroup, change the following Windows settings on the computer. Caution: These settings affect all users on the system and they can make the system more vulnerable to a malicious attack. Use caution when making these changes. -- Windows XP with SP2: Use Local Security Settings (Secpol.msc) to change the setting of the "Network Access: Sharing and security model for local accounts" policy in Security Settings\Local Policies\Security Options to "Classic". -- Windows Vista: Create the following registry entry, and then set its value to 1: LocalAccountTokenFilterPolicy in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System You can use the following Windows PowerShell command to add this entry: new-itemproperty ` -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System ` -name LocalAccountTokenFilterPolicy -propertyType DWord -value 1 -- Windows 2003: No changes are needed because the default setting of the "Network Access: Sharing and security model for local accounts" policy is "Classic". Verify the setting in case it has changed. CAN I RUN REMOTE COMMANDS ON A COMPUTER IN ANOTHER DOMAIN? Yes. Typically, the commands run without error, although you might need to use the Credential parameter of the Invoke-Command, New-PSSession, or Enter-PSSession cmdlets to provide the credentials of a member of the Administrators group on the remote computer. This is sometimes required even when the current user is a member of the Administrators group on the local and remote computers. However, if the remote computer is not in a domain that the local computer trusts, the remote computer might not be able to authenticate the user's credentials. To enable authentication, use the following command to add the remote computer to the list of trusted hosts for the local computer in WinRM. Type the command at the Windows PowerShell prompt. set-item WSMan:\localhost\Client\TrustedHosts -value <Remote-computer-n ame> For example, to add the Server01 computer to the list of trusted hosts on the local computer, type the following command at the Windows PowerShell prompt: set-item WSMan:\localhost\Client\TrustedHosts -value Server01 SEE ALSO about_Remote about_Profiles about_PSSessions about_Remote_Jobs Invoke-Command New-PSSession about_remote_jobs TOPIC about_Remote_Jobs SHORT DESCRIPTION Describes how to run background jobs on remote computers. DETAILED DESCRIPTION A background job is a command that runs asynchronously without interacting with the current session. The command prompt returns immediately, and you can continue to use the session while the job runs. By default, background jobs run on the local computer. However, you can use several different procedures to run background jobs on remote computers. This topic explains how to run a background job on a remote computer. For information about how to run background jobs on a local computer, see about_Jobs. For more information about background jobs, see about_Job_Details. REMOTE BACKGROUND JOBS You can run background jobs on remote computers by using three different methods. -- Start an interactive session with a remote computer, and start a job in the interactive session. The procedures are the same as running a local job, although all actions are performed on the remote computer. -- Run a background job on a remote computer that returns its results to the local computer. Use this method when you want to collect the results of background jobs and maintain them in a central location on the local computer. -- Run a background job on a remote computer that maintains its results on the remote computer. Use this method when the job data is more securely maintained on the originating computer. START A BACKGROUND JOB IN AN INTERACTIVE SESSION You can start an interactive session with a remote computer and then start a background job during the interactive session. For more information about interactive sessions, see about_Remote, and see Enter-PSSession. The procedure for starting a background job in an interactive session is almost identical to the procedure for starting a background job on the local computer. However, all of the operations occur on the remote computer, not the local computer. STEP 1: ENTER-PSSESSION Use the Enter-PSSession cmdlet to start an interactive session with a remote computer. You can use the ComputerName parameter of Enter-PSSession to establish a temporary connection for the interactive session. Or, you can use the Session parameter to run the interactive session in a Windows PowerShell session (PSSession). The following command starts an interactive session on the Server01 computer. C:\PS> Enter-PSSession -computername Server01 The command prompt changes to show that you are now connected to the Server01 computer. Server01\C:> STEP 2: START-JOB To start a background job in the session, use the Start-Job cmdlet. The following command runs a background job that gets the events in the Windows PowerShell event log on the Server01 computer. The Start-Job cmdlet returns an object that represents the job. This command saves the job object in the $job variable. Server01\C:> $job = start-job -scriptblock {get-eventlog "Windows Power Shell"} While the job runs, you can use the interactive session to run other commands, including other background jobs. However, you must keep the interactive session open until the job is completed. If you end the session, the job is interrupted, and the results are lost. STEP 3: GET-JOB To find out if the job is complete, display the value of the $job variable, or use the Get-Job cmdlet to get the job. The following command uses the Get-Job cmdlet to display the job. Server01\C:> get-job $job SessionId Name State HasMoreData Location Command --------- ---- ----- ----------- -------- ------- 1 Job1 Complete True localhost get-eventlog "Windo ws PowerShell" The Get-Job output shows that job is running on the "localhost" computer because the job was started on and is running on the same computer (in this case, Server01). STEP 4: RECEIVE-JOB To get the results of the job, use the Receive-Job cmdlet. You can display the results in the interactive session or save them to a file on the remote computer. The following command gets the results of the job in the $job variable. The command uses the redirection operator (>) to save the results of the job in the PsLog.txt file on the Server01 computer. Server01\C:> receive-job $job > c:\logs\PsLog.txt STEP 5: EXIT-PSSESSION To end the interactive session, use the Exit-PSSession cmdlet. The command prompt changes to show that you are back in the original session on the local computer. Server01\C:> Exit-PSSession C:\PS> STEP 6: INVOKE-COMMAND: GET CONTENT To view the contents of the PsLog.txt file on the Server01 computer at any time, start another interactive session, or run a remote command. This type of command is best run in a PSSession (a persistent connection) in case you want to use several commands to investigate and manage the data in the PsLog.txt file. For more information about PSSessions, see about_PSSessions. The following commands use the New-PSSession cmdlet to create a PSSession that is connected to the Server01 computer, and they use the Invoke-Command cmdlet to run a Get-Content command in the PSSession to view the contents of the file. C:\PS> $s = new-pssession -computername Server01 C:\PS> invoke-command -session $s -scriptblock {get-content c:\logs\psl og.txt} START A REMOTE JOB THAT RETURNS THE RESULTS TO THE LOCAL COMPUTER (ASJOB) To start a background job on a remote computer that returns the command results to the local computer, use the AsJob parameter of a cmdlet such as the Invoke-Command cmdlet. When you use the AsJob parameter, the job object is actually created on the local computer even though the job runs on the remote computer. When the job is completed, the results are returned to the local computer. You can use the cmdlets that contain the Job noun (the Job cmdlets) to manage any job created by any cmdlet. Many of the cmdlets that have AsJob parameters do not use Windows PowerShell remoting, so you can use them even on computers that are not configured for remoting and that do not meet the requirements for remoting. STEP 1: INVOKE-COMMAND -ASJOB The following command uses the AsJob parameter of Invoke-Command to start a background job on the Server01 computer. The job runs a Get-Eventlog command that gets the events in the System log. You can use the JobName parameter to assign a display name to the job. invoke-command -computername Server01 -scriptblock {get-eventlog system} -asjob The results of the command resemble the following sample output. SessionId Name State HasMoreData Location Command --------- ---- ----- ----------- -------- ------- 1 Job1 Running True Server01 get-eventlog s ystem When the AsJob parameter is used, Invoke-Command returns the same type of job object that Start-Job returns. You can save the job object in a variable, or you can use a Get-Job command to get the job. Note that the value of the Location property shows that the job ran on the Server01 computer. STEP 2: GET-JOB To manage a job started by using the AsJob parameter of the Invoke-Command cmdlet, use the Job cmdlets. Because the job object that represents the remote job is on the local computer, you do not need to run remote commands to manage the job. To determine whether the job is complete, use a Get-Job command. The following command gets all of the jobs that were started in the current session. get-job Because the remote job was started in the current session, a local Get-Job command gets the job. The State property of the job object shows that the command was completed successfully. SessionId Name State HasMoreData Location Command --------- ---- ----- ----------- -------- ------- 1 Job1 Completed True Server01 get-eventlog sy stem STEP 3: RECEIVE-JOB To get the results of the job, use the Receive-Job cmdlet. Because the job results are automatically returned to the computer where the job object resides, you can get the results with a local Receive-Job command. The following command uses the Receive-Job cmdlet to get the results of the job. It uses the session ID to identify the job. This command saves the job results in the $results variable. You can also redirect the results to a file. $results = receive-job -id 1 START A REMOTE JOB THAT KEEPS THE RESULTS ON THE REMOTE COMPUTER To start a background job on a remote computer that keeps the command results on the remote computer, use the Invoke-Command cmdlet to run a Start-Job command on a remote computer. You can use this method to run background jobs on multiple computers. When you run a Start-Job command remotely, the job object is created on the remote computer, and the job results are maintained on the remote computer. From the perspective of the job, all operations are local. You are just running commands remotely to manage a local job on the remote computer. STEP 1: INVOKE-COMMAND START-JOB Use the Invoke-Command cmdlet to run a Start-Job command on a remote computer. This command requires a PSSession (a persistent connection). If you use the ComputerName parameter of Invoke-Command to establish a temporary connection, the Invoke-Command command is considered to be complete when the job object is returned. As a result, the temporary connection is closed, and the job is canceled. The following command uses the New-PSSession cmdlet to create a PSSession that is connected to the Server01 computer. The command saves the PSSession in the $s variable. $s = new-pssession -computername Server01 The next command uses the Invoke-Command cmdlet to run a Start-Job command in the PSSession. The Start-Job command and the Get-Eventlog command are enclosed in braces. invoke-command -session $s -scriptblock {start-job -scriptblock {get-eve ntlog system}} The results resemble the following sample output. Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 2 Job2 Running True Localhost get-eventlog syst em When you run a Start-Job command remotely, Invoke-Command returns the same type of job object that Start-Job returns. You can save the job object in a variable, or you can use a Get-Job command to get the job. Note that the value of the Location property shows that the job ran on the local computer, known as "LocalHost", even though the job ran on the Server01 computer. Because the job object is created on the Server01 computer and the job runs on the same computer, it is considered to be a local background job. STEP 2: INVOKE-COMMAND GET-JOB To manage a remote background job, use the Job cmdlets. Because the job object is on the remote computer, you need to run remote commands to get, stop, wait for, or retrieve the job results. To see if the job is complete, use an Invoke-Command command to run a Get-Job command in the PSSession that is connected to the Server01 computer. invoke-command -session $s -scriptblock {get-job} The command returns a job object. The State property of the job object shows that the command was completed successfully. SessionId Name State HasMoreData Location Command --------- ---- ----- ----------- -------- ------- 2 Job2 Completed True LocalHost get-event log system STEP 3: INVOKE-COMMAND RECEIVE-JOB To get the results of the job, use the Invoke-Command cmdlet to run a Receive-Job command in the PSSession that is connected to the Server01 computer. The following command uses the Receive-Job cmdlet to get the results of the job. It uses the session ID to identify the job. This command saves the job results in the $results variable. It uses the Keep parameter of Receive-Job to keep the result in the job cache on the remote computer. $results = invoke-command -session $s -scriptblock {receive-job -sessio nid 2 -keep} You can also redirect the results to a file on the local or remote computer. The following command uses a redirection operator to save the results in a file on the Server01 computer. invoke-command -session $s -command {receive-job -sessionid 2 > c:\logs \pslog.txt} SEE ALSO about_Jobs about_Job_Details about_Remote Invoke-Command Start-Job Get-Job Wait-Job Stop-Job Remove-Job New-PSSession Enter-PSSession Exit-PSSession about_remote_output TOPIC about_Remote_Output SHORT DESCRIPTION Describes how to interpret and format the output of remote commands. LONG DESCRIPTION The output of a command that was run on a remote computer might look like output of the same command run on a local computer, but there are some significant differences. This topic explains how to interpret, format, and display the output of commands that are run on remote computers. DISPLAYING THE COMPUTER NAME When you use the Invoke-Command cmdlet to run a command on a remote computer, the command returns an object that includes the name of the computer that generated the data. The remote computer name is stored in the PSComputerName property. For many commands, the PSComputerName is displayed by default. For example, the following command runs a Get-Culture command on two remote computers, Server01 and Server02. The output, which appears below, includes the names of the remote computers on which the command ran. C:\PS> invoke-command -script {get-culture} -comp Server01, Server02 LCID Name DisplayName PSComputerName ---- ---- ----------- -------------- 1033 en-US English (United States) Server01 1033 es-AR Spanish (Argentina) Server02 You can use the HideComputerName parameter of Invoke-Command to hide the PSComputerName property. This parameter is designed for commands that collect data from only one remote computer. The following command runs a Get-Culture command on the Server01 remote computer. It uses the HideComputerName parameter to hide the PSComputerName property and related properties. C:\PS> invoke-command -scr {get-culture} -comp Server01 -HideComputerNa me LCID Name DisplayName ---- ---- ----------- 1033 en-US English (United States) You can also display the PSComputerName property if it is not displayed by default. For example, the following commands use the Format-Table cmdlet to add the PSComputerName property to the output of a remote Get-Date command. C:\PS> $dates = invoke-command -script {get-date} -computername Server0 1, Server02 C:\PS> $dates | format-table DateTime, PSComputerName -auto DateTime PSComputerName -------- -------------- Monday, July 21, 2008 7:16:58 PM Server01 Monday, July 21, 2008 7:16:58 PM Server02 DISPLAYING THE MACHINENAME PROPERTY Several cmdlets, including Get-Process, Get-Service, and Get-EventLog, have a ComputerName parameter that gets the objects on a remote computer. These cmdlets do not use Windows PowerShell remoting, so you can use them even on computers that are not configured for remoting in Windows PowerShell. The objects that these cmdlets return store the name of the remote computer in the MachineName property. (These objects do not have a PSComputerName property.) For example, this command gets the PowerShell process on the Server01 and Server02 remote computers. The default display does not include the MachineName property. C:\PS> get-process powershell -computername server01, server02 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 920 38 97524 114504 575 9.66 2648 powershell 194 6 24256 32384 142 3020 powershell 352 27 63472 63520 577 3.84 4796 powershell You can use the Format-Table cmdlet to display the MachineName property of the process objects. For example, the following command saves the processes in the $p variable and then uses a pipeline operator (|) to send the processes in $p to the Format-Table command. The command uses the Property parameter of Format-Table to include the MachineName property in the display. C:\PS> $p = get-process powershell -comp Server01, Server02 C:\PS> $P | format-table -property ID, ProcessName, MachineName -auto Id ProcessName MachineName -- ----------- ----------- 2648 powershell Server02 3020 powershell Server01 4796 powershell Server02 The following more complex command adds the MachineName property to the default process display. It uses hash tables to specify calculated properties. Fortunately, you do not have to understand it to use it. (Note that the backtick [`] is the continuation character.) C:\PS> $p = get-process powershell -comp Server01, Server02 C:\PS> $p | format-table -property Handles, ` @{Label="NPM(K)";Expression={[int]($_.NPM/1024)}}, ` @{Label="PM(K)";Expression={[int]($_.PM/1024)}}, ` @{Label="WS(K)";Expression={[int]($_.WS/1024)}}, ` @{Label="VM(M)";Expression={[int]($_.VM/1MB)}}, ` @{Label="CPU(s)";Expression={if ($_.CPU -ne $()){ $_.CPU.To String("N")}}}, ` Id, ProcessName, MachineName -auto Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName MachineName ------- ------ ----- ----- ----- ------ -- ----------- ----------- 920 38 97560 114532 576 2648 powershell Server02 192 6 24132 32028 140 3020 powershell Server01 438 26 48436 59132 565 4796 powershell Server02 DESERIALIZED OBJECTS When you run remote commands that generate output, the command output is transmitted across the network back to the local computer. Because most live Microsoft .NET Framework objects (such as the objects that Windows PowerShell cmdlets return) cannot be transmitted over the network, the live objects are "serialized". In other words, the live objects are converted into XML representations of the object and its properties. Then, the XML-based serialized object is transmitted across the network. On the local computer, Windows PowerShell receives the XML-based serialized object and "deserializes" it by converting the XML-based object into a standard .NET Framework object. However, the deserialized object is not a live object. It is a snapshot of the object at the time that it was serialized, and it includes properties but no methods. You can use and manage these objects in Windows PowerShell, including passing them in pipelines, displaying selected properties, and formatting them. Most deserialized objects are automatically formatted for display by entries in the Types.ps1xml or Format.ps1xml files. However, the local computer might not have formatting files for all of the deserialized objects that were generated on a remote computer. When objects are not formatted, all of the properties of each object appear in the console in a streaming list. When objects are not formatted automatically, you can use the formatting cmdlets, such as Format-Table or Format-List, to format and display selected properties. Or, you can use the Out-GridView cmdlet to display the objects in a table. Also, if you run a command on a remote computer that uses cmdlets that you do not have on your local computer, the objects that the command returns might not be formatted properly because you do not have the formatting files for those objects on your computer. To get formatting data from another computer, use the Get-FormatData and Export-FormatData cmdlets. Some object types, such as DirectoryInfo objects and GUIDs, are converted back into live objects when they are received. These objects do not need any special handling or formatting. ORDERING THE RESULTS The order of the computer names in the ComputerName parameter of cmdlets determines the order in which Windows PowerShell connects to the remote computers. However, the results appear in the order in which the local computer receives them, which might be a different order. To change the order of the results, use the Sort-Object cmdlet. You can sort on the PSComputerName or MachineName property. You can also sort on another property of the object so that the results from different computers are interspersed. SEE ALSO about_Remote Format-Table Get-EventLog Get-Process Get-Service Get-WmiObject Invoke-Command Out-GridView Select-Object about_remote_requirements TOPIC about_Remote_Requirements SHORT DESCRIPTION Describes the system requirements and configuration requirements for running remote commands in Windows PowerShell. LONG DESCRIPTION This topic describes the system requirements, user requirements, and resource requirements for establishing remote connections and running remote commands in Windows PowerShell. It also provides instructions for configuring remote operations. Note: Many cmdlets (including the Get-Service, Get-Process, Get-WMIObject, Get-EventLog, and Get-WinEvent cmdlets) get objects from remote computers by using Microsoft .NET Framework methods to retrieve the objects. They do not use the Windows PowerShell remoting infrastructure. The requirements in this document do not apply to these cmdlets. To find the cmdlets that have a ComputerName parameter but do not use Windows PowerShell remoting, read the description of the ComputerName parameter of the cmdlets. SYSTEM REQUIREMENTS The local and remote computers must have: -- Windows PowerShell 2.0 or later -- The Microsoft .NET Framework 2.0 or later -- Windows Remote Management 2.0 To find the version number of an installed version of Windows PowerShell, use the $PSVersionTable automatic variable. The value of the $PSVersionTable.Version.Major property must be at least 2. Windows Remote Management 2.0 is included in Windows 7 and in Windows Server 2008 R2. It is also included in the integrated installation package for earlier versions of Windows that includes Windows PowerShell. Windows PowerShell Integrated Scripting Environment (ISE) and the Out-Gridview cmdlet require the Microsoft .NET Framework 3.5 with Service Pack 1. The Get-WinEvent cmdlet requires the Microsoft .NET Framework 3.5 or greater. These upgrades are not required for remoting. USER PERMISSIONS To establish a remote connection and run remote commands, the current user must be a member of the Administrators group on the remote computer. Or, the current user must be able to provide the credentials of an administrator. RUN AS ADMINISTRATOR In Windows Vista, Windows Server 2008, and later versions of Windows, Administrator privileges are required for the following remoting operations: -- Establishing a remote connection to the local computer. This is commonly known as a "loopback" scenario. -- Managing session configurations on the local computer. -- Viewing and changing WS-Management settings on the local computer. These are the settings in the LocalHost node of the WSMAN: drive. To perform these tasks, you must start Windows PowerShell with the "Run as administrator" option even if you are a member of the Administrators group on the local computer. In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell with the "Run as administrator" option: 1. Click Start, click All Programs, click Accessories, and then click the Windows PowerShell folder. 2. Right-click Windows PowerShell, and then click "Run as administrator". In Windows Vista and Windows Server 2008, to start Windows PowerShell with the "Run as administrator" option: 1. Click Start, click All Programs, and then click the Windows PowerShell folder. 2. Right-click Windows PowerShell, and then click "Run as administrator". The "Run as administrator" option is also available in other Windows Explorer entries for Windows PowerShell, including shortcuts. Just right-click the item, and then click "Run as administrator". When you start Windows PowerShell from another program such as Cmd.exe, use the "Run as administrator" option to start the program. HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING The remoting features of Windows PowerShell are supported by the WinRM service, which is the Microsoft implementation of the Web Services for Management (WS-Management) protocol. To use the remoting features, you need to change the default configuration of WS-Management on the system. To configure Windows PowerShell to receive remote commands: 1. Start Windows PowerShell. In Windows Vista and later versions of Windows, start Windows PowerShell with the "Run as administrator" option. 2. At the command prompt, type: enable-psremoting This procedure allows users on other computers to establish remote connections and to run remote commands on the local computer. It also allows you to create a "loopback" connection on the local computer. To verify that remoting is configured correctly, run a test command such as the following command, which creates a remote session on the local computer. new-pssession If remoting is configured correctly, the command will create a session on the local computer and return an object that represents the session. The output should resemble the following sample output: C:\PS> new-pssession Id Name ComputerName State ConfigurationName -- ---- ------------ ----- ----- 1 Session1 localhost Opened Microsoft.PowerShell If the command fails, see about_Remote_Troubleshooting for assistance. UNDERSTAND POLICIES When you work remotely, you use two instances of Windows PowerShell, one on the local computer and one on the remote computer. As a result, your work is affected by the Windows policies and the Windows PowerShell policies on the local and remote computers. In general, before you connect and as you are establishing the connection, the policies on the local computer are in effect. When you are using the connection, the policies on the remote computer are in effect. SEE ALSO about_Remote about_PSSessions Invoke-Command Enter-PSSession New-PSSession about_remote_troubleshooting TOPIC about_Remote_Troubleshooting SHORT DESCRIPTION Describes how to troubleshoot remote operations in Windows PowerShell. LONG DESCRIPTION This section describes some of the problems that you might encounter when using the remoting features of Windows PowerShell that are based on WS-Management technology and it suggests solutions to these problems. Before using Windows PowerShell remoting, see about_Remote and about_Remote_Requirements for guidance on configuration and basic use Also, the Help topics for each of the remoting cmdlets, particularly the paramete r descriptions, have useful information that is designed to help you avoid problems. Updated versions of this topic, and other Windows PowerShell help topics, can be found online in the Microsoft TechNet Library. To see the online version of this help topic, paste the following URL in your Internet browser: http://go.microsoft.com/fwlink/?LinkID=135188 NOTE: On Windows Vista, Windows Server 2008, and later versions of Windows, to view or change settings for the local computer in the WSMan: drive, including changes to the session configurations, trusted hosts, ports, or listeners, start Windows PowerShell with the "Run as administrator" option. TROUBLESHOOTING PERMISSION AND AUTHENTICATION ISSUES This section discusses remoting problems that are related to user and computer permissions and remoting requirements. HOW TO RUN AS ADMINISTRATOR --------------------------- ERROR: Access is denied. You need to run this cmdlet from an elevated process. To start a remote session on the local computer, or to view or change settings for the local computer in the WSMan: drive, including changes to the session configurations, trusted hosts, ports, or listeners, start Windows PowerShell with the "Run as administrator" option. To start Windows PowerShell with the "Run as administrator option: -- Right-click a Windows PowerShell (or Windows PowerShell ISE) icon and then click "Run as administrator. To start Windows PowerShell with the "Run as administrator option in Windows 7 and Windows Server 2008 R2. -- In the Windows taskbar, right-click the Windows PowerShell icon, and then click "Run Windows PowerShell as admin." Note: In Windows Server 2008 R2, the Windows PowerShell icon is pinned to the taskbar by default. HOW TO ENABLE REMOTING ---------------------- ERROR: ACCESS IS DENIED - or - ERROR: The connection to the remote host was refused. Verify that the WS-Management service is running on the remote host and configured to listen for requests on the correct port and HTTP URL. No configuration is required to enable a computer to send remote commands. However, to receive remote commands, the computer must be configured for remoting. The configuration includes starting the WinRM service, setting the startup type for the WinRM service to Automatic, creating listeners for HTTP and HTTPS connections, and creating default session configurations. To configure a computer to receive remote commands, use the Enable-PSRemoting cmdlet. The following command enables all required remote settings, enables the session configurations, and restarts the WinRM service to make the changes effective. enable-psremoting To suppress all user prompts, type: enable-psremoting -force For more information, see Enable-PSRemoting. HOW TO ENABLE REMOTING IN AN ENTERPRISE --------------------------------------- ERROR: ACCESS IS DENIED - or - ERROR: The connection to the remote host was refused. Verify that the WS-Management service is running on the remote host and configured to listen for requests on the correct port and HTTP URL. To enable a single computer to receive remote Windows PowerShell commands and accept connections, use the Enable-PSRemoting cmdlets. To enable remoting for multiple computers in an enterprise, you can use the following scaled options. -- To configure listeners for remoting, enable the "Allow automatic configuration of listeners" group policy. For instructions, see "How to Enable Listeners by Using a Group Policy" (below). -- To set the startup type of the Windows Remote Management (WinRM) to Automatic on multiple computers, use the Set-Service cmdlet. For instructions, see "How to Set the Startup Type of the WinrM Service" (below). -- To enable a firewall exception, use the "Windows Firewall: Allow Local Port Exceptions" group policy. For instructions, see "How to Create a Firewall Exception by Using a Group Policy" (below). HOW TO ENABLE LISTENERS BY USING A GROUP POLICY ------------------------------------------------ ERROR: ACCESS IS DENIED - or - ERROR: The connection to the remote host was refused. Verify that the WS-Management service is running on the remote host and configured to listen for requests on the correct port and HTTP URL. To configure the listeners for all computers in a domain, enable the "Allow automatic configuration of listeners" policy in the following Group Policy path: Computer Configuration\Administrative Templates\Windows Components \Windows Remote Management (WinRM)\WinRM service Enable the policy and specify the IPv4 and IPv6 filters. Wildcards (*) are permitted. HOW TO ENABLE A FIREWALL EXCEPTION BY USING A GROUP POLICY ---------------------------------------------------------- ERROR: ACCESS IS DENIED - or - ERROR: The connection to the remote host was refused. Verify that the WS-Management service is running on the remote host and configured to listen for requests on the correct port and HTTP URL. To enable a firewall exception for in all computers in a domain, enable the "Windows Firewall: Allow local port exceptions" policy in the following Group Policy path: Computer Configuration\Administrative Templates\Network \Network Connections\Windows Firewall\Domain Profile This policy allows members of the Administrators group on the computer to use Windows Firewall in Control Panel to create a firewall exception for the Windows Remote Management service. HOW TO SET THE STARTUP TYPE OF THE WINRM SERVICE ------------------------------------------------ ERROR: ACCESS IS DENIED Windows PowerShell remoting depends upon the Windows Remote Management (WinRM) service. The service must be running to support remote commands. On Windows Server 2003, Windows Server 2008, and Windows Server 2008 R2, the startup type of the Windows Remote Management (WinRM) service is Automatic. However, on Windows XP, Windows Vista, and Windows 7, the WinRM service is disabled by default. To set the startup type of a service on a remote computer, use the Set-Service cmdlet. To run the command on multiple computers, you can create a text file or CSV file of the computer names. For example, the following commands get a list of computer names from the Servers.txt file and then sets the startup type of the WinRM service on all of the computers to Automatic. C:\PS> $servers = get-content servers.txt C:\PS> set-service WinRM -computername $servers -startuptype Automatic To see the results use the Get-WMIObject cmdlet with the Win32_Service obje ct. For more information, see Set-Service. HOW TO RECREATE THE DEFAULT SESSION CONFIGURATIONS -------------------------------------------------- ERROR: ACCESS IS DENIED To connect to the local computer and run commands remotely, the local computer must include session configurations for remote commands. When you use Enable-PSRemoting, it creates default session configurations on the local computer. Remote users use these session configurations whenever a remote command does not include the ConfigurationName parameter. If the default configurations on a computer are unregistered or deleted, use the Enable-PSRemoting cmdlet to recreate them. You can use this cmdlet repeatedly. It does not generate errors if a feature is already configured. If you change the default session configurations and want to restore the original default session configurations, use the Unregister-PSSessionConfiguration cmdlet to delete the changed session configurations and then use the Enable-PSRemoting cmdlet to restore them. Enable-PSRemoting does not change existing session configurations. Note: When Enable-PSRemoting restores the default session configuration, it does not create explicit security descriptors for the configurations. Instead, the configurations inherit the security descriptor of the RootSDDL , which is secure by default. To see the RootSDDL security descriptor, type: get-item wsman:\localhost\Service\RootSDDL To change the RootSDDL, use the Set-Item cmdlet in the WSMan: drive. To change the security descriptor of a session configuration, use the Set-PSSessionConfiguration cmdlet with the SecurityDescriptorSDDL or ShowSecurityDescriptorUI parameters. For more information about the WSMan: drive, see the Help topic for the WS-Management provider ("get-help wsman"). HOW TO PROVIDE ADMINISTRATOR CREDENTIALS ---------------------------------------- ERROR: ACCESS IS DENIED To create a PSSession or run commands on a remote computer, by default, the current user must be a member of the Administrators group on the remote computer. Credentials are sometimes required even when the current user is logged on to an account that is a member of the Administrators group. If the current user is a member of the Administrators group on the remote computer, or can provide the credentials of a member of the Administrators group, use the Credential parameter of the New-PSSession, Enter-PSSession or Invoke-Command cmdlets to connect remotely. For example, the following command provides the credentials of an Administrator. Invoke-Command -ComputerName Server01 -Credential Domain01\Admin01 For more information about the Credential parameter, see New-PSSession, Enter-PSSession or Invoke-Command. HOW TO ENABLE REMOTING FOR NON-ADMINISTRATIVE USERS --------------------------------------------------- ERROR: ACCESS IS DENIED To establish a PSSession or run a command on a remote computer, the user must have permission to use the session configurations on the remote computer. By default, only members of the Administrators group on a computer have permission to use the default session configurations. Therefore, only members of the Administrators group can connect to the computer remotely. To allow other users to connect to the local computer, give the user Execute permissions to the default session configurations on the local computer. The following command opens a property sheet that lets you change the security descriptor of the default Microsoft.PowerShell session configuration on the local computer. Set-PSSessionConfiguration Microsoft.Powershell -ShowSecurityDescriptor UI For more information, see about_Session_Configurations. HOW TO ENABLE REMOTING FOR ADMINISTRATORS IN OTHER DOMAINS ---------------------------------------------------------- ERROR: ACCESS IS DENIED When a user in another domain is a member of the Administrators group on the local computer, the user cannot connect to the local computer remotely with Administrator privileges. By default, remote connections from other domains run with only standard user privilege tokens. However, you can use the LocalAccountTokenFilterPolicy registry entry to change the default behavior and allow remote users who are members of the Administrators group to run with Administrator privileges. Caution: The LocalAccountTokenFilterPolicy entry disables user account control (UAC) remote restrictions for all users of all affected computers. Consider the implications of this setting carefully before changing the policy. To change the policy, use the following command to set the value of the LocalAccountTokenFilterPolicy registry entry to 1. C:\PS> new-itemproperty -name LocalAccountTokenFilterPolicy -path ` HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -pr opertyType ` DWord -value 1 HOW TO USE AN IP ADDRESS IN A REMOTE COMMAND ----------------------------------------------------- ERROR: The WinRM client cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting. The ComputerName parameters of the New-PSSession, Enter-PSSession and Invoke-Command cmdlets accept an IP address as a valid value. However, because Kerberos authentication does not support IP addresses, NTLM authentication is used by default whenever you specify an IP address. When using NTLM authentication, the following procedure is required for remoting. 1. Configure the computer for HTTPS transport or add the IP addresses of the remote computers to the TrustedHosts list on the local computer. For instructions, see "How to Add a Computer to the TrustedHosts List" below. 2. Use the Credential parameter in all remote commands. This is required even when you are submitting the credentials of the current user. HOW TO CONNECT REMOTELY FROM A WORKGROUP-BASED COMPUTER ------------------------------------------------------- ERROR: The WinRM client cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting. When the local computer is not in a domain, the following procedure is requ ired for remoting. 1. Configure the computer for HTTPS transport or add the names of the remote computers to the TrustedHosts list on the local computer. For instructions, see "How to Add a Computer to the TrustedHosts List" below. 2. Verify that a password is set on the workgroup-based computer. If a password is not set or the password value is empty, you cannot run remote commands. To set password for your user account, use User Accounts in Control Panel. 3. Use the Credential parameter in all remote commands. This is required even when you are submitting the credentials of the current user. HOW TO ADD A COMPUTER TO THE TRUSTED HOSTS LIST ----------------------------------------------- The TrustedHosts item can contain a comma-separated list of computer names, IP addresses, and fully-qualified domain names. Wildcards are permitted. To view or change the trusted host list, use the WSMan: drive. The TrustedHost item is in the WSMan:\localhost\Client node. Only members of the Administrators group on the computer have permission to change the list of trusted hosts on the computer. Caution: The value that you set for the TrustedHosts item affects all users of the computer. To view the list of trusted hosts, use the following command: get-item wsman:\localhost\Client\TrustedHosts You can also use the Set-Location cmdlet (alias = cd) to navigate though the WSMan: drive to the location. For example: "cd WSMan:\localhost\Client; dir". To add all computers to the list of trusted hosts, use the following command, which places a value of * (all) in the ComputerName set-item wsman:localhost\client\trustedhosts -value * You can also use a wildcard character (*) to add all computers in a particular domain to the list of trusted hosts. For example, the following command adds all of the computers in the Fabrikam domain to the list of trusted hosts. set-item wsman:localhost\client\trustedhosts *.fabrikam.com To add the names of particular computers to the list of trusted hosts, use the following command format: set-item wsman:\localhost\Client\TrustedHosts -value <ComputerName>[,<C omputerName>] where each value <ComputerName> must have the following format: <Computer>.<Domain>.<Company>. For example: set-item wsman:\localhost\Client\TrustedHosts -value Server01.Domain01. Fabrikam.com To add a computer name to an existing list of trusted hosts, first save the current value in a variable, and then set the value to a comma-separated list that includes the current and new values. For example, to add the Server01 computer to an existing list of trusted hosts, use the following command $curValue = (get-item wsman:\localhost\Client\TrustedHosts).value set-item wsman:\localhost\Client\TrustedHosts -value "$curValue, Server 01.Domain01.Fabrikam.com" To add the IP addresses of particular computers to the list of trusted host s, use the following command format: set-item wsman:\localhost\Client\TrustedHosts -value <IP Address> For example: set-item wsman:\localhost\Client\TrustedHosts -value 172.16.0.0 To add a computer to the TrustedHosts list of a remote computer, use the Connect-WSMan cmdlet to add a node for the remote computer to the WSMan: dr ive on the local computer. Then use a Set-Item command to add the computer. For more information about the Connect-WSMan cmdlet, see Connect-WSMan. TROUBLESHOOTING COMPUTER CONFIGURATION ISSUES This section discusses remoting problems that are related to particular configurations of a computer, domain, or enterprise. HOW TO CONFIGURE REMOTING ON ALTERNATE PORTS -------------------------------------------- ERROR: The connection to the specified remote host was refused. Verify that the WS-Management service is running on the remote host and configured to listen for requests on the correct port and HTTP URL. Windows PowerShell remoting uses port 80 for HTTP transport by default. The default port is used whenever the user does not specify the ConnectionURI or Port parameters in a remote command. To change the default port that Windows PowerShell uses, use Set-Item cmdle t in the WSMan: drive to change the Port value in the listener leaf node. For example, the following command changes the default port to 8080. set-item wsman:\localhost\listener\listener*\port -value 8080 HOW TO CONFIGURE REMOTING WITH A PROXY SERVER --------------------------------------------- ERROR: The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests. Because Windows PowerShell remoting uses the HTTP protocol, it is affected by HTTP proxy settings. In enterprises that have proxy servers, users cannot access a Windows PowerShell remote computer directly. To resolve this problem, use proxy setting options in your remote command. The following settings are available: -- ProxyAccessType -- ProxyAuthentication -- ProxyCredential To set these options for a particular command, use the following procedure: 1. Use the ProxyAccessType, ProxyAuthentication, and ProxyCredential parameters of the New-PSSessionOption cmdlet to create a session option object with the proxy settings for your enterprise. Save the option object is a variable. 2. Use the variable that contains the option object as the value of the SessionOption parameter of a New-PSSession, Enter-PSSession, or Invoke-Command command. For example, the following command creates a session option object with proxy session options and then uses the object to create a remote session. C:\PS> $SessionOption = New-PSSessionOption -ProxyAccessType IEConfig ` -ProxyAuthentication Negotiate -ProxyCredential Domain01\User01 C:\PS> New-PSSession -ConnectionURI https://www.fabrikam.com For more information about the New-PSSessionOption cmdlet, see New-PSSessionOption. To set these options for all remote commands in the current session, use the option object that New-PSSessionOption creates in the value of the $PSSessionOption preference variable. For more information about the $PSSessionOption preference variable, see about_Preference_Variables. To set these options for all remote commands all Windows PowerShell session s on the local computer, add the $PSSessionOption preference variable to your Windows PowerShell profile. For more information about Windows PowerShell profiles, see about_Profiles. HOW TO DETECT A 32-BIT SESSION ON A 64-BIT COMPUTER --------------------------------------------------- ERROR: The term "<tool-name>" is not recognized as the name of a cmdlet , function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and tr y again. If the remote computer is running a 64-bit version of Windows, and the remote command is using a 32-bit session configuration, such as Microsoft.PowerShell32, Windows Remote Management (WinRM) loads a WOW64 process and Windows automatically redirects all references to the %Windir%\System32 directory to the %windir%\SysWOW64 directory. As a result, if you try to use tools in the System32 directory that do not have counterparts in the SysWow64 directory, such as Defrag.exe, the tools cannot be found in the directory. To find the processor architecture that is being used in the session, use the value of the PROCESSOR_ARCHITECTURE environment variable. The following command finds the processor architecture of the session in the $s variable. C:\PS> $s = new-pssession -computername Server01 -configurationName Cus tomShell C:\PS> invoke-command -session $s {$env:PROCESSOR_ARCHITECTURE} x86 For more information about session configurations, see about_session_configurations. TROUBLESHOOTING POLICY AND PREFERENCE ISSUES This section discusses remoting problems that are related to policies and preferences set on the local and remote computers. HOW TO CHANGE THE EXECUTION POLICY FOR IMPORT-PSSESSION AND IMPORT-MODULE ------------------------------------------------------------------------- ERROR: Import-Module: File <filename> cannot be loaded because the execution of scripts is disabled on this system. The Import-PSSession and Export-PSSession cmdlets create modules that contains unsigned script files and formatting files. To import the modules that are created by these cmdlets, either by using Import-PSSession or Import-Module, the execution policy in the current session cannot be Restricted or AllSigned. (For information about Windows PowerShell execution policies, see about_Execution_Policies. To import the modules without changing the execution policy for the local computer that is set in the registry, use the Scope parameter of Set-ExecutionPolicy to set a less restrictive execution policy for a single process. For example, the following command starts a process with the RemoteSigned execution policy. The execution policy change affects only the current process and does not change the Windows PowerShell ExecutionPolicy registry setting. set-executionpolicy -scope process -executionpolicy RemoteSigned You can also use the ExecutionPolicy parameter of PowerShell.exe to start a single session with a less restrictive execution policy. powershell.exe -executionpolicy RemoteSigned For more information about the cmdlets, see Import-PSSession, Export-PSSession, and Import-Module. For more information about execution policies, see about_Execution_Policies. For more information about the PowerShell.exe console help options, type "powershell.exe -?". HOW TO SET AND CHANGE QUOTAS ---------------------------- ERROR: The total data received from the remote client exceeded allowed maximum. You can use quotas to protect the local computer and the remote computer from excessive resource use, both accidental and malicious. The following quotas are available in the basic configuration. -- The WS-Management provider (WSMan:) provides several quota settings, such as the MaxEnvelopeSizeKB and MaxProviderRequests settings in the WSMan:\<ComputerName> node and the MaxConcurrentOperations, MaxConcurrentOperationsPerUser, and MaxConnections settings in the WSMan:\<ComputerName>\Service node. -- You can protect the local computer by using the MaximumReceivedDataSizePerCommandMB and MaximumReceivedObjectSizeMB parameters of the New-PSSessionOption cmdlet and the $PSSessionOption preference variable. -- You can protect the remote computer by adding restrictions to the sessio n configurations, such as by using the MaximumReceivedDataSizePerCommandMB and MaximumReceivedObjectSizeMB parameters of the Register-PSSessionConfiguration cmdlet. When quotas conflict with a command, Windows PowerShell generates an error. To resolve the error, change the remote command to comply with the quota. Or, determine the source of the quota, and then increase the quota to allow the command to complete. For example, the following command increases the object size quota in the Microsoft.PowerShell session configuration on the remote computer from 10 M B (the default value) to 11 MB. Set-PSSessionConfiguration -name microsoft.powershell ` -MaximumReceivedObjectSizeMB 11 -Force For more information about the New-PSSsessionOption cmdlet, see New-PSSessionOption. For more information about the WS-Management quotas, see the Help topic for the WS-Management provider (type "get-help WSMan"). HOW TO RESOLVE TIMEOUT ERRORS ----------------------------- ERROR: The WS-Management service cannot complete the operation within the time specified in OperationTimeout. You can use timeouts to protect the local computer and the remote computer from excessive resource use, both accidental and malicious. When timeouts are set on both the local and remote computer, Windows PowerShell uses the shortest timeout settings. The following timeouts are available in the basic configuration. -- The WS-Management provider (WSMan:) provides several client-side and service-side timeout settings, such as the MaxTimeoutms setting in the WSMan:\<ComputerName> node and the EnumerationTimeoutms and MaxPacketRetrievalTimeSeconds settings in the WSMan:\<ComputerName>\Service node. -- You can protect the local computer by using the CancelTimeout, IdleTimeo ut, OpenTimeout, and OperationTimeout parameters of the New-PSSessionOption cmdlet and the $PSSessionOption preference variable. -- You can also protect the remote computer by setting timeout values programmatically in the session configuration for the session. When a timeout value does not permit a operation to complete, Windows PowerShell terminates the operation and generates an error. To resolve the error, change the command to complete within the timeout interval or determine the source of the timeout limit and increase the timeout interval to allow the command to complete. For example, the following commans use the New-PSSessionOption cmdlet to create a session option object with an OperationTimeout value of 4 minutes (in MS) and then use the session option object to create a remote session. C:\PS> $pso = new-pssessionoption -operationtimeout 240000 C:\PS> new-pssession -computername Server01 -sessionOption $pso For more information about the WS-Management timeouts, see the Help topic f or the WS-Management provider (type "get-help WSMan"). For more information about the New-PSSsessionOption cmdlet, see New-PSSessionOption. TROUBLESHOOTING UNRESPONSIVE BEHAVIOR This section discusses remoting problems that prevent a command from completin g and prevent or delay the return of the Windows PowerShell prompt. HOW TO INTERRUPT A COMMAND -------------------------- Some native Windows programs, such as programs with a user interface, conso le applications that prompt for input, and console applications that use the Win32 console API, do not work correctly in the Windows PowerShell remote h ost. When you use these programs, you might see unexpected behavior, such as no output, partial output, or a remote command that does not complete. To end an unresponsive program, type CTRL + C. To view any errors that migh t have been reported, type "$error" in the local host and the remote session. SEE ALSO Online version: http://go.microsoft.com/fwlink/?LinkID=135188 about_remote about_remote_requirements about_requires TOPIC about_Requires SHORT DESCRIPTION Prevents a script from running by requiring the specified snap-ins and version. LONG DESCRIPTION The #Requires statement prevents a script from running unless the Windows PowerShell version, snap-in, and snap-in version prerequisites are met. If the prerequisites are not met, Windows PowerShell does not run the script. You can use #Requires statements in any script. You cannot use them in functions, cmdlets, or snap-ins. Syntax Use the following syntax to specify the snap-in and the version of the snap-in that you want to require: #requires -PsSnapIn <PsSnapIn> [-Version <N>[.<n>]] Use the following syntax to specify the minimum version of Windows PowerShell that you want to require: #requires -Version <N>[.<n>] Use the following syntax to specify the shell that you want to require: #requires -ShellId <ShellId> Rules for Use - The #Requires statement must be the first item on a line in a script. - A script can include more than one #Requires statement. - The #Requires statements can appear on any line in a script. Examples The following statement requires the Microsoft.PowerShell.Security snap-in: #requires -PsSnapIn Microsoft.PowerShell.Security If the Microsoft.PowerShell.Security snap-in is not loaded, the script does not run, and Windows PowerShell displays the following error message: "The script '<script-name>' cannot be run because the following Windows PowerShell snap-ins that are specified by its "#requires" statements are missing: Microsoft.PowerShell.Security." The following statement requires the Windows PowerShell 2.0 version or any later version of the Microsoft.PowerShell.Security snap-in: #requires -PsSnapIn Microsoft.PowerShell.Security -Version 2 The following statement requires Windows PowerShell 2.0 or a later version: #requires -Version 2.0 The following script has two #Requires statements. The requirements specified in both statements must be met. Otherwise, the script will not run. Each #Requires statement must be the first item on a line: #requires -PsSnapIn Microsoft.PowerShell.Security -Version 2 Get-WMIObject WIN32_LogicalDisk | out-file K:\status\DiskStatus.txt #requires -Version 2 The following #Requires statement prevents a script from running if the specified shell ID does not match the current shell ID. The current shell ID is stored in the $ShellId variable: #requires -ShellId MyLocalShell SEE ALSO about_Automatic_Variables about_Language_Keywords about_PSSnapins get-PSSnapin about_Reserved_Words TOPIC about_Reserved_Words SHORT DESCRIPTION Lists the reserved words that cannot be used as identifiers because they have a special meaning in Windows PowerShell. LONG DESCRIPTION There are certain words that have special meaning in Windows PowerShell. When these words appear without quotation marks, Windows PowerShell attempts to apply their special meaning rather than treating them as character strings. To use these words as parameter arguments in a command or script without invoking their special meaning, enclose the reserved words in quotation marks. The following are the reserved words in Windows PowerShell: Break Continue Do Else Elseif Filter For Foreach Function If In Local Private Return Switch Until Where While For information about language statements, such as Foreach, If, For, and While, type "get-help", type the prefix "about_", and then type the name of the statement. For example, to get information about the Foreach statement, type: get-help about_foreach For information about the Filter statement or the Return statement syntax, type: get-help about_functions SEE ALSO about_Command_Syntax about_Escape_Characters about_Language_Keywords about_Parsing about_Quoting_Rules about_Script_Blocks about_Special_Characters about_Return TOPIC about_Return SHORT DESCRIPTION Exits the current scope, which can be a function, script, or script block. LONG DESCRIPTION The Return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached. Users who are familiar with languages like C or C# might want to use the Return keyword to make the logic of leaving a scope explicit. In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the Return keyword. Syntax The syntax for the Return keyword is as follows: return [<expression>] The Return keyword can appear alone, or it can be followed by a value or expression, as follows: return return $a return (2 + $a) Examples The following example uses the Return keyword to exit a function at a specific point if a conditional is met: function ScreenPassword($instance) { if (($instance.screensaversecure)) {return $instance.name} <additional statements> } foreach ($a in @(get-wmiobject win32_desktop)) { ScreenPassword($a) } This script checks each user account. The ScreenPassword function returns the name of any user account that does not have a password-protected screen saver. If the screen saver is password protected, the function completes any other statements to be run, and Windows PowerShell does not return any value. In Windows PowerShell, values can be returned even if the Return keyword is not used. The results of each statement are returned. For example, the following statements return the value of the $a variable: $a return The following statement also returns the value of $a: return $a The following example includes a statement intended to let the user know that the function is performing a calculation: function calculation { param ($value) "Please wait. Working on calculation..." $value += 73 return $value } Running this function and assigning the result to a variable has the following effect: C:\PS> $a = calculation 14 C:\PS> The "Please wait. Working on calculation..." string is not displayed. Instead, it is assigned to the $a variable, as in the following example: C:\PS> $a Please wait. Working on calculation... 87 Both the informational string and the result of the calculation are returned by the function and assigned to the $a variable. SEE ALSO about_Functions about_Scopes about_Script_Blocks about_scopes TOPIC about_Scopes SHORT DESCRIPTION Explains the concept of scope in Windows PowerShell and shows how to set and change the scope of elements. LONG DESCRIPTION Windows PowerShell protects access to variables, aliases, functions, and Windows PowerShell drives (PSDrives) by limiting where they can be read and changed. By enforcing a few simple rules for scope, Windows PowerShell helps to ensure that you do not inadvertently change an item that should not be changed. The following are the basic rules of scope: - An item you include in a scope is visible in the scope in which it was created and in any child scope, unless you explicitly make it private. You can place variables, aliases, functions, or Windows PowerShell drives in one or more scopes. - An item that you created within a scope can be changed only in the scope in which it was created, unless you explicitly specify a different scope. If you create an item in a scope, and the item shares its name with an item in a different scope, the original item might be hidden under the new item. But, it is not overridden or changed. Windows PowerShell Scopes Scopes in Windows PowerShell have both names and numbers. The named scopes specify an absolute scope. The numbers are relative and reflect the relationship between scopes. Global: The scope that is in effect when Windows PowerShell starts. Variables and functions that are present when Windows PowerShell starts have been created in the global scope. This includes automatic variables and preference variables. This also includes the variables, aliases, and functions that are in your Windows PowerShell profiles. Local: The current scope. The local scope can be the global scope or any other scope. Script: The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope. Private: Items in private scope cannot be seen outside of the current scope. You can use private scope to create a private version of an item with the same name in another scope. Numbered Scopes: You can refer to scopes by name or by a number that describes the relative position of one scope to another. Scope 0 represents the current, or local, scope. Scope 1 indicates the immediate parent scope. Scope 2 indicates the parent of the parent scope, and so on. Numbered scopes are useful if you have created many recursive scopes. Parent and Child Scopes You can create a new scope by running a script or function, by creating a session, or by starting a new instance of Windows PowerShell. When you create a new scope, the result is a parent scope (the original scope) and a child scope (the scope that you created). In Windows PowerShell, all scopes are child scopes of the global scope, but you can create many scopes and many recursive scopes. Unless you explicitly make the items private, the items in the parent scope are available to the child scope. However, items that you create and change in the child scope do not affect the parent scope, unless you explicitly specify the scope when you create the items. Inheritance A child scope does not inherit the variables, aliases, and functions from the parent scope. Unless an item is private, the child scope can view the items in the parent scope. And, it can change the items by explicitly specifying the parent scope, but the items are not part of the child scope. However, a child scope is created with a set of items. Typically, it includes all the aliases that have the AllScope option. This option is discussed later in this topic. It includes all the variables that have the AllScope option, plus some variables that can be used to customize the scope, such as MaximumFunctionCount. To find the items in a particular scope, use the Scope parameter of Get-Variable or Get-Alias. For example, to get all the variables in the local scope, type: get-variable -scope local To get all the variables in the global scope, type: get-variable -scope global Scope Modifiers To specify the scope of a new variable, alias, or function, use a scope modifier. The valid values of a modifier are Global and Script. The syntax for a scope modifier in a variable is: $[<scope-modifier>]:<name> = <value> The syntax for a scope modifier in a function is: function [<scope-modifier>]:<name> {<function-body>} The default scope for scripts is the script scope. The default scope for functions and aliases is the local scope, even if they are defined in a script. The following command, which does not use a scope modifier, creates a variable in the current or local scope: $a = "one" To create the same variable in the global scope, use the Global scope modifier: $global:a = "one" To create the same variable in the script scope, use the script scope modifier: $script:a = "one" You can also use a scope modifier in functions. The following function definition creates a function in the global scope: function global:Hello { write-host "Hello, World" } You can also use scope modifiers to refer to a variable in a different scope. The following command refers to the $test variable, first in the local scope and then in the global scope: $test $global:test The AllScope Option Variables and aliases have an Option property that can take a value of AllScope. Items that have the AllScope property become part of any child scopes that you create, although they are not retroactively inherited by parent scopes. An item that has the AllScope property is visible in the child scope, and it is part of that scope. Changes to the item in any scope affect all the scopes in which the variable is defined. Managing Scope Several cmdlets have a Scope parameter that lets you get or set (create and change) items in a particular scope. Use the following command to find all the cmdlets in your session that have a Scope parameter: get-help * -parameter scope To find the variables that are visible in a particular scope, use the Scope parameter of Get-Variable. The visible parameters include global parameters, parameters in the parent scope, and parameters in the current scope. For example, the following command gets the variables that are visible in the local scope: get-variable -scope local To create a variable in a particular scope, use a scope modifier or the Scope parameter of Set-Variable. The following command creates a variable in the global scope: new-variable -scope global -name a -value "One" You can also use the Scope parameter of the New-Alias, Set-Alias, or Get-Alias cmdlets to specify the scope. The following command creates an alias in the global scope: new-alias -scope global -name np -value Notepad.exe To get the functions in a particular scope, use the Get-Item cmdlet when you are in the scope. The Get-Item cmdlet does not have a scope parameter. Using Dot Source Notation with Scope Scripts and functions follow all the rules of scope. You create them in a particular scope, and they affect only that scope unless you use a cmdlet parameter or a scope modifier to change that scope. But, you can add a script or function to the current scope by using dot source notation. Then, when a script runs in the current scope, any functions, aliases, and variables that the script creates are available in the current scope. To add a function to the current scope, type a dot (.) and a space before the path and name of the function in the function call. For example, to run the Sample.ps1 script from the C:\Scripts directory in the script scope (the default for scripts), use the following command: c:\scripts\sample.ps1 To run the Sample.ps1 script in the local scope, use the following command: . c:\scripts.sample.ps1 When you use the call operator (&) to run a function or script, it is not added to the current scope. The following example uses the call operator: & c:\scripts.sample.ps1 Any aliases, functions, or variables that the Sample.ps1 script creates are not available in the current scope. Restricting Without Scope A few Windows PowerShell concepts are similar to scope or interact with scope. These concepts may be confused with scope or the behavior of scope. Sessions, modules, and nested prompts are self-contained environments, but they are not child scopes of the global scope in the session. Sessions: A session is an environment in which Windows PowerShell runs. When you create a session on a remote computer, Windows PowerShell establishes a persistent connection to the remote computer. The persistent connection lets you use the session for multiple related commands. Because a session is a contained environment, it has its own scope, but a session is not a child scope of the session in which is was created. The session starts with its own global scope. This scope is independent of the global scope of the session. You can create child scopes in the session. For example, you can run a script to create a child scope in a session. Modules: You can use a Windows PowerShell module to share and deliver Windows PowerShell tools. A module is a unit that can contain cmdlets, scripts, functions, variables, aliases, and other useful items. Unless explicitly defined, the items in a module are not accessible outside the module. Therefore, you can add the module to your session and use the public items without worrying that the other items might override the cmdlets, scripts, functions, and other items in your session. The privacy of a module behaves like a scope, but adding a module to a session does not change the scope. And, the module does not have its own scope, although the scripts in the module, like all Windows PowerShell scripts, do have their own scope. Nested Prompts: Similarly, nested prompts do not have their own scope. When you enter a nested prompt, the nested prompt is a subset of the environment. But, you remain within the local scope. Scripts do have their own scope. If you are debugging a script, and you reach a breakpoint in the script, you enter the script scope. Private Option: Aliases and variables have an Option property that can take a value of Private. Items that have the Private option can be viewed and changed in the scope in which they are created, but they cannot be viewed or changed outside that scope. For example, if you create a variable that has a private option in the global scope and then run a script, Get-Variable commands in the script do not display the private variable. This occurs even if you use the global scope modifier. You can use the Option parameter of the New-Variable, Set-Variable, New-Alias, and Set-Alias cmdlets to set the value of the Option property to Private. Visibility: The Visibility property of a variable or alias determines whether you can see the item outside the container, such as a module, in which it was created. Visibility is designed for containers in the same way that the Private value of the Option property is designed for scopes. The Visibility property takes the Public and Private values. Items that have private visibility can be viewed and changed only in the container in which they were created. If the container is added or imported, the items that have private visibility cannot be viewed or changed. Because Visibility is designed for containers, it works differently in a scope. If you create an item that has private visibility in the global scope, you cannot view or change the item in any scope. If you try to view or change the value of a variable that has private visibility, Windows PowerShell returns an error message. You can use the New-Variable and Set-Variable cmdlets to create a variable that has private visibility. EXAMPLES Example 1: Change a Variable Value Only in a Script The following command changes the value of the $ConfirmPreference variable in a script. The change does not affect the global scope. First, to display the value of the $ConfirmPreference variable in the local scope, use the following command: C:\PS> $ConfirmPreference High Create a Scope.ps1 script that contains the following commands: $ConfirmPreference = "Low" "The value of `$ConfirmPreference is $ConfirmPreference." Run the script. The script changes the value of the $ConfirmPreference variable and then reports its value in the script scope. The output should resemble the following output: The value of $ConfirmPreference is Low. Next, test the current value of the $ConfirmPreference variable in the current scope. C:\PS> $ConfirmPreference High This example shows that changes to the value of a variable in the script scope do not affect the value of that variable in the parent scope. Example 2: View a Variable Value in Different Scopes You can use scope modifiers to view the value of a variable in the local scope and in a parent scope. First, define a $test variable in the global scope. $test = "Global" Next, create a Sample.ps1 script that defines the $test variable. In the script, use a scope modifier to refer to either the global or local versions of the $test variable. # In Sample.ps1 $test = "Local" "The local value of `$test is $test." "The global value of `$test is $global:test." When you run Sample.ps1, the output should resemble the following output: The local value of $test is Local. The global value of $test is Global. When the script is complete, only the global value of $test is defined in the session. C:\PS> $test Global Example 3: Change the Value of a Variable in a Parent Scope Unless you protect an item by using the Private option or another method, you can view and change the value of a variable in a parent scope. First, define a $test variable in the global scope. $test = "Global" Next, create a Sample.ps1 script that defines the $test variable. In the script, use a scope modifier to refer to either the global or local versions of the $test variable. # In Sample.ps1 $global:test = "Local" "The global value of `$test is $global:test." When the script is complete, the global value of $test is changed. C:\PS> $test Local Example 4: Creating a Private Variable A private variable is a variable that has an Option property that has a value of Private. Private variables are inherited by the child scope, but they can be viewed or changed only in the scope in which they were created. The following command creates a private variable called $ptest in the local scope. new-variable -name ptest -value 1 -option private You can display and change the value of $ptest in the local scope. C:\PS> $ptest 1 C:\PS> $ptest = 2 C:\PS> $ptest 2 Next, create a Sample.ps1 script that contains the following commands. The command tries to display and change the value of $ptest. # In Sample.ps1 "The value of `$Ptest is $Ptest." "The value of `$Ptest is $global:Ptest." Because the $ptest variable is not visible in the script scope, the output is empty. "The value of $Ptest is ." "The value of $Ptest is ." SEE ALSO about_Variables about_Environment_Variables about_Functions about_Script_Blocks about_script_blocks TOPIC about_Script_Blocks SHORT DESCRIPTION Defines what a script block is and explains how to use script blocks in the Windows PowerShell programming language. LONG DESCRIPTION In the Windows PowerShell programming language, a script block is a collection of statements or expressions that can be used as a single unit. A script block can accept arguments and return values. Syntactically, a script block is a statement list in braces, as shown in the following syntax: {<statement list>} A script block returns the output of all the commands in the script block, either as a single object or as an array. Like functions, a script block can include parameters. Use the Param keyword to assign named parameters, as shown in the following syntax: { param ([type]$parameter1 [,[type]$parameter2]) <statement list> } In a script block, unlike a function, you cannot specify parameters outside the braces. Like functions, script blocks can include the DynamicParam, Begin, Process, and End keywords. For more information, see about_Functions and about_Functions_Advanced. Using Script Blocks A script block is an instance of a Microsoft .NET Framework type (System.Management.Automation.ScriptBlock). Commands can have script block parameter values. For example, the Invoke-Command cmdlet has a ScriptBlock parameter that takes a script block value, as shown in this example: C:\PS> invoke-command -scriptblock { get-process } Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 999 28 39100 45020 262 15.88 1844 communicator 721 28 32696 36536 222 20.84 4028 explorer . . . The script block that is used as a value can be more complicated, as shown in the following example: C:\PS> invoke-command -scriptblock { param ($uu = "Parameter"); "$uu assigned." } Parameter assigned. The script block in the preceding example uses the Param keyword to create a parameter that has a default value. The following example uses the Args parameter of the Invoke-Command cmdlet to assign a different value to the parameter: C:\PS> invoke-command -scriptblock {param ($uu = "Parameter"); "$uu assigned."} -args "Other value" Other value assigned. You can assign a script block to a variable, as shown in the following example: C:\PS> $a = {param ($uu = "Parameter"); "$uu assigned."} You can use the variable with a cmdlet such as Invoke-Command, as shown in the following example: C:\PS> invoke-command -scriptblock $a -args "Other value" Other value assigned. You can run a script block that is assigned to a variable by using the call operator (&), as shown in the following example: C:\PS> &$a Parameter assigned. You can also provide a parameter to the script block, as shown in the following example: C:\PS> &$a "Other value" Other value assigned. If you want to assign the value that is created by a script block to a variable, use the call operator to run the script block directly, as shown in the following example: C:\PS> $a = &{param ($uu = "Parameter"); "$uu assigned."} C:\PS> $a Parameter assigned. For more information about the call operator, see about_Operators. SEE ALSO about_Functions about_Functions_Advanced about_Operators about_script_internationalization TOPIC about_Script_Internationalization SHORT DESCRIPTION Describes the script internationalization features of Windows PowerShell 2. 0 that make it easy for scripts to display messages and instructions to users in their user interface (UI) language. LONG DESCRIPTION The Windows PowerShell script internationalization features allow you to better serve users throughout the world by displaying Help and user messages for scripts and functions in the user's UI language. The script internationalization features query the UI culture of the operating system during execution, import the appropriate translated text strings, and display them to the user. The Data section lets you store text strings separate from code so they are easily identified and extracted. A new cmdlet, ConvertFrom-StringData, converts text strings into dictionary-like hash tables to facilitate translation. The Windows PowerShell 2.0 features used in script internationalization are not supported by Windows PowerShell 1.0. Scripts that include these features will not run in Windows PowerShell 1.0 without modification. To support international Help text, Windows PowerShell 2.0 includes the following features: -- A Data section that separates text strings from code instructions. Fo r more information about the Data section, see about_Data_Sections. -- New automatic variables, $PSCulture and $PSUICulture. $PSCulture stor es the name of the UI language used on the system for elements such as the date, time, and currency. The $PSUICulture variable stores the name of the UI language used on the system for user interface element s such as menus and text strings. -- A cmdlet, ConvertFrom-StringData, that converts text strings into dictionary-like hash tables to facilitate translation. For more information, see ConvertFrom-StringData. -- A new file type, .psd1, that stores translated text strings. The .psd 1 files are stored in language-specific subdirectories of the script directory. -- A cmdlet, Import-LocalizedData, that imports translated text strings for a specified language into a script at runtime. This cmdlet recogn izes and imports strings in any Windows-supported language. For more information see Import-LocalizedData. THE DATA SECTION: Storing Default Strings Use a Data section in the script to store the text strings in the default language. Arrange the strings in key/value pairs in a here-string. Each key/value pa ir must be on a separate line. If you include comments, the comments must be on se parate lines. The ConvertFrom-StringData cmdlet converts the key/value pairs in the here -string into a dictionary-like hash table that is stored in the value of the Data section variable. In the following example, the Data section of the World.ps1 script include s the English-United States (en-US) set of prompt messages for a script. The ConvertFrom-StringData cmdlet converts the strings into a hash table and s tores them in the $msgtable variable. $msgTable = Data { # culture="en-US" ConvertFrom-StringData @' helloWorld = Hello, World. errorMsg1 = You cannot leave the user name field blank. promptMsg = Please enter your user name. '@ } For more information about here-strings, see about_Quoting_Rules. PSD1 FILES: Storing Translated Strings Save the script messages for each UI language in separate text files with the same name as the script and the .psd1 file name extension. Store the fi les in subdirectories of the script directory with names of cultures in the fol lowing format: <language>-<region> Examples: de-DE, ar-SA, and zh-Hans For example, if the World.ps1 script is stored in the C:\Scripts directory, you would create a file directory structure that resembles the following: C:\Scripts C:\Scripts\World.ps1 C:\Scripts\de-DE\World.psd1 C:\Scripts\ar-SA\World.psd1 C:\Scripts\zh-CN\World.psd1 ... The World.psd1 file in the de-DE subdirectory of the script directory might include the following statement: ConvertFrom-StringData @' helloWorld = Hello, World (in German). errorMsg1 = You cannot leave the user name field blank (in German). promptMsg = Please enter your user name (in German). '@ Similarly, the World.psd1 file in the ar-SA subdirectory of the script dire ctory might includes the following statement: ConvertFrom-StringData @' helloWorld = Hello, World (in Arabic). errorMsg1 = You cannot leave the user name field blank (in Arabic). promptMsg = Please enter your user name (in Arabic). '@ IMPORT-LOCALIZEDDATA: Dynamic Retrieval of Translated Strings To retrieve the strings in the UI language of the current user, use the Import-LocalizedData cmdlet. Import-LocalizedData finds the value of the $PSUICulture automatic variable and imports the content of the <script-name>.psd1 files in the subdirectory that matches the $PSUICulture value. Then, it saves the imported content in the variable specified by the value of the BindingVariable parameter. import-localizeddata -bindingVariable msgTable For example, if the Import-LocalizedData command appears in the C:\Scripts\World.ps1 script and the value of $PSUICulture is "ar-SA", Import-LocalizedData finds the following file: C:\Scripts\ar-SA\World.psd1 Then, it imports the Arabic text strings from the file into the $msgTable variable, replacing any default strings that might be defined in the Data section of the World.ps1 script. As a result, when the script uses the $msgTable variable to display user messages, the messages are displayed in Arabic. For example, the following script displays the "Please enter your user name" message in Arabic: if (($username)) { $msgTable.promptMsg } If Import-LocalizedData cannot find a .psd1 file that matches the value of $PSUIculture, the value of $msgTable is not replaced, and the call to $msgTable.promptMsg displays the fallback en-US strings. ExAMPLE This example shows how the script internationalization features are used in a script to display a day of the week to users in the language that is set on the computer. The following is a complete listing of the Sample1.ps1 script file. The script begins with a Data section named Day ($Day) that contains a ConvertFrom-StringData command. The expression submitted to ConvertFrom-StringData is a here-string that contains the day names in the default UI culture, en-US, in key/value pairs. The ConvertFrom-StringData cmdlet converts the key/value pairs in the here-string into a hash table and then saves it in the value of the $Day variable. The Import-LocalizedData command imports the contents of the .psd1 file in the directory that matches the value of the $PSUICulture automatic variable and then saves it in the $Day variable, replacing the values of $Day that are defined in the Data section. The remaining commands load the strings into an array and display them. $Day = DATA { # culture="en-US" ConvertFrom-StringData @' messageDate = Today is d1 = Monday d2 = Tuesday d3 = Wednesday d4 = Thursday d5 = Friday d6 = Saturday d7 = Sunday '@ } Import-LocalizedData -BindingVariable Day # Build an array of weekdays. $a = $Day.d1, $Day.d2, $Day.d3, $Day.d4, $Day.d5, $Day.d6, $Day.d7 # Get the day of the week as a number (Monday = 1). # Index into $a to get the name of the day. # Use string formatting to build a sentence. "{0} {1}" -f $Day.messageDate, $a[(get-date -uformat %u)] | Out-Host The .psd1 files that support the script are saved in subdirectories of the script directory with names that match the $PSUICulture values. The following is a complete listing of .\de-DE\sample1.psd1: # culture="en-US" ConvertFrom-StringData @' messageDate = Today is d1 = Monday (in German) d2 = Tuesday (in German) d3 = Wednesday (in German) d4 = Thursday (in German) d5 = Friday (in German) d6 = Saturday (in German) d7 = Sunday (in German) '@ As a result, when you run Sample.ps1 on a system on which the value of $PSUICulture is de-DE, the output of the script is: Today is Friday (in German) SEE ALSO about_Data_Sections about_Automatic_Variables about_Hash_Tables about_Quoting_Rules ConvertFrom-StringData Import-LocalizedData about_scripts TOPIC about_Scripts SHORT DESCRIPTION Describes how to write and run scripts in Windows PowerShell. LONG DESCRIPTION A script is a plain text file that contains one or more Windows PowerShell commands. Windows PowerShell scripts have a .ps1 file name extension. Writing a script saves a command for later use and makes it easy to share with others. Most importantly, it lets you run the commands simply by typin g the script path and the file name. Scripts can be as simple as a single command in a file or as extensive as a complex program. Scripts have additional features, such as the #Requires special comment, the use of parameters, support for data sections, and digital signing for security. You can also write Help topics for scripts and for any functions in the script. HOW TO WRITE A SCRIPT A script can contain any valid Windows PowerShell commands, including singl e commands, commands that use the pipeline, functions, and control structures such as If statements and For loops. To write a script, start a text editor (such as Notepad) or a script editor (such as the Windows PowerShell Integrated Scripting Environment [ISE]). Ty pe the commands and save them in a file with a valid file name and the .ps1 fi le name extension. The following example is a simple script that gets the services that are running on the current system and saves them to a log file. The log file na me is created from the current date. $date = (get-date).dayofyear get-service | out-file "$date.log" To create this script, open a text editor or a script editor, type these commands, and then save them in a file named ServiceLog.ps1. HOW TO RUN A SCRIPT Before you can run a script, you need to change the default Windows PowerShell execution policy. The default execution policy, "Restricted", prevents all scripts from running, including scripts that you write on the local computer. For more information, see about_Execution_Policies. To run a script, type the full name and the full path to the script file. For example, to run the ServicesLog script in the C:\Scripts directory, typ e: c:\scripts\ServicesLog.ps1 To run a script in the current directory, type the path to the current directory, or use a dot to represent the current directory, followed by a path backslash (.\). For example, to run the ServicesLog.ps1 script in the local directory, type : .\ServicesLog.ps1 As a security feature, Windows PowerShell does not run scripts when you double-click the script icon in Windows Explorer or when you type the script name without a full path, even when the script is in the current directory. For more information about running commands and scripts in Windows PowerShell, see about_Command_Precedence. RUNNING SCRIPTS REMOTELY To run a script on a remote computer, use the FilePath parameter of the Invoke-Command cmdlet. Enter the path and file name of the script as the value of the FilePath parameter. The script must reside on the local computer or in a directory that the local computer can access. The following command runs the ServicesLog.ps1 script on the Server01 remot e computer. invoke-command -computername Server01 -filepath C:\scripts\servicesLog. ps1 PARAMETERS IN SCRIPTS To define parameters in a script, use a Param statement. The Param statemen t must be the first statement in a script, except for comments and any #Requires statements. Script parameters work like function parameters. The parameter values are available to all of the commands in the script. All of the features of function parameters, including the Parameter attribute and its named arguments, are also valid in scripts. When running the script, script users type the parameters after the script name. The following example shows a Test-Remote.ps1 script that has a ComputerNam e parameter. Both of the script functions can access the ComputerName parameter value. param ($ComputerName = $(throw "ComputerName parameter is required.")) function CanPing { $error.clear() $tmp = test-connection $computername -erroraction SilentlyContinue if ($?) {write-host "Ping failed: $ComputerName."; return $false} else {write-host "Ping succeeded: $ComputerName"; return $true} } function CanRemote { $s = new-pssession $computername -erroraction SilentlyContinue if ($s -is [System.Management.Automation.Runspaces.PSSession]) {write-host "Remote test succeeded: $ComputerName."} else {write-host "Remote test failed: $ComputerName."} } if (CanPing $computername) {CanRemote $computername} To run this script, type the parameter name after the script name. For example: C:\PS> .\test-remote.ps1 -computername Server01 Ping succeeded: Server01 Remote test failed: Server01 For more information about the Param statement and the function parameters, see about_Functions and about_Functions_Advanced_Parameters. HELP FOR SCRIPTS The Get-Help cmdlet gets Help for scripts as well as for cmdlets, providers, and functions. To get Help for a script, type Get-Help and the path and file name of the script. If the script path is in your Path environment variable, you can omit the path. For example, to get Help for the ServicesLog.ps1 script, type: get-help C:\admin\scripts\ServicesLog.ps1 You can write Help for a script by using either of the two following method s: -- Comment-Based Help for Scripts Create a Help topic by using special keywords in the comments. To creat e comment-based Help for a script, the comments must be placed at the beginning or end of the script file. For more information about comment-based Help, see about_Comment_Based_Help. -- XML-Based Help for Scripts Create an XML-based Help topic, such as the type that is typically created for cmdlets. XML-based Help is required if you are translating Help topics into multiple languages. To associate the script with the XML-based Help topic, use the .ExternalHelp Help comment keyword. For more information about the ExternalHelp keyword, see about_Comment_Based_Help. For more informatio n about XML-based help, see "How to Write Cmdlet Help" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkID=123415. SCRIPT SCOPE AND DOT SOURCING Each script runs in its own scope. The functions, variables, aliases, and drives that are created in the script exist only in the script scope. You cannot access these items or their values in the scope in which the script runs. To run a script in a different scope, you can specify a scope, such as Global or Local, or you can dot source the script. The dot sourcing feature lets you run a script in the current scope instead of in the script scope. When you run a script that is dot sourced, the commands in the script run as though you had typed them at the command prompt. The functions, variables, aliases, and drives that the script creates are created in the scope in which you are working. After the script runs, you can use the created items and access their values in your session . To dot source a script, type a dot (.) and a space before the script path. For example: . C:\scripts\UtilityFunctions.ps1 -or- . .\UtilityFunctions.ps1 After the UtilityFunctions script runs, the functions and variables that th e script creates are added to the current scope. For example, the UtilityFunctions.ps1 script creates the New-Profile function and the $ProfileName variable. #In UtilityFunctions.ps1 function New-Profile { Write-Host "Running New-Profile function" $profileName = split-path $profile -leaf if (test-path $profile) {write-error "There is already a $profileName profile on this co mputer."} else {new-item -type file -path $profile -force } } If you run the UtilityFunctions.ps1 script in its own script scope, the New-Profile function and the $ProfileName variable exist only while the script is running. When the script exits, the function and variable are removed, as shown in the following example. C:\PS> .\UtilityFunctions.ps1 C:\PS> New-Profile The term 'new-profile' is not recognized as a cmdlet, function, operabl e program, or script file. Verify the term and try again. At line:1 char:12 + new-profile < + CategoryInfo : ObjectNotFound: (new-profile:String) [], + FullyQualifiedErrorId : CommandNotFoundException C:\PS> $profileName C:\PS> When you dot source the script and run it, the script creates the New-Profile function and the $ProfileName variable in your session in your scope. After the script runs, you can use the New-Profile function in your session, as shown in the following example. C:\PS> . .\UtilityFunctions.ps1 C:\PS> New-Profile Directory: C:\Users\juneb\Documents\WindowsPowerShell Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 1/14/2009 3:08 PM 0 Microsoft.PowerShellISE_profile.ps 1 C:\PS> $profileName Microsoft.PowerShellISE_profile.ps1 For more information about scope, see about_Scopes. SCRIPTS IN MODULES A module is a set of related Windows PowerShell resources that can be distributed as a unit. You can use modules to organize your scripts, functions, and other resources. You can also use modules to distribute your code to others, and to get code from trusted sources. You can include scripts in your modules, or you can create a script module, which is a module that consists entirely or primarily of a script and supporting resources. A script module is just a script with a .psm1 file name extension. For more information about modules, see about_Modules. OTHER SCRIPT FEATURES Windows PowerShell has many useful features that you can use in scripts. #Requires You can use a #Requires statement to prevent a script from running without specified modules or snap-ins and a specified version of Windows PowerShell. For more information, see about_Requires. $MyInvocation The $MyInvocation automatic variable contains information about the current command, including the current script. You can use this variabl e and its properties to get information about the script while it is running. For example, the $MyInvocation.MyCommand.Path variable contain s the path and file name of the script. Data sections You can use the Data keyword to separate data from logic in scripts. Data sections can also make localization easier. For more information, see about_Data_Sections and about_Script_Localization. Script Signing You can add a digital signature to a script. Depending on the execution policy, you can use digital signatures to restrict the running of scrip ts that could include unsafe commands. For more information, see about_Execution_Policies and about_Signing. SEE ALSO about_Command_Precedence about_Comment_Based_Help about_Execution_Policies about_Functions about_Modules about_Profiles about_Requires about_Scopes about_Script_Blocks about_Signing Invoke-Command about_Session_Configurations TOPIC about_Session_Configurations SHORT DESCRIPTION Describes session configurations, which determine the users who can connect to the computer remotely and the commands they can run. LONG DESCRIPTION A session configuration is a group of settings on the local computer that define the environment for the Windows PowerShell sessions that are created when remote users connect to the local computer. Administrators of the computer can use session configurations to protect the computer and to define custom environments for users who connect to the computer. Administrators can also use session configurations to determine the permissions that are required to connect to the computer remotely. By default, only members of the Administrators group have permission to use the session configuration to connect remotely, but you can change the default settings to allow all users, or selected users, to connect remotely to your computer. Session configurations are a feature of Web Services for Management (WS-Management) based Windows PowerShell remoting. They are used only when you use the New-PSSession, Invoke-Command, or Enter-PSSession cmdlets to connect to a remote computer. Note: To manage the session configurations on a computer that is running Windows Vista, Windows Server 2008, or a later version of Windows, start Windows PowerShell with the "Run as administrator" option. About Session Configurations Every Windows PowerShell session uses a session configuration. This includes persistent sessions that you create by using the New-PSSession or Enter-PSSession cmdlets, and the temporary sessions that Windows PowerShell creates when you use the ComputerName parameter of a cmdlet that uses WS-Management-based remoting technology, such as Invoke-Command. Administrators can use session configurations to protect the resources of the computer and to create custom environments for users who connect to the computer. For example, you can use a session configuration to limit the size of objects that the computer receives in the session, to define the language mode of the session, and to specify the cmdlets, providers, and functions that are available in the session. By configuring the security descriptor of a session configuration, you determine who can use the session configuration to connect to the computer. Users must have Execute permission to a session configuration to use it in a session. If a user does not have the required permissions to use any of the session configurations on a computer, the user cannot connect to the computer remotely. By default, only Administrators of the computer have permission to use the default session configurations. But, you can change the security descriptors to allow everyone, no one, or only selected users to use the session configurations on your computer. Default Session Configurations Windows PowerShell includes a built-in session configuration named Microsoft.PowerShell. On computers running 64-bit versions of Windows, Windows PowerShell also provides Microsoft.PowerShell32, a 32-bit session configuration. These session configurations are used for sessions by default, that is, when a command to create a session does not include the ConfigurationName parameter of the New-PSSession, Enter-PSSession, or Invoke-Command cmdlet. The security descriptors for the default session configurations allow only members of the Administrators group on the local computer to use them. As such, only members of the Administrators group can connect to the computer remotely unless you change the default settings. You can change the default session configurations by using the $PSSessionConfigurationName preference variable. For more information, see about_Preference_Variables. Viewing Session Configurations on the Local Computer To get the session configurations on your local computer, use the Get-PSSessionConfiguration cmdlet. For example, type: C:\PS> get-pssessionconfiguration | format-list -property name, permiss ion Name : microsoft.powershell Permission : BUILTIN\Administrators AccessAllowed Name : microsoft.powershell32 Permission : BUILTIN\Administrators AccessAllowed You can also use the WS-Management provider in Windows PowerShell to view session configurations. The WS-Management provider creates a WSMAN: drive in your session. In the WSMAN: drive, session configurations are in the Plugin node. (All session configurations are in the Plugin node, but there are items in the Plugin node that are not session configurations.) For example, to view the session configurations on the local computer, type: C:\PS> dir wsman:\localhost\plugin\microsoft* WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Pl ugin Name Type Keys ---- ---- ---- microsoft.powershell Container {Name=microsoft.powersh ell} microsoft.powershell32 Container {Name=microsoft.powersh ell} Viewing Session Configurations on a Remote Computer To view the session configurations on a remote computer, use the Connect-WSMan cmdlet to add a note for the remote computer to the WSMAN: drive on your local computer, and then use the WSMAN: drive to view the session configurations. For example, the following command adds a node for the Server01 remote computer to the WSMAN: drive on the local computer. C:\PS> connect-wsman server01.corp.fabrikam.com When the command is complete, you can navigate to the node for the Server01 computer to view the session configurations. For example: C:\PS> cd wsman: PS WSMan:\> dir ComputerName Type ------------ ---- localhost Container server01.corp.fabrikam.com Container PS WSMan:\> dir server01*\plugin\* WSManConfig: Microsoft.WSMan.Management\WSMan::server01.corp.fab rikam.com\Plugin Name Type Keys ---- ---- ---- microsoft.powershell Container {Name=microsoft.powershell} microsoft.powershell32 Container {Name=microsoft.powershell32} Changing the Security Descriptor of a Session Configuration By default, members of the Administrators group on the computer have Execute permission to the default session configurations, but you can change the security descriptors on the default session configurations and on any session configurations that you create. To give other users permission to connect to the computer remotely, use the Set-PSSessionConfiguration cmdlet to add "Execute" permissions for those users to the security descriptors of the Microsoft.PowerShell and Microsoft.PowerShell32 session configurations. For example, the following command opens a property page that lets you change the security descriptor for the Microsoft.PowerShell default session configuration. C:\PS> set-pssessionConfiguration -name Microsoft.PowerShell -showSecur ityDescriptorUI To deny everyone permission to all the session configurations on the computer, use the Disable-PSRemoting function or the Disable-PSSessionConfiguration cmdlet. For example, the following command adds a "Deny All" entry to all the session configurations on the computer. C:\PS> disable-psremoting To add a "Deny All" entry to a particular session configuration, use the Disable-PSSessionConfiguration cmdlet. For example, the following command adds a "Deny All" entry to the Microsoft.PowerShell session configuration. C:\PS> disable-pssessionConfiguration -name Microsoft.PowerShell To remove the "Deny All" entry from all the session configurations, use the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. For example, the following command removes the "Deny All" entry from the default session configurations. C:\PS> enable-pssessionConfiguration -name Microsoft.Power* To make other changes to the security descriptor of a session configuration, use the Set-PSSessionConfiguration cmdlet. Use the SecurityDescriptorSDDL parameter to submit an SDDL string value. Use the ShowSecurityDescriptorUI parameter to display a user interface property sheet that helps you to create a new SDDL. For example: C:\PS> set-pssessionConfiguration -name Microsoft.PowerShell -showSecur ityDescriptorUI Creating a New Session Configuration To create a new session configuration on the local computer, use the Register-PSSessionConfiguration cmdlet. To define the new session configuration, you can use a C# assembly, a Window PowerShell script, and the parameters of the Register-PSSessionConfiguration cmdlet. For example, the following command creates a session configuration that is identical the Microsoft.PowerShell session configuration, except that it limits the data received from a remote command to 20 megabytes (MB). (The default is 50 MB). c:\PS> register-psSessionConfiguration -name NewConfig --MaximumReceive dDataSizePerCommandMB 20 When you create a session configuration, you can manage it by using the other session configuration cmdlets, and it appears in the WSMAN: drive. For more information, see Register-PSSessionConfiguration. Removing a Session Configuration To remove a session configuration from the local computer, use the Unregister-PSSessionConfiguration cmdlet. For example, the following command removes the NewConfig session configuration from the computer. c:\PS> unregister-psSessionConfiguration -name NewConfig For more information, see Unregister-PSSessionConfiguration. Selecting a Session Configuration To select a particular session configuration for a session, use the ConfigurationName parameter of New-PSSession, Enter-PSSession, or Invoke-Command. For example, this command uses the New-PSSession cmdlet to start a PSSession on the Server01 computer. The command uses the ConfigurationName parameter to select the WithProfile configuration on the Server01 computer. C:\PS> new-pssession -computername Server01 -configurationName WithProf ile This command will succeed only if the current user has permission to use the WithProfile session configuration or can supply the credentials of a user who has the required permissions. You can also use the $PSSessionConfigurationName preference variable to change the default session configuration on the computer. For more information about the $PSSessionConfigurationName preference variable, see about_Preference_Variables. SEE ALSO about_Preference_Variables about_PSSession about_Remote New-PSSession Disable-PSSessionConfiguration Enable-PSSessionConfiguration Get-PSSessionConfiguration Register-PSSessionConfiguration Set-PSSessionConfiguration Unregister-PSSessionConfiguration about_Signing TOPIC about_signing SHORT DESCRIPTION Explains to how sign scripts so that they comply with the Windows PowerShell execution policies. LONG DESCRIPTION The Restricted execution policy does not permit any scripts to run. The AllSigned and RemoteSigned execution policies prevent Windows PowerShell from running scripts that do not have a digital signature. This topic explains how to run selected scripts that are not signed, even while the execution policy is RemoteSigned, and how to sign scripts for your own use. For more information about Windows PowerShell execution policies, see about_Execution_Policy. TO PERMIT SIGNED SCRIPTS TO RUN ------------------------------- When you start Windows PowerShell on a computer for the first time, the Restricted execution policy (the default) is likely to be in effect. The Restricted policy does not permit any scripts to run. To find the effective execution policy on your computer, type: get-executionpolicy To run unsigned scripts that you write on your local computer and signed scripts from other users, use the following command to change the execution policy on the computer to RemoteSigned: set-executionpolicy remotesigned For more information, see Set-ExecutionPolicy. RUNNING UNSIGNED SCRIPTS (REMOTESIGNED EXECUTION POLICY) -------------------------------------------------------- If your Windows PowerShell execution policy is RemoteSigned, Windows PowerShell will not run unsigned scripts that are downloaded from the Internet, including unsigned scripts you receive through e-mail and instant messaging programs. If you try to run a downloaded script, Windows PowerShell displays the following error message: The file <file-name> cannot be loaded. The file <file-name> is not digitally signed. The script will not execute on the system. Please see "Get-Help about_signing" for more details. Before you run the script, review the code to be sure that you trust it. Scripts have the same effect as any executable program. To run an unsigned script: 1. Save the script file on your computer. 2. Click Start, click My Computer, and locate the saved script file. 3. Right-click the script file, and then click Properties. 4. Click Unblock. If a script that was downloaded from the Internet is digitally signed, but you have not yet chosen to trust its publisher, Windows PowerShell displays the following message: Do you want to run software from this untrusted publisher? The file <file-name> is published by CN=<publisher-name>. This publisher is not trusted on your system. Only run scripts from trusted publishers. [V] Never run [D] Do not run [R] Run once [A] Always run [?] Help (default is "D"): If you trust the publisher, select "Run once" or "Always run." If you do not trust the publisher, select either "Never run" or "Do not run." If you select "Never run" or "Always run," Windows PowerShell will not prompt you again for this publisher. METHODS OF SIGNING SCRIPTS -------------------------- You can sign the scripts that you write and the scripts that you obtain from other sources. Before you sign any script, examine each command to verify that it is safe to run. For best practices about code signing, see "Code-Signing Best Practices" at http://go.microsoft.com/fwlink/?LinkId=119096. For more information about how to sign a script file, see Set-AuthenticodeSignature. To add a digital signature to a script, you must sign it with a code signing certificate. Two types of certificates are suitable for signing a script file: -- Certificates that are created by a certification authority: For a fee, a public certificate authority verifies your identity and gives you a code signing certificate. When you purchase your certificate from a reputable certification authority, you are able to share your script with users on other computers that are running Windows because those other computers trust the certification authority. -- Certificates that you create: You can create a self-signed certificate for which your computer is the authority that creates the certificate. This certificate is free of charge and enables you to write, sign, and run scripts on your computer. However, a script signed by a self-signed certificate will not run on other computers. Typically, you would use a self-signed certificate only to sign scripts that you write for your own use and to sign scripts that you get from other sources that you have verified to be safe. It is not appropriate for scripts that will be shared, even within an enterprise. If you create a self-signed certificate, be sure to enable strong private key protection on your certificate. This prevents malicious programs from signing scripts on your behalf. The instructions are included at the end of this topic. CREATE A SELF-SIGNED CERTIFICATE -------------------------------- To create a self-signed certificate, use the Certificate Creation tool (MakeCert.exe). This tool is included in the Microsoft .NET Framework SDK (versions 1.1 and later) and in the Microsoft Windows SDK. For more information about the syntax and the parameter descriptions of the MakeCert.exe tool, see "Certificate Creation Tool (MakeCert.exe)" in the MSDN (Microsoft Developer Network) library at http://go.microsoft.com/fwlink/?LinkId=119097. To use the MakeCert.exe tool to create a certificate, run the following commands in an SDK Command Prompt window. Note: The first command creates a local certification authority for your computer. The second command generates a personal certificate from the certification authority. Note: You can copy or type the commands exactly as they appear. No substitutions are necessary, although you can change the certificate name. makecert -n "CN=PowerShell Local Certificate Root" -a sha1 ` -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer ` -ss Root -sr localMachine makecert -pe -n "CN=PowerShell User" -ss MY -a sha1 ` -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer The MakeCert.exe tool will prompt you for a private key password. The password ensures that no one can use or access the certificate without your consent. Create and enter a password that you can remember. You will use this password later to retrieve the certificate. To verify that the certificate was generated correctly, use the following command to get the certificate in the certificate store on the computer. (You will not find a certificate file in the file system directory.) At the Windows PowerShell prompt, type: get-childitem cert:\CurrentUser\my -codesigning This command uses the Windows PowerShell Certificate provider to view information about the certificate. If the certificate was created, the output shows the thumbprint that identifies the certificate in a display that resembles the following: Directory: Microsoft.PowerShell.Security\Certificate::CurrentUser\My Thumbprint Subject ---------- ------- 4D4917CB140714BA5B81B96E0B18AAF2C4564FDF CN=PowerShell User ] SIGN A SCRIPT ------------- After you create a self-signed certificate, you can sign scripts. If you use the AllSigned execution policy, signing a script permits you to run the script on your computer. The following sample script, Add-Signature.ps1, signs a script. However, if you are using the AllSigned execution policy, you must sign the Add-Signature.ps1 script before you run it. To use this script, copy the following text into a text file, and name it Add-Signature.ps1. Note: Be sure that the script file does not have a .txt file name extension. If your text editor appends ".txt", enclose the file name in quotation marks: "add-signature.ps1". ## add-signature.ps1 ## Signs a file param([string] $file=$(throw "Please specify a filename.")) $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] Set-AuthenticodeSignature $file $cert To sign the Add-Signature.ps1 script file, type the following commands at the Windows PowerShell command prompt: $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] Set-AuthenticodeSignature add-signature.ps1 $cert After the script is signed, you can run it on the local computer. However, the script will not run on computers on which the Windows PowerShell execution policy requires a digital signature from a trusted authority. If you try, Windows PowerShell displays the following error message: The file C:\remote_file.ps1 cannot be loaded. The signature of the certificate cannot be verified. At line:1 char:15 + .\ remote_file.ps1 If Windows PowerShell displays this message when you run a script that you did not write, treat the file as you would treat any unsigned script. Review the code to determine whether you can trust the script. ENABLE STRONG PRIVATE KEY PROTECTION FOR YOUR CERTIFICATE --------------------------------------------------------- If you have a private certificate on your computer, malicious programs might be able to sign scripts on your behalf, which authorizes Windows PowerShell to run them. To prevent automated signing on your behalf, use Certificate Manager (Certmgr.exe) to export your signing certificate to a .pfx file. Certificate Manager is included in the Microsoft .NET Framework SDK, the Microsoft Windows SDK, and in Internet Explorer 5.0 and later versions. To export the certificate: 1. Start Certificate Manager. 2. Select the certificate issued by PowerShell Local Certificate Root. 3. Click Export to start the Certificate Export Wizard. 4. Select "Yes, export the private key", and then click Next. 5. Select "Enable strong protection." 6. Type a password, and then type it again to confirm. 7. Type a file name that has the .pfx file name extension. 8. Click Finish. To re-import the certificate: 1. Start Certificate Manager. 2. Click Import to start the Certificate Import Wizard. 3. Open to the location of the .pfx file that you created during the export process. 4. On the Password page, select "Enable strong private key protection", and then enter the password that you assigned during the export process. 5. Select the Personal certificate store. 6. Click Finish. PREVENT THE SIGNATURE FROM EXPIRING ----------------------------------- The digital signature in a script is valid until the signing certificate expires or as long as a time stamp server can verify that the script was signed while the signing certificate was valid. Because most signing certificates are valid for one year only, using a time stamp server ensures that users can use your script for many years to come. SEE ALSO about_Execution_Policies about_Profiles Get-ExecutionPolicy Set-ExecutionPolicy Set-AuthenticodeSignature "Introduction to Code Signing" (http://go.microsoft.com/fwlink/?LinkId=1062 96) about_Special_Characters TOPIC about_Special_Characters SHORT DESCRIPTION Describes the special characters that you can use to control how Windows PowerShell interprets the next character in a command or parameter. LONG DESCRIPTION Windows PowerShell supports a set of special character sequences that are used to represent characters that are not part of the standard character set. The special characters in Windows PowerShell begin with the backtick character, also known as the grave accent (ASCII 96). The following special characters are recognized by Windows PowerShell: `0 Null `a Alert `b Backspace `f Form feed `n New line `r Carriage return `t Horizontal tab `v Vertical tab These characters are case-sensitive. NULL (`0) Windows PowerShell recognizes a null special character (`0) and represents it with a character code of 0. It appears as an empty space in the Windows PowerShell output. This allows you to use Windows PowerShell to read and process text files that use null characters, such as string termination or record termination indicators. The null special character is not equivalent to the $null variable, which stores a value of NULL. ALERT (`a) The alert (`a) character sends a beep signal to the computer's speaker. You can use this to warn a user about an impending action. The following command sends two beep signals to the local computer's speaker: for ($i = 0; $i -le 1; $i++){"`a"} BACKSPACE (`b) The backspace character (`b) moves the cursor back one character, but it does not delete any characters. The following command writes the word "backup", moves the cursor back twice, and then writes the word "out" (preceded by a space and starting at the new position): "backup`b`b out" The output from this command is as follows: back out FORM FEED (`f) The form feed character (`f) is a print instruction that ejects the current page and continues printing on the next page. This character affects printed documents only; it does not affect screen output. NEW LINE (`n) The new line character (`n) inserts a line break immediately after the character. The following example shows how to use the new line character in a Write-Host command: "There are two line breaks`n`nhere." The output from this command is as follows: There are two line breaks here. CARRIAGE RETURN (`r) The carriage return character (`r) eliminates the entire line prior to the `r character, as though the prior text were on a different line. For example: Write-Host "Let's not move`rDelete everything before this point." The output from this command is: Delete everything before this point. HORIZONTAL TAB (`t) The horizontal tab character (`t) advances to the next tab stop and continues writing at that point. By default, the Windows PowerShell console has a tab stop at every eighth space. For example, the following command inserts two tabs between each column. "Column1`t`tColumn2`t`tColumn3" The output from this command is: Column1 Column2 Column3 VERTICAL TAB (`v) The horizontal tab character (`t) advances to the next vertical tab stop and writes all subsequent output beginning at that point. This character affects printed documents only. It does not affect screen output. SEE ALSO about_Quoting_Rules about_Escape_Characters about_split TOPIC about_Split SHORT DESCRIPTION Explains how to use the split operator to split one or more strings into substrings. LONG DESCRIPTION The split operator splits one or more strings into substrings. You can change the following elements of the split operation: -- Delimiter. The default is whitespace, but you can specify characters, strings, patterns, or script blocks that specify the delimiter. -- Maximum number of substrings. The default is to return all substrings. If you specify a number less than the number of substrings, the remaini ng substrings are concatenated in the last substring. -- Options that specify the conditions under which the delimiter is matched, such as SimpleMatch and Multiline. SYNTAX The following diagram shows the syntax for the -split operator. The parameter names do not appear in the command. Include only the parameter values. The values must appear in the order specified in the syntax diagram. -Split <String> <String> -Split <Delimiter>[,<Max-substrings>[," <String> -Split {<ScriptBlock>} [,<Max-substrings>] In any split statement, you can substitute -iSplit or -cSplit for -split. The -iSplit and -split operators are case-insensitive. The -cSplit operator is case-sensitive, meaning that case is considered when the delimiter rules are applied. PARAMETERS <String> Specifies one or more strings to be split. If you submit multiple strings, all the strings are split using the same delimiter rules. Example: -split "red yellow blue green" red yellow blue green <Delimiter> The characters that identify the end of a substring. The default delimiter is whitespace, including spaces and non-printable characters, such as newline (`n) and tab (`t). When the strings are split, the delimiter is omitted from all the substrings. Example: "Lastname:FirstName:Address" -split ":" Lastname FirstName Address <Max-substrings> Specifies the maximum number of substrings returned. The default is all the substrings split by the delimiter. If there are more substrings , they are concatenated to the final substring. If there are fewer substrings, all the substrings are returned. A value of 0 and negative values return all the substrings. If you submit more than one string (an array of strings) to the split o perator , the Max-substrings limit is applied to each string separately. Example: $c = "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" $c -split ",", 5 Mercury Venus Earth Mars Jupiter,Saturn,Uranus,Neptune <ScriptBlock> An expression that specifies rules for applying the delimiter. The expression must evaluate to $true or $false. Enclose the script block in braces. Example: $c = "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" $c -split {$_ -eq "e" -or $_ -eq "p"} M rcury,V nus,Earth,Mars,Ju it r,Saturn,Uranus,N tun <Options> Enclose the option name in quotation marks. Options are valid only when the <Max-substrings> parameter is used in the statement. The syntax for the Options parameter is: "SimpleMatch [,IgnoreCase]" "[RegexMatch] [,IgnoreCase] [,CultureInvariant] [,IgnorePatternWhitespace] [,ExplicitCapture] [,Singleline | ,Multiline]" The SimpleMatch options are: -- SimpleMatch: Use simple string comparison when evaluating the delimiter. Cannot be used with RegexMatch. -- IgnoreCase: Forces case-insensitive matching, even if the -cSplit operator is specified. The RegexMatch options are: -- RegexMatch: Use regular expression matching to evaluate the delimiter. This is the default behavior. Cannot be used with SimpleMatch. -- IgnoreCase: Forces case-insensitive matching, even if the -cSplit operator is specified. -- CultureInvariant: Ignores cultural differences in language when evaluting the delimiter. Valid only with RegexMatch. -- IgnorePatternWhitespace: Ignores unescaped whitespace and comments marked with the number sign (#). Valid only with RegexMatch. -- Multiline: Multiline mode recognizes the start and end of lines and strings. Valid only with RegexMatch. Singleline is the default . -- Singleline: Singleline mode recognizes only the start and end of strings. Valid only with RegexMatch. Singleline is the default. -- ExplicitCapture: Ignores non-named match groups so that only explicit capture groups are returned in the result list. Valid only with RegexMatch. UNARY and BINARY SPLIT OPERATORS The unary split operator (-split <string>) has higher precedence than a comma. As a result, if you submit a comma-separated list of strings to the unary split operator, only the first string (before the first comma) is split. To split more than one string, use the binary split operator (<string> -split <delimiter>). Enclose all the strings in parentheses, or store the strings in a variable, and then submit the variable to the split operator. Consider the following example: -split "1 2", "a b" 1 2 a b "1 2", "a b" -split " " 1 2 a b -split ("1 2", "a b") 1 2 a b $a = "1 2", "a b" -split $a 1 2 a b EXAMPLES The following statement splits the string at whitespace. C:\PS> -split "Windows PowerShell 2.0`nWindows PowerShell with remoting" Windows PowerShell 2.0 Windows PowerShell with remoting The following statement splits the string at any comma. C:\PS> "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split ',' Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune The following statement splits the string at the pattern "er". C:\PS>"Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split 'er' M cury,Venus,Earth,Mars,Jupit ,Saturn,Uranus,Neptune The following statement performs a case-sensitive split at the letter "N". C:\PS> "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -cSplit 'N' Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus, eptune The following statement splits the string at "e" and "t". C:\PS> "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split '[et]' M rcury,V nus, ar h,Mars,Jupi r,Sa urn,Uranus,N p un The following statement splits the string at "e" and "r", but limits the resulting substrings to six substrings. C:\PS> "Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune" -split '[er]', 6 M cu y,V nus, arth,Mars,Jupiter,Saturn,Uranus,Neptune The following statement splits a string into three substrings. C:\PS> "a,b,c,d,e,f,g,h" -split ",", 3 a b c,d,e,f,g,h The following statement splits two strings into three substrings. (The limit is applied to each string independently.) C:\PS> "a,b,c,d", "e,f,g,h" -split ",", 3 a b c,d e f g,h The following statement splits each line in the here-string at the first digit. It uses the Multiline option to recognize the beginning of each line and string. The 0 represents the "return all" value of the Max-substrings parameter. Yo u can use options, such as Multiline, only when the Max-substrings value is specified. C:\PS> $a = @' 1The first line. 2The second line. 3The third of three lines. '@ C:\PS> $a -split "^\d", 0, "multiline" The first line. The second line. The third of three lines. The following statement uses the SimpleMatch option to direct the -split operator to interpret the dot (.) delimiter literally. With the default, RegexMatch, the dot enclosed in quotation marks (".") is interpreted to match any character except for a newline character. As a result, the split statement returns a blank line for every character except newline. The 0 represents the "return all" value of the Max-substrings parameter. You can use options, such as SimpleMatch, only when the Max-substrings value is specified. C:\PS> "This.is.a.test" -split ".", 0, "simplematch" This is a test The following statement splits the string at one of two delimiters, depending on the value of a variable. C:\PS> $i = 1 C:\PS> $c = "LastName, FirstName; Address, City, State, Zip" C:\PS> $c -split {if ($i -lt 1) {$_ -eq ","} else {$_ -eq ";"}} LastName, FirstName Address, City, State, Zip The following split statements split an XML file first at the angle bracket and then at the semicolon. The result is a readable version of the XML file. C:\PS> get-process powershell | export-clixml ps.xml C:\PS> $x = import-clixml ps.xml C:\PS> $x = $x -split "<" C:\PS> $x = $x -split ";" To display the result, type "$x". C:\PS> $x @{__NounName=Process Name=powershell Handles=428 VM=150081536 WS=34840576 PM=36253696 ... SEE ALSO Split-Path about_Operators about_Comparison_Operators about_Join about_Switch TOPIC about_Switch SHORT DESCRIPTION Explains how to use a switch to handle multiple If statements. LONG DESCRIPTION You use an If statement to make a decision in a script or program. Essentially, it says; "If this condition exists, perform this action. Otherwise do that action." You can perform that operation as many times as you want, but if you have a long list of conditions, an If statement becomes unwieldy. You can combine a long list of conditions in a switch statement. As in all branching statements, braces ({}) must enclose script blocks. A Switch statement is, in effect, a series of If statements. It matches the expression with each of the conditions case by case. If a match is found, the action associated with that condition is performed. A basic switch statement takes the following form: PS> $a = 3 PS> switch ($a) { 1 {"It is one."} 2 {"It is two."} 3 {"It is three."} 4 {"It is four."} } It is three. This simple example takes a value and compares it with each condition in the list. The action echoes a string from the match. But, you could have a problem if you check all of the conditions. For example: PS> $day = "day5" PS> switch ($day){ day1 {"Monday"; break} day2 {"Tuesday"; break} day3 {"Wednesday"; break} day4 {"Thursday"; break} day5 {"Friday"; break} day6 {"Saturday"; break} day7 {"Sunday"; break} day5 {"Too many days"; break} } Friday There are two day5 conditions in the list. But, the break at the end of each condition tells the switch to stop looking further and to perform the action it finds. If the break statements were not there, both day5 actions would be performed. If the value to switch against is an array, then each element in the array will be evaluated in order, starting at element 0 (zero). At least one element must be present that meets at least one condition; otherwise, an error will result. If there is more than one default clause, an error will result. The complete switch syntax is as follows: switch [-regex|-wildcard|-exact][-casesensitive] ( pipeline ) or switch [-regex|-wildcard|-exact][-casesensitive] -file filename followed by { "string"|number|variable|{ expression } { statementlist } default { statementlist } } By default, if no parameters are used, Switch behaves as if a case- insensitive exact match is in effect. If "pipeline" results in an array, each element of the array will be evaluated in ascending offset order (starting at 0 [zero]). At least one conditional element must be present in the Switch codeblock, and only one default clause can be present. If more than one default clause is present, a ParseException will be thrown. Switch has the following parameters: Regex Indicates that the match clause, if it is a string, is treated as a regex string. Use of this parameter disables Wildcard and Exact. If the match clause is not a string, this parameter is ignored. Wildcard Indicates that the match clause, if it is a string, is treated as a wildcard string. Use of this parameter disables Regex and Exact. If the match clause is not a string, this parameter is ignored. Exact Indicates that the match clause, if it is a string, must match exactly. Use of this parameter disables Wildcard and Regex. If the match clause is not a string, this parameter is ignored. CaseSensitive Modifies the match clause, if it is a string, to be case-sensitive. If the match clause is not a string, this parameter is ignored. File Takes input from a file (or representative) rather than a statement. If multiple File parameters are used, the last one is used. Each line of the file is read and passed through the switch block. Multiple uses of Regex, Wildcard, or Exact are allowed. However, only the last parameter used governs the behavior. The Break keyword indicates that no more processing will occur and that the Switch statement will exit. The Continue keyword indicates that no processing will continue against the current token and that the next token in the conditional will be evaluated. If no tokens are available, the Switch statement will exit. The "{ expression }" block may be a code block that will be evaluated at the time of the comparison. The current object is bound to the $_ automatic variable and is available during the evaluation of the expression. A comparison is considered a match if the expression evaluates to "True". This expression is evaluated in a new scope. The "Default" keyword within the switch statement indicates that if no matches are found, the code block that follows the keyword will be evaluated. Program flow will not be allowed from block to block because the closing brace ( } ) in the compound list is an explicit break. If multiple matches are found, each match results in the expression being executed. To avoid this, the Break or Continue keywords can be used to halt further comparisons. SEE ALSO about_Break about_Continue about_If about_Script_Blocks about_Throw TOPIC about_Throw SHORT DESCRIPTION Describes the Throw keyword, which generates a terminating error. LONG DESCRIPTION The Throw keyword causes a terminating error. You can use the Throw keyword to stop the processing of a command, function, or script. For example, you can use the Throw keyword in the script block of an If statement to respond to a condition or in the Catch block of a Try-Catch-Finally statement. You can also use the Throw keyword in a parameter declaration to make a function parameter mandatory. The Throw keyword can throw any object, such as a user message string or the object that caused the error. SYNTAX The syntax of the Throw keyword is as follows: throw [<expression>] The expression in the Throw syntax is optional. When the Throw statement does not appear in a Catch block, and it does not include an expression, it generates a ScriptHalted error. C:\PS> throw ScriptHalted At line:1 char:6 + throw + CategoryInfo : OperationStopped: (:) [], RuntimeExceptio n + FullyQualifiedErrorId : ScriptHalted If the Throw keyword is used in a Catch block without an expression, it throws the current RuntimeException again. For more information, see about_Try_Catch_Finally. THROWING A STRING The optional expression in a Throw statement can be a string, as shown in the following example: C:\PS> throw "This is an error." This is an error. At line:1 char:6 + throw < "This is an error." + CategoryInfo : OperationStopped: (This is an error.:Stri ng) [], RuntimeException + FullyQualifiedErrorId : This is an error. THROWING OTHER OBJECTS The expression can also be an object that throws the object that represents the PowerShell process, as shown in the following example: C:\PS> throw (get-process powershell) System.Diagnostics.Process (powershell) At line:1 char:6 + throw < (get-process powershell) + CategoryInfo : OperationStopped: (System.Diagnostics.Pro cess (powershell):Process) [], RuntimeException + FullyQualifiedErrorId : System.Diagnostics.Process (powershell) You can use the TargetObject property of the ErrorRecord object in the $error automatic variable to examine the error. C:\PS> $error[0].targetobject Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 319 26 61016 70864 568 3.28 5548 powershell You can also throw an ErrorRecord object or a Microsoft .NET Framework exception. The following example uses the Throw keyword to throw a System.FormatException object. C:\PS> $formatError = new-object system.formatexception C:\PS> throw $formatError One of the identified items was in an invalid format. At line:1 char:6 + throw < $formatError + CategoryInfo : OperationStopped: (:) [], FormatException + FullyQualifiedErrorId : One of the identified items was in an inv alid format. RESULTING ERROR The Throw keyword can generate an ErrorRecord object. The Exception property of the ErrorRecord object contains a RuntimeException object. The remainder of the ErrorRecord object and the RuntimeException object vary with the object that the Throw keyword throws. The RunTimeException object is wrapped in an ErrorRecord object, and the ErrorRecord object is automatically saved in the $Error automatic variable. USING THROW TO CREATE A MANDATORY PARAMETER You can use the Throw keyword to make a function parameter mandatory. This is an alternative to using the Mandatory parameter of the Parameter keyword. When you use the Mandatory parameter, the system prompts the user for the required parameter value. When you use the Throw keyword, the command stops and displays the error record. For example, the Throw keyword in the parameter subexpression makes the Path parameter a required parameter in the function. In this case, the Throw keyword throws a message string, but it is the presence of the Throw keyword that generates the terminating error if the Path parameter is not specified. The expression that follows Throw is optional. function Get-XMLFiles { param ($path = $(throw "The Path parameter is required.")) dir -path $path\* -include *.xml -recurse | sort lastwritetime | ft lastwritetime, attributes, name -auto } SEE ALSO about_Break about_Continue about_Scope about_Trap about_Try_Catch_Finally about_transactions TOPIC about_Transactions SHORT DESCRIPTION Describes how to manage transacted operations in Windows PowerShell. LONG DESCRIPTION Transactions are supported in Windows PowerShell beginning in Windows PowerShell 2.0. This feature enables you to start a transaction, to indicate which commands are part of the transaction, and to commit or roll back a transaction. ABOUT TRANSACTIONS In Windows PowerShell, a transaction is a set of one or more commands that are managed as a logical unit. A transaction can be completed ("committed"), which changes data affected by the transaction. Or, a transaction can be completely undone ("rolled back") so that the affected data is not changed by the transaction. Because the commands in a transaction are managed as a unit, either all commands are committed, or all commands are rolled back. Transactions are widely used in data processing, most notably in database operations and for financial transactions. Transactions are most often used when the worst-case scenario for a set of commands is not that they all fail, but that some commands succeed while others fail, leaving the system in a damaged, false, or uninterpretable state that is difficult to repair. TRANSACTION CMDLETS Windows PowerShell includes several cmdlets designed for managing transactions. Cmdlet Description -------------- --------------------------------- Start-Transaction Starts a new transaction. Use-Transaction Adds a command or expression to the transaction. The command must use transaction-enabled objects. Undo-Transaction Rolls back the transaction so that no data is changed by the transaction. Complete-Transaction Commits the transaction. The data affected by the transaction is changed. Get-Transaction Gets information about the active transaction. For a list of transaction cmdlets, type: get-command *transaction For detailed information about the cmdlets, type: get-help <cmdlet-name> -detailed For example: get-help use-transaction -detailed TRANSACTION-ENABLED ELEMENTS To participate in a transaction, both the cmdlet and the provider must support transactions. This feature is built in to the objects that are affected by the transaction. The Windows PowerShell Registry provider supports transactions in Windows Vista. The TransactedString object (Microsoft.PowerShell.Commands.Management.TransactedString) works with any operating system that runs Windows PowerShell. Other Windows PowerShell providers can support transactions. To find the Windows PowerShell providers in your session that support transactions, use the following command to find the "Transactions" value in the Capabilities property of providers: get-psprovider | where {$_.Capabilities -like "*transactions*"} For more information about a provider, see the Help for the provider. To get provider Help, type: get-help <provider-name> For example, to get Help for the Registry provider, type: get-help registry THE USETRANSACTION PARAMETER Cmdlets that can support transactions have a UseTransaction parameter. This parameter includes the command in the active transaction. You can use the full parameter name or its alias, "usetx". The parameter can be used only when the session contains an active transaction. If you enter a command with the UseTransaction parameter when there is no active transaction, the command fails. To find cmdlets with the UseTransaction parameter, type: get-help * -parameter UseTransaction In Windows PowerShell core, all of the cmdlets designed to work with Windows PowerShell providers support transactions. As a result, you can use the provider cmdlets to manage transactions. For more information about Windows PowerShell providers, see about_Providers. THE TRANSACTION OBJECT Transactions are represented in Windows PowerShell by a transaction object, System.Management.Automation.Transaction. The object has the following properties: RollbackPreference: Contains the rollback preference set for the current transaction. You can set the rollback preference when you use Start-Transaction to start the transaction. The rollback preference determines the conditions under which the transaction is rolled back automatically. Valid values are Error, TerminatingError, and Never. The default value is Error. Status: Contains the current status of the transaction. Valid values are Active, Committed, and RolledBack. SubscriberCount: Contains the number of subscribers to the transaction. A subscriber is added to a transaction when you start a transaction while another transaction is in progress. The subscriber count is decremented when a subscriber commits the transaction. ACTIVE TRANSACTIONS In Windows PowerShell, only one transaction is active at a time, and you can manage only the active transaction. Multiple transactions can be in progress in the same session at the same time, but only the most-recently started transaction is active. As a result, you cannot specify a particular transaction when using the transaction cmdlets. Commands always apply to the active transaction. This is most evident in the behavior of the Get-Transaction cmdlet. When you enter a Get-Transaction command, Get-Transaction always gets only one transaction object. This object is the object that represents the active transaction. To manage a different transaction, you must first finish the active transaction, either by committing it or rolling it back. When you do this, the previous transaction becomes active automatically. Transactions become active in the reverse of order of which they are started, so that the most recently started transaction is always active. SUBSCRIBERS AND INDEPENDENT TRANSACTIONS If you start a transaction while another transaction is in progress, by default, Windows PowerShell does not start a new transaction. Instead, it adds a "subscriber" to the current transaction. When a transaction has multiple subscribers, a single Undo-Transaction command at any point rolls back the entire transaction for all subscribers. However, to commit the transaction, you must enter a Complete-Transaction command for every subscriber. To find the number of subscribers to a transaction, check the SubscriberCount property of the transaction object. For example, the following command uses the Get-Transaction cmdlet to get the value of the SubscriberCount property of the active transaction: (Get-Transaction).SubscriberCount Adding a subscriber is the default behavior because most transactions that are started while another transaction is in progress are related to the original transaction. In the typical model, a script that contains a transaction calls a helper script that contains its own transaction. Because the transactions are related, they should be rolled back or committed as a unit. However, you can start a transaction that is independent of the current transaction by using the Independent parameter of the Start-Transaction cmdlet. When you start an independent transaction, Start-Transaction creates a new transaction object, and the new transaction becomes the active transaction. The independent transaction can be committed or rolled back without affecting the original transaction. When the independent transaction is finished (committed or rolled back), the original transaction becomes the active transaction again. CHANGING DATA When you use transactions to change data, the data that is affected by the transaction is not changed until you commit the transaction. However, the same data can be changed by commands that are not part of the transaction. Keep this in mind when you are using transactions to manage shared data. Typically, databases have mechanisms that lock the data while you are working on it, preventing other users, and other commands, scripts, and functions, from changing it. However, the lock is a feature of the database. It is not related to transactions. If you are working in a transaction-enabled file system or other data store, the data can be changed while the transaction is in progress. EXAMPLES The examples in this section use the Windows PowerShell Registry provider and assume that you are familiar with it. For information about the Registry provider, type "get-help registry". EXAMPLE 1: COMMITTING A TRANSACTION To create a transaction, use the Start-Transaction cmdlet. The following command starts a transaction with the default settings. start-transaction To include commands in the transaction, use the UseTransaction parameter of the cmdlet. By default, commands are not included in the transaction, For example, the following command, which sets the current location in the Software key of the HKCU: drive, is not included in the transaction. cd hkcu:\Software The following command, which creates the MyCompany key, uses the UseTransaction parameter of the New-Item cmdlet to include the command in the active transaction. new-item MyCompany -UseTransaction The command returns an object that represents the new key, but because the command is part of the transaction, the registry is not yet changed. Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 0 0 MyCompany {} To commit the transaction, use the Complete-Transaction cmdlet. Because it always affects the active transaction, you cannot specify the transaction. complete-transaction As a result, the MyCompany key is added to the registry. dir m* Hive: HKEY_CURRENT_USER\software SKC VC Name Property --- -- ---- -------- 83 1 Microsoft {(default)} 0 0 MyCompany {} EXAMPLE 2: ROLLING BACK A TRANSACTION To create a transaction, use the Start-Transaction cmdlet. The following command starts a transaction with the default settings. start-transaction The following command, which creates the MyOtherCompany key, uses the UseTransaction parameter of the New-Item cmdlet to include the command in the active transaction. new-item MyOtherCompany -UseTransaction The command returns an object that represents the new key, but because the command is part of the transaction, the registry is not yet changed. Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 0 0 MyOtherCompany {} To roll back the transaction, use the Undo-Transaction cmdlet. Because it always affects the active transaction, you do not specify the transaction. Undo-transaction The result is that the MyOtherCompany key is not added to the registry. dir m* Hive: HKEY_CURRENT_USER\software SKC VC Name Property --- -- ---- -------- 83 1 Microsoft {(default)} 0 0 MyCompany {} EXAMPLE 3: PREVIEWING A TRANSACTION Typically, the commands used in a transaction change data. However, the commands that get data are useful in a transaction, too, because they get data inside of the transaction. This provides a preview of the changes that committing the transaction would cause. The following example shows how to use the Get-ChildItem command (the alias is "dir") to preview the changes in a transaction. The following command starts a transaction. start-transaction The following command uses the New-ItemProperty cmdlet to add the MyKey registry entry to the MyCompany key. The command uses the UseTransaction parameter to include the command in the transaction. new-itemproperty -path MyCompany -Name MyKey -value 123 -UseTransaction The command returns an object representing the new registry entry, but the registry entry is not changed. MyKey ----- 123 To get the items that are currently in the registry, use a Get-ChildItem command ("dir") without the UseTransaction parameter. The following command gets items that begin with "M." dir m* The result shows that no entries have yet been added to the MyCompany key. Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 83 1 Microsoft {(default)} 0 0 MyCompany {} To preview the effect of committing the transaction, enter a Get-ChildItem ("dir") command with the UseTransaction parameter. This command has a view of the data from within the transaction. dir m* -useTransaction The result shows that, if the transaction is committed, the MyKey entry will be added to the MyCompany key. Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 83 1 Microsoft {(default)} 0 1 MyCompany {MyKey} EXAMPLE 4: COMBINING TRANSACTED AND NON-TRANSACTED COMMANDS You can enter non-transacted commands during a transaction. The non-transacted commands affect the data immediately, but they do not affect the transaction. The following command starts a transaction in the HKCU:\Software registry key. start-transaction The next three commands use the New-Item cmdlet to add keys to the registry. The first and third commands use the UseTransaction parameter to include the commands in the transaction. The second command omits the parameter. Because the second command is not included in the transaction, it is effective immediately. new-item MyCompany1 -UseTransaction new-item MyCompany2 new-item MyCompany3 -UseTransaction To view the current state of the registry, use a Get-ChildItem ("dir") command without the UseTransaction parameter. This command gets items that begin with "M." dir m* The result shows that the MyCompany2 key is added to the registry, but the MyCompany1 and MyCompany3 keys, which are part of the transaction, are not added. Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 83 1 Microsoft {(default)} 0 0 MyCompany2 {} The following command commits the transaction. complete-transaction Now, the keys that were added as part of the transaction appear in the registry. dir m* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 83 1 Microsoft {(default)} 0 0 MyCompany1 {} 0 0 MyCompany2 {} 0 0 MyCompany3 {} EXAMPLE 5: USING AUTOMATIC ROLLBACK When a command in a transaction generates an error of any kind, the transaction is automatically rolled back. This default behavior is designed for scripts that run transactions. Scripts are typically well tested and include error-handling logic, so errors are not expected and should terminate the transaction. The first command starts a transaction in the HKCU:\Software registry key. start-transaction The following command uses the New-Item cmdlet to add the MyCompany key to the registry. The command uses the UseTransaction parameter (the alias is "usetx") to include the command in the transaction. New-Item MyCompany -UseTX Because the MyCompany key already exists in the registry, the command fails, and the transaction is rolled back. New-Item : A key at this path already exists At line:1 char:9 + new-item < MyCompany -usetx A Get-Transaction command confirms that the transaction has been rolled back and that the SubscriberCount is 0. RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 0 RolledBack EXAMPLE 6: CHANGING THE ROLLBACK PREFERENCE If you want the transaction to be more error tolerant, you can use the RollbackPreference parameter of Start-Transaction to change the preference. The following command starts a transaction with a rollback preference of "Never". start-transaction -rollbackpreference Never In this case, when the command fails, the transaction is not automatically rolled back. New-Item MyCompany -UseTX New-Item : A key at this path already exists At line:1 char:9 + new-item < MyCompany -usetx Because the transaction is still active, you can resubmit the command as part of the transaction. New-Item MyOtherCompany -UseTX EXAMPLE 7: USING THE USE-TRANSACTION CMDLET The Use-Transaction cmdlet enables you to do direct scripting against transaction-enabled Microsoft .NET Framework objects. Use-Transaction takes a script block that can only contain commands and expressions that use transaction-enabled .NET Framework objects, such as instances of the Microsoft.PowerShell.Commands.Management.TransactedString class. The following command starts a transaction. start-transaction The following New-Object command creates an instance of the TransactedString class and saves it in the $t variable. $t = New-Object Microsoft.PowerShell.Commands.Management.TransactedStr ing The following command uses the Append method of the TransactedString object to add text to the string. Because the command is not part of the transaction, the change is effective immediately. $t.append("Windows") The following command uses the same Append method to add text, but it adds the text as part of the transaction. The command is enclosed in braces, and it is set as the value of the ScriptBlock parameter of Use-Transaction. The UseTransaction parameter (UseTx) is required. use-transaction {$t.append(" PowerShell")} -usetx To see the current content of the transacted string in $t, use the ToString method of the TransactedString object. $t.tostring() The output shows that only the non-transacted changes are effective. Windows To see the current content of the transacted string in $t from within the transaction, embed the expression in a Use-Transaction command. use-transaction {$s.tostring()} -usetx The output shows the transaction view. Windows PowerShell The following command commits the transaction. complete-transaction To see the final string: $t.tostring() Windows PowerShell EXAMPLE 7: MANAGING MULTI-SUBSCRIBER TRANSACTIONS When you start a transaction while another transaction is in progress, Windows PowerShell does not create a second transaction by default. Instead, it adds a subscriber to the current transaction. This example shows how to view and manage a multi-subscriber transaction. Begin by starting a transaction in the HKCU:\Software key. start-transaction The following command uses the Get-Transaction command to get the active transaction. get-transaction The result shows the object that represents the active transaction. RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active The following command adds the MyCompany key to the registry. The command uses the UseTransaction parameter to include the command in the transaction. new-item MyCompany -UseTransaction The following command uses the Start-Transaction command to start a transaction. Although this command is typed at the command prompt, this scenario is more likely to happen when you run a script that contains a transaction. start-transaction A Get-Transaction command shows that the subscriber count on the transaction object is incremented. The value is now 2. RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 2 Active The next command uses the New-ItemProperty cmdlet to add the MyKey registry entry to the MyCompany key. It uses the UseTransaction parameter to include the command in the transaction. new-itemproperty -path MyCompany -name MyKey -UseTransaction The MyCompany key does not exist in the registry, but this command succeeds because the two commands are part of the same transaction. The following command commits the transaction. If it rolled back the transaction, the transaction would be rolled back for all the subscribers. complete-transaction A Get-Transaction command shows that the subscriber count on the transaction object is 1, but the value of Status is still Active (not Committed). RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active To finish committing the transaction, enter a second Complete- Transaction command. To commit a multi-subscriber transaction, you must enter one Complete-Transaction command for each Start-Transaction command. complete-transaction Another Get-Transaction command shows that the transaction has been committed. RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 0 Committed EXAMPLE 8: MANAGING INDEPENDENT TRANSACTIONS When you start a transaction while another transaction is in progress, you can use the Independent parameter of Start-Transaction to make the new transaction independent of the original transaction. When you do, Start-Transaction creates a new transaction object and makes the new transaction the active transaction. Begin by starting a transaction in the HKCU:\Software key. start-transaction The following command uses the Get-Transaction command to get the active transaction. get-transaction The result shows the object that represents the active transaction. RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active The following command adds the MyCompany registry key as part of the transaction. It uses the UseTransaction parameter (UseTx) to include the command in the active transaction. new-item MyCompany -use The following command starts a new transaction. The command uses the Independent parameter to indicate that this transaction is not a subscriber to the active transaction. start-transaction -independent When you create an independent transaction, the new (most-recently created) transaction becomes the active transaction. You can use a Get-Transaction command to get the active transaction. get-transaction Note that the SubscriberCount of the transaction is 1, indicating that there are no other subscribers and that the transaction is new. RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active The new transaction must be finished (either committed or rolled back) before you can manage the original transaction. The following command adds the MyOtherCompany key to the registry. It uses the UseTransaction parameter (UseTx) to include the command in the active transaction. new-item MyOtherCompany -usetx Now, roll back the transaction. If there were a single transaction with two subscribers, rolling back the transaction would roll back the entire transaction for all the subscribers. However, because these transactions are independent, rolling back the newest transaction cancels the registry changes and makes the original transaction the active transaction. undo-transaction A Get-Transaction command confirms that the original transaction is still active in the session. get-transaction RollbackPreference SubscriberCount Status ------------------ --------------- ------ Error 1 Active The following command commits the active transaction. complete-transaction A Get-ChildItem command shows that the registry has been changed. dir m* Hive: HKEY_CURRENT_USER\Software SKC VC Name Property --- -- ---- -------- 83 1 Microsoft {(default)} 0 0 MyCompany {} SEE ALSO Start-Transaction Get-Transaction Complete-Transaction Undo-Transaction Use-Transaction Registry (provider) about_Providers Get-PSProvider Get-ChildItem about_trap TOPIC about_Trap SHORT DESCRIPTION Describes a keyword that handles a terminating error. LONG DESCRIPTION A terminating error stops a statement from running. If Windows PowerShell does not handle a terminating error in some way, Windows PowerShell also stops running the function or script in the current pipeline. In other languages, such as C#, terminating errors are referred to as exceptions. The Trap keyword specifies a list of statements to run when a terminating error occurs. Trap statements handle the terminating errors and allow execution of the script or function to continue instead of stopping. Syntax The Trap statement has the following syntax: trap [[<error type>]] {<statement list>} The Trap statement includes a list of statements to run when a terminating error occurs. The Trap keyword can optionally specify an error type. An error type requires brackets. A script or command can have multiple Trap statements. Trap statements can appear anywhere in the script or command. Trapping All Terminating Errors When a terminating error occurs that is not handled in another way in a script or command, Windows PowerShell checks for a Trap statement that handles the error. If a Trap statement is present, Windows PowerShell continues running the script or command in the Trap statement. The following example is a very simple Trap statement: trap {"Error found."} This Trap statement traps any terminating error. The following example is a function that contains this Trap statement: function TrapTest { trap {"Error found."} nonsenseString } This function includes a nonsense string that causes an error. Running this function returns the following: C:\PS> TrapTest Error found. The following example includes a Trap statement that displays the error by using the $_ automatic variable: function TrapTest { trap {"Error found: $_"} nonsenseString } Running this version of the function returns the following: C:\PS> TrapTest Error found: The term 'nonsenseString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included verify that the path is correct, and then try again. Trap statements can also be more complex. A Trap statement can include multiple conditions or function calls. It can log, test, or even run another program. Trapping Specified Terminating Errors The following example is a Trap statement that traps the CommandNotFoundException error type: trap [System.Management.Automation.CommandNotFoundException] {"Command error trapped"} When a function or script encounters a string that does not match a known command, this Trap statement displays the "Command error trapped" string. After running any statements in the Trap statement list, Windows PowerShell writes the error object to the error stream and then continues the script. Windows PowerShell uses the Microsoft .NET Framework exception types. The following example specifies the System.Exception error type: trap [System.Exception] {"An error trapped"} The CommandNotFoundException error type inherits from the System.Exception type. This statement traps an error that is created by an unknown command. It also traps other error types. You can have more than one Trap statement in a script. Each error can be trapped by only one Trap statement. If an error occurs, and more than one Trap statement is available, Windows PowerShell uses the Trap statement with the most specific error type that matches the error. The following script example contains an error. The script includes a general Trap statement that traps any terminating error and a specific Trap statement that specifies the CommandNotFoundException type. trap {"Other terminating error trapped" } trap [System.Management.Automation.CommandNotFoundException] {"Comman d error trapped"} nonsenseString Running this script produces the following result: Command error trapped The term 'nonsenseString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included verify that the path is correct, and then try again. At C:\PS>testScript1.ps1:3 char:19 + nonsenseString < Because Windows PowerShell does not recognize "nonsenseString" as a cmdlet or other item, it returns a CommandNotFoundException error. This terminating error is trapped by the specific Trap statement. The following script example contains the same Trap statements with a different error: trap {"Other terminating error trapped" } trap [System.Management.Automation.CommandNotFoundException] {"Command error trapped"} 1/$null Running this script produces the following result: Other terminating error trapped Attempted to divide by zero. At C:PS> errorX.ps1:3 char:7 + 1/ < $null The attempt to divide by zero does not create a CommandNotFoundException error. Instead, that error is trapped by the other Trap statement, which traps any terminating error. Trapping Errors and Scope If a terminating error occurs in the same scope as the Trap statement, after running the Trap statements, Windows PowerShell continues at the statement after the error. If the Trap statement is in a different scope from the error, execution continues at the next statement that is in the same scope as the Trap statement. For instance, if an error occurs in a function, and the Trap statement is in the function, the script continues at the next statement. For example, the following script contains an error and a Trap statement: function function1 { trap { "An error: " } NonsenseString "function1 was completed" } Later in the script, running the Function1 function produces the following result: function1 An error: The term 'NonsenseString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included verify that the path is correct, and then try again. At C:\PS>TestScript1.ps1:3 char:19 + NonsenseString function1 was completed The Trap statement in the function traps the error. After displaying the message, Windows PowerShell resumes running the function. Note that Function1 was completed. Compare this with the following example, which has the same error and Trap statement. In this example, the Trap statement occurs outside the function: function function2 { NonsenseString "function2 was completed" } trap { "An error: " } . . . function2 Later in the script, running the Function2 function produces the following result: An error: The term 'NonsenseString' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included verify that the path is correct, and then try again. At C:\PS>TestScript2.ps1:4 char:19 + NonsenseString In this example, the "function2 was completed" command was not run. Although both terminating errors occur within a function, if the Trap statement is outside the function, Windows PowerShell does not go back into the function after the Trap statement runs. Using the Break and Continue Keywords You can use the Break and Continue keywords in a Trap statement to determine whether a script or command continues to run after a terminating error. If you include a Break statement in a Trap statement list, Windows PowerShell stops the function or script. The following sample function uses the Break keyword in a Trap statement: C:\PS> function break_example { trap {"Error trapped"; break;} 1/$null "Function completed." } C:\PS> break_example Error trapped Attempted to divide by zero. At line:4 char:7 Because the Trap statement included the Break keyword, the function does not continue to run, and the "Function completed" line is not run. If you include a Continue statement in a Trap statement, Windows PowerShell resumes after the statement that caused the error, just as it would without Break or Continue. With the Continue keyword, however, Windows PowerShell does not write an error to the error stream. The following sample function uses the Continue keyword in a Trap statement: C:\PS> function continue_example { trap {"Error trapped"; continue;} 1/$null "Function completed."} C:\PS> continue_example Error trapped Function completed. The function resumes after the error is trapped, and the "Function completed" statement runs. No error is written to the error stream. SEE ALSO about_Break about_Continue about_Throw about_Try_Catch_Finally about_Scopes about_Try_Catch_Finally about_try_catch_finally TOPIC about_Try_Catch_Finally SHORT DESCRIPTION Describes how to use the Try, Catch, and Finally blocks to handle terminating errors. LONG DESCRIPTION Use Try, Catch, and Finally blocks to respond to or handle terminating errors in scripts. The Trap statement can also be used to handle terminating errors in scripts. For more information, see about_Trap. A terminating error stops a statement from running. If Windows PowerShell does not handle a terminating error in some way, Windows PowerShell also stops running the function or script using the current pipeline. In other languages, such as C#, terminating errors are referred to as exceptions. For more information about errors, see about_Errors. Use the Try block to define a section of a script in which you want Windows PowerShell to monitor for errors. When an error occurs within the Try block, the error is first saved to the $Error automatic variable. Windows PowerShell then searches for a Catch block to handle the error. If the Try statement does not have a matching Catch block, Windows PowerShell continues to search for an appropriate Catch block or Trap statement in the parent scopes. After a Catch block is completed or if no appropriate Catch block or Trap statement is found, the Finally block is run. If the error cannot be handled, the error is written to the error stream. A Catch block can include commands for tracking the failure or for recovering the expected flow of the script. A Catch block can specify which error types it catches. A Try statement can include multiple Catch blocks for different kinds of errors. A Finally block can be used to free any resources that are no longer needed by your script. Try, Catch, and Finally resemble the Try, Catch, and Finally keywords used in the C# programming language. Syntax A Try statement contains a Try block, zero or more Catch blocks, and zero or one Finally block. A Try statement must have at least one Catch block or one Finally block. The following shows the Try block syntax: try {<statement list>} The Try keyword is followed by a statement list in braces. If a terminating error occurs while the statements in the statement list are being run, the script passes the error object from the Try block to an appropriate Catch block. The following shows the Catch block syntax: catch [[<error type>][',' <error type>]*] {<statement list>} Error types appear in brackets. The outermost brackets indicate the element is optional. The Catch keyword is followed by an optional list of error type specifications and a statement list. If a terminating error occurs in the Try block, Windows PowerShell searches for an appropriate Catch block. If one is found, the statements in the Catch block are executed. The Catch block can specify one or more error types. An error type is a Microsoft .NET Framework exception or an exception that is derived from a .NET Framework exception. A Catch block handles errors of the specified .NET Framework exception class or of any class that derives from the specified class. If a Catch block specifies an error type, that Catch block handles that type of error. If a Catch block does not specify an error type, that Catch block handles any error encountered in the Try block. A Try statement can include multiple Catch blocks for the different specified error types. The following shows the Finally block syntax: finally {<statement list>} The Finally keyword is followed by a statement list that runs every time the script is run, even if the Try statement ran without error or an error was caught in a Catch statement. Note that pressing CTRL+C stops the pipeline. Objects that are sent to the pipeline will not be displayed as output. Therefore, if you include a statement to be displayed, such as "Finally block has run", it will not be displayed after you press CTRL+C, even if the Finally block ran. Catching Errors The following sample script shows a Try block with a Catch block: try { NonsenseString } catch { "An error occurred." } The Catch keyword must immediately follow the Try block or another Catch block. Windows PowerShell does not recognize "NonsenseString" as a cmdlet or other item. Running this script returns the following result: An error occurred. When the script encounters "NonsenseString", it causes a terminating error. The Catch block handles the error by running the statement list inside the block. Using Multiple Catch Statements A Try statement can have any number of Catch blocks. For example, the following script has a Try block that downloads MyFile.doc, and it contains two Catch blocks: try { $wc = new-object System.Net.WebClient $wc.DownloadFile("http://www.contoso.com/MyDoc.doc") } catch [System.Net.WebException],[System.IO.IOException] { "Unable to download MyDoc.doc from http://www.contoso.com." } catch { "An error occurred that could not be resolved." } The first Catch block handles errors of the System.Net.WebException and System.IO.IOException types. The second Catch block does not specify an error type. The second Catch block handles any other terminating errors that occur. Windows PowerShell matches error types by inheritance. A Catch block handles errors of the specified .NET Framework exception class or of any class that derives from the specified class. The following example contains a Catch block that catches a "Command Not Found" error: catch [System.Management.Automation.CommandNotFoundException] {"Inherited Exception" } The specified error type, CommandNotFoundException, inherits from the System.SystemException type. The following example also catches a Command Not Found error: catch [System.SystemException] {"Base Exception" } This Catch block handles the "Command Not Found" error and other errors that inherit from the SystemException type. If you specify an error class and one of its derived classes, place the Catch block for the derived class before the Catch block for the general class. Freeing Resources by Using Finally To free resources used by a script, add a Finally block after the Try and Catch blocks. The Finally block statements run regardless of whether the Try block encounters a terminating error. Windows PowerShell runs the Finally block before the script terminates or before the current block goes out of scope. A Finally block runs even if you use CTRL+C to stop the script. A Finally block also runs if an Exit keyword stops the script from within a Catch block. SEE ALSO about_Errors about_Trap about_type_operators TOPIC about_Type_Operators SHORT DESCRIPTION Describes the operators that work with Microsoft .NET Framework types. LONG DESCRIPTION The Boolean type operators (-is and -isnot) tell whether an object is an instance of a specified .NET Framework type. The -is operator returns a value of TRUE if the type matches and a value of FALSE otherwise. The -isnot operator returns a value of FALSE if the type matches and a value of TRUE otherwise. The -as operator tries to convert the input object to the specified .NET Framework type. If it succeeds, it returns the converted object. It if fails, it returns nothing. It does not return an error. The following table lists the type operators in Windows PowerShell. Operator Description Example -------- ------------------------ ------------------------------------- -is Returns TRUE when the C:\PS> (get-date) -is [datetime] input is an instance True of the specified .NET Framework type. -isnot Returns TRUE when the C:\PS> (get-date) -isnot [datetime] input is not an instance False of the specified .NETFramework type. -as Converts the input to C:\PS> 12/31/07 -as [datetime] the specified Monday, December 31, 2007 12:00:00 AM .NET Framework type. The syntax of the type operators is as follows: <input> <operator> [.NET type] You can also use the following syntax: <input> <operator> ".NET type" To specify the .NET Framework type, enclose the type name in brackets ([ ]), or enter the type as a string, such as [DateTime] or "datetime" for System.DateTime. If the type is not at the root of the system namespace, specify the full name of the object type. You can omit "System.". For example, to specify System.Diagnostics.Process, enter [System.Diagnostics.Process], [Diagnostics.Process], or "diagnostics.process". The type operators always return a Boolean value, even if the input is a collection of objects. However, when the input is a collection, the type operators match the .NET Framework type of the collection. They do not match the type of each object, even when all of the objects are of the same type. To find the .NET Framework type of an object, use the Get-Member cmdlet. Or, use the GetType method of all the objects together with the FullName property of this method. For example, the following statement gets the type of the return value of a Get-Culture command: C:\PS> (get-culture).gettype().fullname System.Globalization.CultureInfo EXAMPLES The following examples show some uses of the Type operators: C:\PS> 32 -is [Float] False C:\PS> 32 -is "int" True C:\PS> (get-date) -is [DateTime] True C:\PS> "12/31/2007" -is [DateTime] False C:\PS> "12/31/2007" -is [String] True C:\PS> (get-process powershell)[0] -is [System.Diagnostics.Process] True C:\PS> (get-command get-member) -is [System.Management.Automation.Cmdle tInfo] True The following example shows that when the input is a collection of objects, the matching type is the .NET Framework type of the collection, not the typ e of the individual objects in the collection. In this example, although both the Get-Culture and Get-UICulture cmdlets return System.Globalization.CultureInfo objects, a collection of these objects is a System.Object array. C:\PS> (get-culture) -is [System.Globalization.CultureInfo] True C:\PS> (get-uiculture) -is [System.Globalization.CultureInfo] True C:\PS> (get-culture), (get-uiculture) -is [System.Globalization.Culture Info] False C:\PS> (get-culture), (get-uiculture) -is [Array] True C:\PS> (get-culture), (get-uiculture) | foreach {$_ -is [System.Globali zation.CultureInfo]) True True C:\PS> (get-culture), (get-uiculture) -is [Object] True The following examples show how to use the -as operator. C:\PS> "12/31/07" -is [datetime] False C:\PS> "12/31/07" -as [datetime] Monday, December 31, 2007 12:00:00 AM C:\PS> $date = "12/31/07" -as [datetime] C:\PS>$a -is [datetime] True C:\PS> 1031 -as [System.Globalization.CultureInfo] LCID Name DisplayName ---- ---- ----------- 1031 de-DE German (Germany) The following example shows that when the -as operator cannot convert the input object to the .NET Framework type, it returns nothing. C:\PS> 1031 -as [System.Diagnostic.Process] C:\PS> SEE ALSO about_Operators about_types.ps1xml TOPIC about_Types.ps1xml SHORT DESCRIPTION Explains how the Types.ps1xml files let you extend the Microsoft .NET Framework types of the objects that are used in Windows PowerShell. LONG DESCRIPTION The Types.ps1xml file in the Windows PowerShell installation directory ($pshome) is an XML-based text file that lets you add properties and methods to the objects that are used in Windows PowerShell. Windows PowerShell has a built-in Types.ps1xml file that adds several elements to the .NET Framework types, but you can create additional Types.ps1xml files to further extend the types. For example, by default, array objects (System.Array) have a Length property that lists the number of objects in the array. However, because the name "length" does not clearly describe the property, Windows PowerShell adds an alias property named "Count" that displays the same value. The following XML adds the Count property to the System.Array type. <Type> <Name>System.Array</Name> <Members> <AliasProperty> <Name>Count</Name> <ReferencedMemberName> Length </ReferencedMemberName> </AliasProperty> </Members> </Type> To get the new AliasProperty, use a Get-Member command on any array, as sho wn in the following example. Get-Member -inputobject (1,2,3,4) The command returns the following results. Name MemberType Definition ---- ---------- ---------- Count AliasProperty Count = Length Address Method System.Object& Address(Int32 ) Clone Method System.Object Clone() CopyTo Method System.Void CopyTo(Array array, Int32 index): Equals Method System.Boolean Equals(Object obj) Get Method System.Object Get(Int32 ) ... As a result, you can use either the Count property or the Length property of arrays in Windows PowerShell. For example: C:\PS> (1, 2, 3, 4).count 4 C:\PS> (1, 2, 3, 4).length 4 Creating New Types.ps1xml Files The .ps1xml files that are installed with Windows PowerShell are digitally signed to prevent tampering because the formatting can include script blocks. Therefore, to add a property or method to a .NET Framework type, create your own Types.ps1xml files, and then add them to your Windows PowerShell console. To create a new file, start by copying an existing Types.ps1xml file. The new file can have any name, but it must have a .ps1xml file name extension. You can place the new file in any directory that is accessible to Windows PowerShell, but it is useful to place the files in the Windows PowerShell installation directory ($pshome) or in a subdirectory of the installation directory. When you have saved the new file, use the Update-TypeData cmdlet to add the new file to your Windows PowerShell console. If you want your types to take precedence over the types that are defined in the built-in file, use the PrependData parameter of the Update-TypeData cmdlet. Update-TypeData affects only the current console. To make the change to all future consoles, export the console, or add the Update-TypeData command to your Windows PowerShell profile. Types.ps1xml and Add-Member The Types.ps1xml files add properties and methods to all the instances of the objects of the specified .NET Framework type in the affected Windows PowerShell console. However, if you need to add properties or methods only to one instance of an object, use the Add-Member cmdlet. For more information,see Add-Member. Example: Adding an Age Member to FileInfo Objects This example shows how to add an Age property to file objects (System.IO.FileInfo). The age of a file is the difference between its creation time and the current time in days. It is easiest to use the original Types.ps1xml file as a template for the new file. The following command copies the original file to a file called MyTypes.ps1xml in the $pshome directory. copy-item Types.ps1xml MyTypes.ps1xml Next, open the Types.ps1xml file in any XML or text editor, such as Notepad. Because the Age property is calculated by using a script block, find a <ScriptProperty> tag to use as a model for the new Age property. Copy the XML between the <Type> and </Type> tags of the code to create the script property. Then, delete the remainder of the file, except for the opening <?xml> and <Types> tags and the closing </Types> tag. You must also delete the digital signature to prevent errors. Begin with the model script property, such as the following script property, which was copied from the original Types.ps1xml file. <?xml version="1.0" encoding="utf-8" ?> <Types> <Type> <Name>System.Guid</Name> <Members> <ScriptProperty> <Name>Guid</Name> <GetScriptBlock>$this.ToString()</GetScriptBlock> </ScriptProperty> </Members> </Type> </Types> Then, change the name of the .NET Framework type, the name of the property, and the value of the script block to create an Age property for file objects. <?xml version="1.0" encoding="utf-8" ?> <Types> <Type> <Name>System.IO.FileInfo</Name> <Members> <ScriptProperty> <Name>Age</Name> <GetScriptBlock> ((get-date) - ($this.creationtime)).days </GetScriptBlock> </ScriptProperty> </Members> </Type> </Types> After you save the file and close it, use an Update-TypeData command, such as the following command, to add the new Types.ps1xml file to the current console. The command uses the PrependData parameter to place the new file in a higher precedence order than the original file. (For more information about Update-TypeData, see Update-TypeData.) update-typedata -prependpath $pshome\MyTypes.ps1xml To test the change, use a Get-ChildItem command to get the PowerShell.exe file in the $pshome directory, and then pipe the file to the Format-List cmdlet to list all of the properties of the file. As a result of the change, the Age property appears in the list. get-childitem $pshome\powershell.exe | format-list -property * PSPath : Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS... PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\WINDOWS... PSChildName : powershell.exe PSDrive : C PSProvider : Microsoft.PowerShell.Core\FileSystem PSIsContainer : False Age : 16 VersionInfo : File: C:\WINDOWS\system32\WindowsPow... InternalName: POWERSHELL OriginalFilename: PowerShell.EXE ... You can also display the Age property of the file by using the following command. (get-childitem $pshome\powershell.exe).age 16 The XML in Types.ps1xml Files The <Types> tag encloses all of the types that are defined in the file. There should be only one pair of <Types> tags. Each .NET Framework type mentioned in the file should be represented by a pair of <Type> tags. The type tags must contain the following tags: <Name>: A pair of <Name> tags that enclose the name of the affected .NET Framework type. <Members>: A pair of <Members> tags that enclose the tags for the new properties and methods that are defined for the .NET Framework type. Any of the following member tags can be inside the <Members> tags. <AliasProperty>: Defines a new name for an existing property. The <AliasProperty> tag must have a pair of <Name> tags that specify the name of the new property and a pair of <ReferencedMemberName> tags that specify the existing property. For example, the Count alias property is an alias for the Length property of array objects. <Type> <Name>System.Array</Name> <Members> <AliasProperty> <Name>Count</Name> <ReferencedMemberName>Length</ReferencedMemberName> </AliasProperty> </Members> </Type> <CodeMethod>: References a static method of a .NET Framework class. The <CodeMethod> tag must have a pair of <Name> tags that specify the name of the new method and a pair of <GetCodeReference> tags that specify the code in which the method is defined. For example, the Mode property of directories (System.IO.DirectoryInfo objects) is a code property defined in the Windows PowerShell FileSystem provider. <Type> <Name>System.IO.DirectoryInfo</Name> <Members> <CodeProperty> <Name>Mode</Name> <GetCodeReference> <TypeName>Microsoft.PowerShell.Commands.FileSystemPr ovider</TypeName> <MethodName>Mode</MethodName> </GetCodeReference> </CodeProperty> </Members> </Type> <CodeProperty>: References a static method of a .NET Framework class. The <CodeProperty> tag must have a pair of <Name> tags that specify the name of the new property and a pair of <GetCodeReference> tags that specify the code in which the property is defined. For example, the Mode property of directories (System.IO.DirectoryInfo objects) is a code property defined in the Windows PowerShell FileSystem provider. <Type> <Name>System.IO.DirectoryInfo</Name> <Members> <CodeProperty> <Name>Mode</Name> <GetCodeReference> <TypeName>Microsoft.PowerShell.Commands.FileSystemPr ovider</TypeName> <MethodName>Mode</MethodName> </GetCodeReference> </CodeProperty> </Members> </Type> <MemberSet>: Defines a collection of members (properties and methods). The <MemberSet> tags appear within the primary <Members> tags. The tags must enclose a pair of <Name> tags surrounding the name of the member set and a pair of secondary <Members> tags that surround the members (properties and methods) in the set. Any of the tags that create a property (such as <NoteProperty> or <ScriptProperty>) or a method (such as <Method> or <ScriptMethod>) can be members of the set. In Types.ps1xml files, the <MemberSet> tag is used to define the default views of the .NET Framework objects in Windows PowerShell. In this case, the name of the member set (the value within the <Name> tags) is always "PsStandardMembers", and the names of the properties (the value of the <Name> tag) are one of the following: - DefaultDisplayProperty: A single property of an object. - DefaultDisplayPropertySet: One or more properties of an object. - DefaultKeyPropertySet: One or more key properties of an object. A key property identifies instances of property values, such as the ID number of items in a session history. For example, the following XML defines the default display of services (System.ServiceProcess.ServiceController objects) that are returned by the Get-Service cmdlet. It defines a member set named "PsStandardMembers" that consists of a default property set with the Status, Name, and DisplayName properties. <Type> <Name>System.ServiceProcess.ServiceController</Name> <Members> <MemberSet> <Name>PSStandardMembers</Name> <Members> <PropertySet> <Name>DefaultDisplayPropertySet</Name> <ReferencedProperties> <Name>Status</Name> <Name>Name</Name> <Name>DisplayName</Name> </ReferencedProperties> </PropertySet> </Members> </MemberSet> </Members> </Type> <Method>: References a native method of the underlying object. <Methods>: A collection of the methods of the object. <NoteProperty>: Defines a property with a static value. The <NoteProperty> tag must have a pair of <Name> tags that specify the name of the new property and a pair of <Value> tags that specify the value of the property. For example, the following XML creates a Status property for directories (System.IO.DirectoryInfo objects). The value of the Status property is always "Success". <Type> <Name>System.IO.DirectoryInfo</Name> <Members> <NoteProperty> <Name>Status</Name> <Value>Success</Value> </NoteProperty> </Members> </Type> <ParameterizedProperty>: Properties that take arguments and return a value. <Properties>: A collection of the properties of the object. <Property>: A property of the base object. <PropertySet>: Defines a collection of properties of the object. The <PropertySet> tag must have a pair of <Name> tags that specify the name of the property set and a pair of <ReferencedProperty> tags that specify the properties. The names of the properties are enclosed in <Name> tag pairs. In Types.ps1xml, <PropertySet> tags are used to define sets of properties for the default display of an object. You can identify the default displays by the value "PsStandardMembers" in the <Name> tag of a <MemberSet> tag. For example, the following XML creates a Status property for directories (System.IO.DirectoryInfo objects). The value of the Status property is always "Success". <Type> <Name>System.ServiceProcess.ServiceController</Name> <Members> <MemberSet> <Name>PSStandardMembers</Name> <Members> <PropertySet> <Name>DefaultDisplayPropertySet</Name> <ReferencedProperties> <Name>Status</Name <Name>Name</Name> <Name>DisplayName</Name> </ReferencedProperties> </PropertySet> <Members> <MemberSet> <Members> <Type> <ScriptMethod>: Defines a method whose value is the output of a script. The <ScriptMethod> tag must have a pair of <Name> tags that specify the name of the new method and a pair of <Script> tags that enclose the script block that returns the method result. For example, the ConvertToDateTime and ConvertFromDateTime methods of management objects (System.System.Management.ManagementObject) are script methods that use the ToDateTime and ToDmtfDateTime static methods of the System.Management.ManagementDateTimeConverter class. <Type> <Name>System.Management.ManagementObject</Name> <Members> <ScriptMethod> <Name>ConvertToDateTime</Name> <Script> [System.Management.ManagementDateTimeConverter]::T oDateTime($args[0]) </Script> </ScriptMethod> <ScriptMethod> <Name>ConvertFromDateTime</Name> <Script> [System.Management.ManagementDateTimeConverter]::T oDmtfDateTime($args[0]) </Script> </ScriptMethod> </Members> </Type> <ScriptProperty>: Defines a property whose value is the output of a script. The <ScriptProperty> tag must have a pair of <Name> tags that specify the name of the new property and a pair of <GetScriptBlock> tags that enclose the script block that returns the property value. For example, the VersionInfo property of files (System.IO.FileInfo objects) is a script property that results from using the FullName property of the GetVersionInfo static method of System.Diagnostics.FileVersionInfo objects. <Type> <Name>System.IO.FileInfo</Name> <Members> <ScriptProperty> <Name>VersionInfo</Name> <GetScriptBlock> [System.Diagnostics.FileVersionInfo]::GetVersionInfo ($this.FullName) </GetScriptBlock> </ScriptProperty> </Members> </Type> For more information, see the Windows PowerShell Software Development Kit (SDK) in the MSDN (Microsoft Developer Network )library at http://go.microsoft.com/fwlink/?LinkId=144538. Update-TypeData To load your Types.ps1xml files into a Windows PowerShell console, use the Update-TypeData cmdlet. If you want the types in your file to take precedence over types in the built-in Types.ps1xml file, use the PrependData parameter of Update-TypeData. Update-TypeData affects only the current console. To make the change to all future consoles, export the console, or add the Update-TypeData command to your Windows PowerShell profile. Signing a Types.ps1xml File To protect users of your Types.ps1xml file, you can sign the file using a digital signature. For more information, see about_Signing. SEE ALSO about_Signing Copy-Item Get-Member Update-TypeData about_Variables TOPIC about_Variables SHORT DESCRIPTION Describes how variables store values that can be used in Windows PowerShell. LONG DESCRIPTION A variable is a unit of memory in which values are stored. In Windows PowerShell, variables are represented by single-word text strings that begin with the dollar sign ($), such as $a, $process, or $my_var. 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, MaximumHistoryCount 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 list all of the variables in your Windows PowerShell session, type: get-variable To display the value of any variable, type the name of the variable, preceded by a dollar sign ($). Windows PowerShell responds by displaying its value. $<variable-name> For example: PS> $pshome C:\Windows\System32\WindowsPowerShell\v1.0 To create a new variable or to change the value of a variable, use an assignment statement in the following format: $<variable> = <value> For example: PS> $my-variable = 1, 2, 3 or PS> $VerbosePreference = "Continue" To get an object that represents the variable, use a Get-Variable command, such as: PS> get-variable pid To use a variable, type the variable name, including the dollar sign ($), in a command or expression. If the command or expression is not enclosed in quotation marks or if it is enclosed in double-quotation marks ("), the value of the variable is used in the command or expression. If the command is enclosed in single quotation marks, ('), the variable name is used in the expression. For example, the first command finds the value of the $profile variable, which is the path to the Windows PowerShell user profile file. The second command opens the file in Notepad. PS> $profile C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microso ft.PowerShell_profile.ps1 PS> Notepad $profile You can store any type of object in a variable, including integers, strings, arrays, and hash tables, objects that represent processes, services, event logs, and computers. 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 save a variable, add the variable to your Windows PowerShell profile. Variables in a profile are added to every Windows PowerShell session that you open. For example, to change the value of the $VerbosePreference variable in every Windows PowerShell session, add the following command to your Windo ws PowerShell profile. $VerbosePreference = "Continue" You can add this command to your profile by opening the profile file in a text editor, such as Notepad, or you can use an Add-Content command, like the following one. The following command adds the new value for the $VerbosePreference varia ble to the CurrentUser,AllHosts profile. add-content -path $profile.CurrentUserAllHosts -value '$VerbosePreference = "Continue"' For more information about Windows PowerShell profiles, see about_profile s. VARIABLE NAMES WITH SPECIAL CHARACTERS You can use braces to force Windows PowerShell to interpret a variable name literally. This is especially helpful when creating or referring to a variable name that includes special characters, such as dashes, periods, colons, and parentheses. To create a variable name that includes a hyphen, enclose the variable name in braces. The following command creates a variable named "save-items". C:\PS> ${save-items} = "a", "b", "c" C:\PS>${save-items} a b c To refer to a variable name that includes parentheses, enclose the variable name in braces. For example, the following command gets the child items in the directory stores in 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 THE VARIABLE: DRIVE Windows PowerShell includes a Variable: drive that looks and acts like a file system drive, but it contains the variables in your session. To change to the variable drive, type: set-location variable: (or "cd variable:") When in the Variable drive, to list the items (variables) in the drive, use the Get-ChildItem cmdlet. For example: get-childitem (or "dir" or "ls") For more information about the Variable: drive and the Windows PowerShell Variable provider, type: get-help variable SEE ALSO about_Automatic_Variables about_Environment_Variables about_Preference_Variables about_Scopes about_While TOPIC about_While SHORT DESCRIPTION Describes a language statement that you can use to run a command block based on the results of a conditional test. LONG DESCRIPTION The While statement (also known as a While loop) is a language construct for creating a loop that runs commands in a command block as long as a conditional test evaluates to true. The While statement is easier to construct than a For statement because its syntax is less complicated. In addition, it is more flexible than the Foreach statement because you specify a conditional test in the While statement to control how many times the loop runs. The following shows the While statement syntax: while (<condition>){<statement list>} When you run a While statement, Windows PowerShell evaluates the <condition> section of the statement before entering the <statement list> section. The condition portion of the statement resolves to either true or false. As long as the condition remains true, Windows PowerShell reruns the <statement list> section. The <statement list> section of the statement contains one or more commands that are run each time the loop is entered or repeated. For example, the following While statement displays the numbers 1 through 3 if the $val variable has not been created or if the $val variable has been created and initialized to 0. while($val -ne 3) { $val++ Write-Host $val } In this example, the condition ($val is not equal to 3) is true while $val = 0, 1, 2. Each time through the loop, $val is incremented by 1 using the ++ unary increment operator ($val++). The last time through the loop, $val = 3. When $val equals 3, the condition statement evaluates to false, and the loop exits. To conveniently write this command at the Windows PowerShell command prompt, you can enter it in the following way: while($val -ne 3){$val++; Write-Host $val} Notice that the semicolon separates the first command that adds 1 to $val from the second command that writes the value of $val to the console. SEE ALSO about_Comparison_Operators about_Foreach about_For about_wildcards TOPIC about_Wildcards SHORT DESCRIPTION Describes how to use wildcard characters in Windows PowerShell. LONG DESCRIPTION In many cases, you will want to run a cmdlet against a group of items rather than an individual item. For example, you might want to locate all the files in the C:\Techdocs directory that have a .ppt file name extension. If you were to run the following command, it would return all the items in the directory: Get-ChildItem c:\techdocs The problem with this command is that you would have to visually inspect all the documents listed in the directory to determine which files use the .ppt file name extension. However, you can limit the items that are returned by using wildcard characters in a cmdlet's parameters. A wildcard character is a type of placeholder that allows you to search unknown values in order to return specific results. The process of using wildcard characters is sometimes referred to as "globbing". For example, you can recast the previous example so that only .ppt files are returned: Get-ChildItem c:\techdocs\*.ppt In this case, the asterisk (*) is used as a wildcard character to specify that any characters can exist before the .ppt file name extension. Because the file name extension is included, all files returned by the command must have that file name extension, but the files can have any name. As a result, only the files that you are looking for are returned. Windows PowerShell supports several wildcard characters in addition to the asterisk wildcard character. Wildcard Description Example Match No match -------- ------------------ -------- ----------------- -------- * Matches zero or a* A, ag, Apple banana more characters ? Matches exactly ?n an, in, on ran one character in the specified position [ ] Matches a range [a-l]ook book, cook, look took of characters [ ] Matches specified [bc]ook book, cook hook characters Most cmdlets accept wildcard characters in some of their parameters. The Help topic for each cmdlet describes which parameters, if any, permit wildcard characters. For parameters in which wildcard characters are accepted, their use is case insensitive. For example, ?n will return An, an, In, in, On, and on. You can also mix wildcard characters within a single parameter. For example, suppose that you want to display all the .txt files in the C:\Techdocs directory that begin with the letters a through l. You can use the following command: Get-ChildItem c:\techdocs\[a-l]*.txt The command uses a range wildcard ([a-l]) to specify that the file name should begin with the letters a through l. The command then uses the asterisk wildcard character to provide a placeholder for any characters between the first letter and the file name extension. SEE ALSO about_Language_Keywords about_Windows_PowerShell_2.0 TOPIC about_Windows_PowerShell_2.0 SHORT DESCRIPTION Describes the new features that are included in Windows PowerShell 2.0. LONG DESCRIPTION Windows PowerShell 2.0 includes several significant features that extend its use, improve its usability, and allow you to control and manage Windows-based environments more easily and comprehensively. Windows PowerShell 2.0 is backward compatible. Cmdlets, providers, snap-ins, scripts, functions, and profiles that were designed for Windows PowerShell 1.0 work in Windows PowerShell 2.0 without changes. NEW FEATURES Windows PowerShell 2.0 includes the following new features. Remoting Windows PowerShell 2.0 lets you run commands on one or many remote computers with a single Windows PowerShell command. You can run individual commands, or you can create a persistent connection (a session) to run a series of related commands. You can also start a session with a remote computer so that the commands you type run directly on the remote computer. The remoting features of Windows PowerShell are built on Windows Remote Management (WinRM). WinRM is the Microsoft implementation of the WS-Management protocol, a standard SOAP-based, firewall-compatible communications protocol. The remote computers must have Windows PowerShell 2.0, the Microsoft .NET Framework 2.0, and the WinRM service. Remote commands are supported on all operating systems that can run Windows PowerShell. The current user must have permission to run commands on the remote computers. For more information, see about_Remote_Requirements. To support remoting, the Invoke-Command, Enter-PSSession, and Exit-PSSession cmdlets have been added, along with other cmdlets that contain the PSSession noun. These cmdlets let you create and manage persistent connections. The ComputerName parameter has also been added to several cmdlets, including the Get-Process, Get-Service, and Get-Eventlog cmdlets. This parameter allows you to get information about remote computers. These cmdlets use .NET Framework methods to get their data, so they do not rely on Windows PowerShell remoting. They do not require any new programs or configuration. For more information, see the Help for each cmdlet. For more information about remote commands, see about_Remote and about_Remote_FAQ. For more information about sessions, see about_PSSessions. Windows PowerShell ISE Windows PowerShell 2.0 includes Windows PowerShell Integrated Scripting Environment (ISE), a host application that lets you run commands, and design, write, test, and debug scripts in a graphical, color-coded, Unicode-based environment. Windows PowerShell ISE requires the Microsoft .NET Framework 3.0 or later. Windows PowerShell ISE includes: - A Command pane that lets you run interactive commands just as you would in the Windows PowerShell console. Just type a command, and then press ENTER. The output appears in the Output pane. - A Script pane that lets you compose, edit, debug, and run functions and scripts. - Multiple tabs, each with its own Command and Script pane, that let you work on one or several tasks independently. Windows PowerShell ISE is designed for both novice and advanced users. Background Jobs Background jobs are commands that run asynchronously. When you run a background job, the command prompt returns immediately, even if the command is still running. You can use the background job feature to run a complex command in the background so that you can use your session for other work while the command runs. You can run a background job on a local or remote computer and then save the results on the local or remote computer. To run a job remotely, use the Invoke-Command cmdlet. Windows PowerShell includes a set of cmdlets that contain the Job noun (the Job cmdlets). Use these cmdlets for creating, starting, managing, and deleting background jobs and for getting the results of a background job. To get a list of the job cmdlets, type the following command: get-command *-job For more information about background jobs, see about_Jobs. Script Debugger Windows PowerShell 2.0 includes a cmdlet-based debugger for scripts and functions. The debugger is supported by a fully documented public API that you can use to build your own debugger or to customize or extend the debugger. The debugger cmdlets let you set breakpoints on lines, columns, variables, and commands. These cmdlets let you manage the breakpoints and display the call stack. You can create conditional breakpoints and specify custom actions at a breakpoint, such as running diagnostic and logging scripts. When you reach a breakpoint, Windows PowerShell suspends execution and starts the debugger. The debugger includes a set of custom commands that let you step through the code. You can also run standard Windows PowerShell commands to display the values of variables, and you can use cmdlets to investigate the results. For more information about debugging, see about_Debuggers. Data Section Scripts designed for Windows PowerShell 2.0 can have one or more DATA sections that isolate the data from the script logic. The data in the new DATA section is restricted to a specified subset of the Windows PowerShell scripting language. In Windows PowerShell 2.0, the DATA section is used to support script internationalization. You can use the DATA section to isolate and identify user message strings that will be translated into multiple user interface languages. For more information, see about_Data_Sections. Script Internationalization Windows PowerShell 2.0 script internationalization features allow you to better serve users throughout the world. Script internationalization enables scripts and functions to display messages and Help text to users in multiple languages. The script internationalization features query the operating system user interface culture ($PsUICulture) during execution and then import the appropriate translated text strings so you can display them to the user. The Data section lets you store text strings separate from code so that they are easily identified. A new cmdlet, ConvertFrom-StringData, converts text strings into dictionary-like hash tables to facilitate translation. For more information, see about_Script_Internationalization. WMI Cmdlets The Windows Management Instrumentation (WMI) functionality of Windows PowerShell 2.0 is improved with the addition of the following cmdlets: - Remove-WmiObject - Set-WmiInstance - Invoke-WmiMethod New parameters have been added to the Get-WmiObject cmdlet. All the WMI cmdlets now support the following parameters: - EnableAllPrivileges - Impersonation - Authentication - Authority These new parameters give you more refined control over the security configuration of your WMI operations without requiring you to work directly with the types in the .NET Framework Class Library. For a list of WMI cmdlets, type the following command: get-help *wmi* To get help for each cmdlet, type get-help followed by the cmdlet name. The Get-WinEvent Cmdlet The Get-WinEvent cmdlet gets events from Event Viewer logs and from Event Tracing for Windows (ETW) event log files on local and remote computers. It can get events from classic event logs and from the Windows Event Logs that were introduced in Windows Vista. You can use Get-WinEvent to get the objects that represent event logs, ev ent log providers, and the events in the logs. Get-WinEvent lets you combine events from different sources in a single command. It supports advanced queries in XML Path Language (XPath), XML, and hash table format. Get-WinEvent requires Windows Vista or Windows Server 2008 and the Microsoft .NET Framework 3.5. The Out-Gridview Cmdlet The Out-GridView cmdlet displays the results of other commands in an interactive table in which you can search, sort, group, and filter the results. For example, you can send the results of a Get-Process, Get-WmiObject, Get-WinEvent, or Get-Eventlog command to Out-GridView and then use the table features to examine the data. help out-gridview -full The Add-Type Cmdlet The Add-Type cmdlet lets you add .NET Framework types to Windows PowerShell from the source code of another .NET Framework language. Add-Type compiles the source code that creates the types and generates assemblies that contain the new .NET Framework types. Then, you can use the .NET Framework types in Windows PowerShell commands along with the standard object types provided by the .NET Framework. You can also use Add-Type to load assemblies into your session so that you can use the types in the assemblies in Windows PowerShell. Add-Type allows you develop new .NET Framework types, to use .NET Framework types in C# libraries, and to access Win32 APIs. For more information, see Add-Type. Event Notification Windows PowerShell 2.0 introduces event notification. Users can register and subscribe to events, such as Windows PowerShell events, WMI events, or .NET Framework events. And, users can listen, forward, and act on management and system events both synchronously and asynchronously. Developers can write applications that use the event architecture to receive notification about state changes. Users can write scripts that subscribe to various events and that react to the content. Windows PowerShell provides cmdlets that create new events, get events and event subscriptions, register and unregister events, wait for events, and delete events. For more information about these cmdlets, type the following command: get-command *-event Modules Windows PowerShell modules let you divide and organize your Windows PowerShell scripts into independent, self-contained, reusable units. Code from a module executes in its own context, so it does not add to, conflict with, or overwrite the variables, functions, aliases, and other resources in the session. You can write, distribute, combine, share, and reuse modules to build simple scripts and complex applications. Windows PowerShell 2.0 includes cmdlets to add, get, and remove modules and to export module members. For more information about the cmdlets that are related to modules, type the following command: get-command *-module* Transactions Windows PowerShell 2.0 includes support for transactions. Transactions let you undo an entire series of operations. Transactions are available only for operations that support transactions. They are designed for applications that require atomicity, consistency, isolation, and recoverability, like databases and message queuing. Cmdlets and providers that support transactions have a new UseTransaction parameter. To start an operation within a transaction, use the Start-Transaction cmdlet. Then, when you use the cmdlets that perform the operation, use the UseTransaction parameter of each cmdlet when you want the command to be part of a transaction. If any command in the transaction fails at any point, use the Rollback-Transaction cmdlet to undo all the commands in the transaction. If all the commands succeed, use the Commit-Transaction cmdlet to make the command actions permanent. Windows PowerShell 2.0 includes cmdlets to start, use, commit, and roll back transactions. For information about these cmdlets, type the following command: get-command *transaction* Breaking Changes to Windows PowerShell 1.0 -- The value of the PowerShellVersion registry entry in HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine is changed to 2.0. -- New cmdlets and variables have been added. These additions might conflict with variables and functions in profiles and scripts. -- The -IEQ operator performs a case insensitive comparison on characters. -- The Get-Command cmdlet gets functions by default, in addition to cmdlets. -- Native commands that generate a user interface cannot be piped to the Out-Host cmdlet. -- The new Begin, Process, End, and Dynamic Param language keywords might conflict with similar words used in scripts and functions. Interpreting these words as language keywords might result in parsing errors. -- Cmdlet name resolution has changed. In Windows PowerShell 1.0, a runtime error was generated when two Windows PowerShell snap-ins exported cmdlets with the same name. In Windows PowerShell 2.0, the last cmdlet that is added to the session runs when you type the command name. To run a command that does not run by default, qualify the cmdlet name with the name of the snap-in or module in which it originated. -- A function name followed by '-?' gets the help topic for the function, if one is included in the function. -- Parameter resolution for Microsoft .Net Frameword methods have changed. In Windows PowerShell 1.0, if you called an overloaded .NET method that has more than one best fit syntax, no error was reported. In Windows PowerShell 2.0, an ambiguity error is reported. In addition, in Windows PowerShell 2.0, the algorithm for choosing the best fit method has been revised significantly to minimize the number of ambiguities. -- If you are enumerating a collection in the pipeline and you try to modify the collection in the pipeline, Windows PowerShell throws an exception. For example, the following commands would work in Windows PowerShell 1.0, but would fail after first pipeline iteration in Windows PowerShel 2.0. $h = @{Name="Hello"; Value="Test"} $h.keys | foreach-object {$h.remove($_)} To avoid this error, create a sub-expression for the enumerator by using the $() characters. For example: $($h.keys) | foreach-object {$h.remove($_)} For more information about Windows PowerShell 2.0, visit the following Web sites: -- Windows PowerShell Web Site http://go.microsoft.com/fwlink/?LinkID=106031 -- Windows PowerShell Team Blog: http://go.microsoft.com/fwlink/?LinkId=143696 SEE ALSO about_Data_Sections about_Debuggers about_Functions_Advanced about_Jobs about_Join about_PSSessions about_Remote about_Script_Internationalization about_Split about_Windows_PowerShell_ISE TOPIC about_Windows_PowerShell_ISE SHORT DESCRIPTION Describes the features and system requirements of Windows PowerShell Integrated Scripting Environment (ISE). LONG DESCRIPTION Windows PowerShell ISE is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphical user interface. Its features include multiline editing, tab completion, syntax coloring, selective execution, context-sensitive Help, and support for right-to-left languages. Notes: Because this feature requires a user interface, it does not work on Server Core installations of Windows Server. Window PowerShell ISE is built on the Windows Presentation Foundation (WPF). If the graphical elements of Windows PowerShell ISE do not render correctly on your system, you might resolve the problem by adding or adjusting the graphics rendering settings on your system. This might be required if the computer has an older video driver or you are using virtualization software. For more information, see "Graphics Rendering Registry Settings" in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=144711. Running Interactive Commands You can run any Windows PowerShell expression or command in Windows PowerShell ISE. You can use cmdlets, providers, snap-ins, and modules as you would use them in the Windows PowerShell console. You can type or paste interactive commands in the Command pane. To run the commands, you can use buttons, menu items, and keyboard shortcuts. You can use the multiline editing feature to type or paste several lines of code into the Command pane at once. When you press the UP ARROW key to recall the previous command, all the lines in the command are recalled. When you type commands, press SHIFT+ENTER to make a new blank line appear under the current line. Viewing Output The results of commands and scripts are displayed in the Output pane. You can move or copy the results from the Output pane by using keyboard shortcuts or the Output toolbar, and you can paste the results in other programs. You can also clear the Output pane by clicking the Clear Output button or by typing one of the following commands: clear-host cls Writing Scripts and Functions In the Script pane, you can open, compose, edit, and run scripts. The Script pane lets you edit scripts by using buttons and keyboard shortcuts. You can also copy, cut, and paste text between the Script pane and the Command pane. You can use the selective run feature to run all or part of a script. To run part of a script, select the text you want to run, and then click the Run Script button. Or, press F5. Debugging Scripts You can use the Windows PowerShell ISE debugger to debug a Windows PowerShell script or function. When you debug a script, you can use menu items and shortcut keys to perform many of the same tasks that you would perform in the Windows PowerShell console. For example, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint. You can also use the Windows PowerShell debugger cmdlets in the Command pane just as you would use them in the console. Tab Completion Windows PowerShell ISE has tab completion for cmdlet names, parameter names, and Microsoft .NET Framework static types. To use tab completion, type the beginning of the name, and then press the TAB key. Getting Help Windows PowerShell ISE includes a searchable compiled Help file that describes Windows PowerShell ISE and Windows PowerShell. This Help file includes all the Help that is available from the Get-Help cmdlet. To view the Help file in Windows PowerShell ISE, use the Help menu. Or, press F1. The Help is context sensitive. For example, if you type Invoke-Item and then press F1, the Help file opens to the Help topic for the Invoke-Item cmdlet. And, you can use the Get-Help cmdlet in Windows PowerShell as you would in the Windows PowerShell console. Customizing the View You can use Windows PowerShell ISE features to move and to resize the Command pane, the Output pane, and the Script pane. You can show and hide the Script pane, and you can change the text size in all the panes. You can also use the $Host variable to change some aspects of the appearance of Windows PowerShell ISE, including the window title and the foreground and background colors in the Output pane. In addition, Windows PowerShell ISE has its own custom host variable, $psgHost. You can use this variable to customize Windows PowerShell ISE, including adding menus and menu items. Windows PowerShell ISE Profile Windows PowerShell ISE has its own Windows PowerShell profile, Microsoft.PowerShellISE_profile.ps1. In this profile, you can store functions, aliases, variables, and commands that you use in Windows PowerShell ISE. Items in the Windows PowerShell AllHosts profiles (CurrentUser\AllHosts and AllUsers\AllHosts) are also available in Windows PowerShell ISE, just as they are in any Windows PowerShell host program. However, the items in your Windows PowerShell console profiles are not available in Windows PowerShell ISE. Instructions for moving and reconfiguring your profiles are available in Windows PowerShell ISE Help and in about_Profiles. System Requirements -Operating Systems: - Windows 7 - Windows Server 2008 - Windows Server 2003 with Service Pack 2 - Windows Vista with Service Pack 1 - Windows XP with Service Pack 2 - Microsoft .NET Framework 3.0 - Windows PowerShell remoting requires Windows Remote Management 2.0. Notes - The Get-WinEvent cmdlet requires Windows Vista and later versions of Windows and the Microsoft .NET Framework 3.5. - The Export-Counter cmdlet runs only in Windows 7. Starting Windows PowerShell ISE - To start Windows PowerShell ISE, click Start, point to All Programs, point to Windows PowerShell, and then click Windows PowerShell ISE. - In the Windows PowerShell console, Cmd.exe, or in the Run box, type "powershell_ise.exe". SEE ALSO about_Profiles Get-Help about_WMI_Cmdlets TOPIC about_WMI_cmdlets SHORT DESCRIPTION Provides background information about Windows Management Instrumentation (WMI) and Windows PowerShell. LONG DESCRIPTION This topic provides information about WMI technology, the WMI cmdlets for Windows PowerShell, WMI-based remoting, WMI accelerators, and WMI troubleshooting. This topic also provides links to more information about WMI. About WMI Windows Management Instrumentation (WMI) is the Microsoft implementation of Web-Based Enterprise Management (WBEM), which is an industry initiative to develop a standard technology for accessing management information in an enterprise environment. WMI uses the Common Information Model (CIM) industry standard to represent systems, applications, networks, devices, and other managed components. CIM is developed and maintained by the Distributed Management Task Force (DMTF). You can use WMI to manage both local and remote computers. For example, you can use WMI to do the following: -- Start a process on a remote computer. -- Restart a computer remotely. -- Get a list of the applications that are installed on a local or remote computer. -- Query the Windows event logs on a local or remote computer. The WMI Cmdlets for Windows PowerShell Windows PowerShell implements WMI functionality through a set of cmdlets that are available in Windows PowerShell by default. You can use these cmdlets to complete the end-to-end tasks necessary to manage local and remote computers. The following WMI cmdlets are included. Cmdlet Description ------------------ ---------------------------------------------- Get-WmiObject Gets instances of WMI classes or information about the available classes. Invoke-WmiMethod Calls WMI methods. Register-WmiEvent Subscribes to a WMI event. Remove-WmiObject Deletes WMI classes and instances. Set-WmiInstance Creates or modifies instances of WMI classes. Sample Commands The following command displays the BIOS information for the local computer. C:\PS> get-wmiobject win32_bios | format-list * The following command displays information about the WinRM service for three remote computers. C:\PS> get-wmiobject -query "select * from win32_service where name=' WinRM'" -computername server01, server01, server03 The following more complex command exits all instances of a program. C:\PS> notepad.exe C:\PS> $np = get-wmiobject -query "select * from win32_process where name='notepad.exe'" C:\PS> $np | remove-wmiobject WMI-Based Remoting While the ability to manage a local system through WMI is useful, it is the remoting capabilities that make WMI a powerful administrative tool. WMI uses Microsoft's Distributed Component Object Model (DCOM) to connect to and manage systems. You might have to configure some systems to allow DCOM connections. Firewall settings and locked-down DCOM permissions can block WMI's ability to remotely manage systems. WMI Type Accelerators Windows PowerShell includes WMI type accelerators. These WMI type accelerators (shortcuts) allow more direct access to a WMI objects than a non-type accelerator approach would allow. The following type accelerators are supported with WMI: [WMISEARCHER] - A shortcut for searching for WMI objects. [WMICLASS] - A shortcut for accessing the static properties and methods of a class. [WMI] - A shortcut for getting a single instance of a class. [WMISEARCHER] is a type accelerator for a ManagementObjectSearcher. It can take a string constructor to create a searcher that you can then do a GET() on. For example: PS> $s = [WmiSearcher]'Select * from Win32_Process where Handlecount > 10 00' PS> $s.Get() |sort handlecount |ft handlecount,__path,name -auto handlecount __PATH name ----------- ------ ---- 1105 \\SERVER01\root\cimv2:Win32_Process.Handle="3724" powershe ll... 1132 \\SERVER01\root\cimv2:Win32_Process.Handle="1388" winlogon .exe 1495 \\SERVER01\root\cimv2:Win32_Process.Handle="2852" iexplore .exe 1699 \\SERVER01\root\cimv2:Win32_Process.Handle="1204" OUTLOOK. EXE 1719 \\SERVER01\root\cimv2:Win32_Process.Handle="1912" iexplore .exe 2579 \\SERVER01\root\cimv2:Win32_Process.Handle="1768" svchost. exe [WMICLASS] is a type accelerator for ManagementClass. This has a string constructor that takes a local or absolute WMI path to a WMI class and returns an object that is bound to that class. For example: PS> $c = [WMICLASS]"root\cimv2:WIn32_Process" PS> $c |fl * Name : Win32_Process __GENUS : 1 __CLASS : Win32_Process __SUPERCLASS : CIM_Process __DYNASTY : CIM_ManagedSystemElement __RELPATH : Win32_Process __PROPERTY_COUNT : 45 __DERIVATION : {CIM_Process, CIM_LogicalElement, CIM_ManagedSystemEle ment} __SERVER : SERVER01 __NAMESPACE : ROOT\cimv2 __PATH : \\SERVER01\ROOT\cimv2:Win32_Process [WMI] is a type accelerator for ManagementObject. This has a string constructor that takes a local or absolute WMI path to a WMI instance and returns an object that is bound to that instance. For example: PS> $p = [WMI]'\\SERVER01\root\cimv2:Win32_Process.Handle="1204"' PS> $p.Name OUTLOOK.EXE WMI Troubleshooting The following problems are the most common problems that might occur when you try to connect to a remote computer. Problem 1: The remote computer is not online. If a computer is offline, you will not be able to connect to it by using WMI. You may receive the following error message: "Remote server machine does not exist or is unavailable" If you receive this error message, verify that the computer is online. Try to ping the remote computer. Problem 2: You do not have local administrator rights on the remote computer. To use WMI remotely, you must have local administrator rights on the remote computer. If you do not, access to that computer will be denied. To verify namespace security: a. Click Start, right-click My Computer, and then click Manage. b. In Computer Management, expand Services and Applications, right-click WMI Control, and then click Properties. c. In the WMI Control Properties dialog box, click the Security tab. Problem 3: A firewall is blocking access to the remote computer. WMI uses the DCOM (Distributed COM) and RPC (Remote Procedure Call) protocols to traverse the network. By default, many firewalls block DCOM and RPC traffic. If your firewall is blocking these protocols, your connection will fail. For example, Windows Firewall in Microsoft Windows XP Service Pack 2 is configured to automatically block all unsolicited network traffic, including DCOM and WMI. In its default configuration, Windows Firewall rejects an incoming WMI request, and you receive the following error message: "Remote server machine does not exist or is unavailable" More Information about WMI For more information about WMI, see the following topics in the MSDN (Microsoft Developer Network) library: "About WMI: http://go.microsoft.com/fwlink/?LinkId=142212 "WMI Troubleshooting" http://go.microsoft.com/fwlink/?LinkId=142213 And, see "Secrets of Windows Management Instrumentation - Troubleshooting and Tips" in the Microsoft TechNet Script Center: http://go.microsoft.com/fwlink/?LinkId=142214 SEE ALSO Online version: http://go.microsoft.com/fwlink/?LinkId=142219 Get-WmiObject Invoke-WmiMethod Register-WmiEvent Remove-WmiObject Set-WmiInstance about_WS-Management_Cmdlets TOPIC about_WS-Management_Cmdlets SHORT DESCRIPTION Provides an overview of Web Services for Management (WS-Management) as background for using the WS-Management cmdlets in Windows PowerShell. LONG DESCRIPTION This topic provides an overview of Web Services for Management (WS-Management) as background for using the WS-Management cmdlets in Windows PowerShell. This topic also provides links to more information about WS-Management. The Microsoft implementation of WS-Management is also known as Windows Remote Management (WinRM). About WS-Management Windows Remote Management is the Microsoft implementation of the WS-Management protocol, a standard SOAP-based, firewall-friendly protocol that allows hardware and operating systems from different vendors to interoperate. The WS-Management protocol specification provides a common way for systems to access and exchange management information across an information technology (IT) infrastructure. WS-Management and Intelligent Platform Management Interface (IPMI), along with the Event Collector, are components of the Windows Hardware Management features. The WS-Management protocol is based on the following standard Web service specifications: HTTPS, SOAP over HTTP (WS-I profile), SOAP 1.2, WS-Addressing, WS-Transfer, WS-Enumeration, and WS-Eventing. WS-Management and WMI WS-Management can be used to retrieve data exposed by Windows Management Instrumentation (WMI). You can obtain WMI data with scripts or applications that use the WS-Management Scripting API or through the WinRM command-line tool. WS-Management supports most of the familiar WMI classes and operations, including embedded objects. WS-Management can leverage WMI to collect data about resources or to manage resources on a Windows-based computers. That means that you can obtain data about objects such as disks, network adapters, services, or processes in your enterprise through the existing set of WMI classes. You can also access the hardware data that is available from the standard WMI IPMI provider. WS-Management Windows PowerShell Provider The WS-Management provider provides a hierarchical view into the available WS-Management configuration settings. The provider allows you to explore and set the various WS-Management configuration options. WS-Management Configuration If WS-Management is not installed and configured, Windows PowerShell remoting is not available, the WS-Management cmdlets do not run, WS-Management scripts do not run, and the WS-Management provider cannot perform data operations. The WS-Management command-line tool, WinRM, and event forwarding also depend on the WS-Management configuration. WS-Management Cmdlets WS-Management functionality is implemented in Windows PowerShell through a module that contains a set of cmdlets and the WS-Management provider. You can use these cmdlets to complete the end-to-end tasks necessary to manage WS-Management settings on local and remote computers. The following WS-Management cmdlets are available. Connection Cmdlets -- Connect-WSMan: Connects the local computer to the WS-Management (WinRM) service on a remote computer. -- Disconnect-WSMan: Disconnects the local computer from the WS-Management (WinRM) service on a remote computer. Management-Data Cmdlets -- Get-WSManInstance: Displays management information for a resource instance that is specified by a resource URI. -- Invoke-WSManAction: Invokes an action on the target object that is specified by the resource URI and by the selectors. -- New-WSManInstance: Creates a new management resource instance. -- Remove-WSManInstance: Deletes a management resource instance. -- Set-WSManInstance: Modifies the management information that is related to a resource. Setup and Configuration Cmdlets -- Set-WSManQuickConfig: Configures the local computer for remote management. You can use the Set-WSManQuickConfig cmdlet to configure WS-Management to allow remote connections to the WS-Management (WinRM) service. The Set-WSManQuickConfig cmdlet performs the following operations: - It determines whether the WS-Management (WinRM) service is running. If the WinRM service is not running, the Set-WSManQuickConfig cmdlet starts the service. - It sets the WS-Management (WinRM) service startup type to automatic. - It creates a listener that accepts requests from any IP address. The default transport protocol is HTTP. - It enables a firewall exception for WS-Management traffic. Note: To run this cmdlet in Windows Vista, Windows Server 2008, and later versions of Windows, you must start Windows PowerShell with the "Run as administrator" option. -- Test-WSMan: Verifies that WS-Management is installed and configured. The Test-WSMan cmdlet tests whether the WS-Management (WinRM) service is running and configured on a local or remote computer. -- Disable-WSManCredSSP: Disables CredSSP authentication on a client computer. -- Enable-WSManCredSSP: Enables CredSSP authentication on a client computer. -- Get-WSManCredSSP: Gets the CredSSP-related configuration for a client computer. WS-Management-Specific Cmdlets -- New-WSManSessionOption: Creates a WSManSessionOption object to use as input to one or more parameters of a WS-Management cmdlet. Additional WS-Management Information For more information about WS-Management, see the following topics in the MSDN (Microsoft Developer Network) library. "Windows Remote Management" http://go.microsoft.com/fwlink/?LinkId=142321 "About Windows Remote Management" http://go.microsoft.com/fwlink/?LinkId=142322 "Installation and Configuration for Windows Remote Management" http://go.microsoft.com/fwlink/?LinkId=142323 "Windows Remote Management Architecture" http://go.microsoft.com/fwlink/?LinkId=142324 "WS-Management Protocol" http://go.microsoft.com/fwlink/?LinkId=142325 "Windows Remote Management and WMI" http://go.microsoft.com/fwlink/?LinkId=142326 "Resource URIs" http://go.microsoft.com/fwlink/?LinkId=142327 "Remote Hardware Management" http://go.microsoft.com/fwlink/?LinkId=142328 "Events" http://go.microsoft.com/fwlink/?LinkId=142329 SEE ALSO Online version: http://go.microsoft.com/fwlink/?LinkId=142331 Connect-WSMan Disable-WSManCredSSP Disconnect-WSMan Enable-WSManCredSSP Get-WSManCredSSP Get-WSManInstance Invoke-WSManAction New-WSManInstance Remove-WSManInstance Set-WSManInstance Set-WSManQuickConfig Set-WSManSessionOption Test-WSMan KEYWORDS about_WSMAN about_WinRM default TOPIC Get-Help SHORT DESCRIPTION Displays help about Windows PowerShell cmdlets and concepts. LONG DESCRIPTION SYNTAX get-help {<CmdletName> | <TopicName>} help {<CmdletName> | <TopicName>} <CmdletName> -? "Get-help" and "-?" display help on one page. "Help" displays help on multiple pages. Examples: get-help get-process : Displays help about the Get-Process cmdlet. get-help about_signing : Displays help about signing scripts. help where-object : Displays help about the Where-Object cmdlet. help about_foreach : Displays help about foreach loops in PowerShell. set-service -? : Displays help about the Set-Service cmdlet. You can use wildcard characters in the help commands (not with -?). If multiple help topics match, PowerShell displays a list of matching topics. If only one help topic matches, PowerShell displays the topic. Examples: get-help * : Displays all help topics. get-help get-* : Displays topics that begin with get-. help *object* : Displays topics with "object" in the name. get-help about* : Displays all conceptual topics. For information about wildcards, type: get-help about_wildcard REMARKS To learn about Windows PowerShell, read the following help topics: get-command : Gets information about cmdlets from the cmdlet code. get-member : Gets the properties and methods of an object. where-object : Filters object properties. about_object : Explains the use of objects in Windows PowerShell. about_remote : Tells how to run commands on remote computers. Conceptual help files are named "about_<topic>", such as: about_regular_expression. The names of conceptual help files must be entered in English even on non-English versions of Windows PowerShell. The help commands also display the aliases of the cmdlets. These are alternate names or nicknames that are often easier to type. For example, the alias for the Invoke-Command cmdlet is "remote". To get the aliases, type: get-alias