diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md index 7a62b5bef11e..0f745ac3aa94 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,232 +7,246 @@ title: about_Object_Creation --- # About Object Creation -## about_Object_Creation - ## SHORT DESCRIPTION -Explains how to create objects in Windows PowerShell®. +Explains how to create objects in PowerShell. ## LONG DESCRIPTION -You can create objects in Windows PowerShell and use the objects that you create in commands and scripts. - -There are several ways to create objects: - -New-Object: -The New-Object cmdlet creates an instance of a .NET Framework object or COM object. +You can create objects in PowerShell and use the objects that you create in +commands and scripts. -Hash tables: +There are several ways to create objects: -Beginning in Windows PowerShell 3.0, you can create objects from hash tables of property names and property values. +- `New-Object`: This cmdlet creates an instance of a .NET Framework object or + COM object. -Import-Csv: +- Hash tables: Beginning in PowerShell 3.0, you can create objects + from hash tables of property names and property values. -The Import-Csv cmdlet creates custom objects (PSCustomObject) from the items in a CSV file. Each row is an object instance and each column is an object property. +- `Import-Csv`: This cmdlet creates custom objects (PSCustomObject) from the + items in a CSV file. Each row is an object instance and each column is an + object property. This topic will demonstrate and discuss each of these methods. - ## NEW-OBJECT -The New-Object cmdlet provides a robust and consistent way to create new objects. The cmdlet works with almost all types and in all supported versions of Windows PowerShell. -To create a new object, specify either the type of a .NET Framework class or a ProgID of a COM object. +The `New-Object` cmdlet provides a robust and consistent way to create new +objects. The cmdlet works with almost all types and in all supported versions +of PowerShell. -For example, the following command creates a Version object. +To create a new object, specify either the type of a .NET Framework class or a +ProgID of a COM object. +For example, the following command creates a Version object. -``` -PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 +```powershell +PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 PS C:\> $v ``` - - -``` -Major Minor Build Revision ------ ----- ----- -------- +```Output +Major Minor Build Revision +----- ----- ----- -------- 2 0 0 1 ``` +```powershell +PS C:\> $v | Get-Member - -``` -PS C:\> $v | Get-Member - TypeName: System.Version ``` - For more information, see the help topic for the New-Object cmdlet. - ### CREATE OBJECTS FROM HASH TABLES -Beginning in Windows PowerShell 3.0, you can create an object from a hash table of properties and property values. -The syntax is as follows: +Beginning in PowerShell 3.0, you can create an object from a hash table of +properties and property values. +The syntax is as follows: ``` -[]@{=;=} +[]@{ + = + = +} ``` - -This method works only for classes that have a null constructor, that is, a constructor that has no parameters. The object properties must be public and settable. - +This method works only for classes that have a null constructor, that is, a +constructor that has no parameters. The object properties must be public and +settable. ### CREATE CUSTOM OBJECTS FROM HASH TABLES -Custom objects are very useful and they are very easy to create by using the hash table method. To create a custom object, use the PSCustomObject class, a class designed specifically for this purpose. - -Custom objects are an excellent way to return customized output from a function or script; far more useful than returning formatted output that cannot be reformatted or piped to other commands. - -The commands in the Test-Object function set some variable values and then use those values to create a custom object. (You can see this object in use in the example section of the Update-Help cmdlet help topic.) - -``` -function Test-Object -{ $ModuleName = "PSScheduledJob" - $HelpCulture = "en-us" - $HelpVersion = "3.1.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} - - $ModuleName = "PSWorkflow" - $HelpCulture = "en-us" - $HelpVersion = "3.0.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} +Custom objects are very useful and they are very easy to create by using the +hash table method. To create a custom object, use the PSCustomObject class, a +class designed specifically for this purpose. + +Custom objects are an excellent way to return customized output from a +function or script; far more useful than returning formatted output that +cannot be reformatted or piped to other commands. + +The commands in the `Test-Object function` set some variable values and then +use those values to create a custom object. You can see this object in use in +the example section of the `Update-Help` cmdlet help topic. + +```powershell +function Test-Object { + $ModuleName = "PSScheduledJob" + $HelpCulture = "en-us" + $HelpVersion = "3.1.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } + $ModuleName = "PSWorkflow" + $HelpCulture = "en-us" + $HelpVersion = "3.0.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } } ``` +The output of this function is a collection of custom objects formatted as a +table by default. -The output of this function is a collection of custom objects formatted as a table by default. - +```powershell +PS C:\> Test-Object -``` -PS C:\> Test-Object - -ModuleName UICulture Version ---------- --------- ------- -PSScheduledJob en-us 3.1.0.0 +ModuleName UICulture Version +--------- --------- ------- +PSScheduledJob en-us 3.1.0.0 PSWorkflow en-us 3.0.0.0 ``` +Users can manage the properties of the custom objects just as they do with +standard objects. -Users can manage the properties of the custom objects just as they do with standard objects. - - -``` -PS C:\> (Test-Object).ModuleName - PSScheduledJob +```powershell +PS C:\> (Test-Object).ModuleName + PSScheduledJob PSWorkflow ``` - - #### CREATE NON-CUSTOM OBJECTS FROM HASH TABLES -You can also use hash tables to create objects for non-custom classes. When you create an object for a non-custom class, the full namespace name is required unless class is in the System namespace. Use only the properties of the class. -For example, the following command creates a session option object. +You can also use hash tables to create objects for non-custom classes. When +you create an object for a non-custom class, the full namespace name is +required unless class is in the System namespace. Use only the properties of +the class. +For example, the following command creates a session option object. +```powershell +[System.Management.Automation.Remoting.PSSessionOption]@{ + IdleTimeout=43200000 + SkipCnCheck=$True +} ``` -[System.Management.Automation.Remoting.PSSessionOption]@{IdleTimeout=43200000; SkipCnCheck=$True} -``` - -The requirements of the hash table feature, especially the null constructor requirement, eliminate many existing classes. However, most Windows PowerShell option classes are designed to work with this feature, as well as other very useful classes, such as the ScheduledJobTrigger class. +The requirements of the hash table feature, especially the null constructor +requirement, eliminate many existing classes. However, most PowerShell option +classes are designed to work with this feature, as well as other very useful +classes, such as the ScheduledJobTrigger class. +```powershell +[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{ + Frequency="Daily" + At="15:00" +} -``` -[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{Frequency="Daily";At="15:00"} - -Id Frequency Time DaysOfWeek Enabled --- --------- ---- ---------- ------- -0 Daily 6/6/2012 3:00:00 PM True +Id Frequency Time DaysOfWeek Enabled +-- --------- ---- ---------- ------- +0 Daily 6/6/2012 3:00:00 PM True ``` +You can also use the hash table feature when setting parameter values. For +example, the value of the **SessionOption** parameter of the New-PSSession +cmdlet and the value of the JobTrigger parameter of `Register-ScheduledJob` +can be a hash table. -You can also use the hash table feature when setting parameter values. For example, the value of the SessionOption parameter of the New-PSSession cmdlet and the value of the JobTrigger parameter of Register-ScheduledJob can be a hash table. - - -``` -New-PSSession -ComputerName Server01 -SessionOption @{IdleTimeout=43200000; SkipCnCheck=$True} -Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{Frequency="Daily";At="15:00"} +```powershell +New-PSSession -ComputerName Server01 -SessionOption @{ + IdleTimeout=43200000 + SkipCnCheck=$True +} +Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{ + Frequency="Daily" + At="15:00" +} ``` - - ### IMPORT-CSV -You can create custom objects from the items in a CSV file. When you use the Import-Csv cmdlet to import the CSV file, the cmdlet creates a custom object (PSCustomObject) for each item in the file. The column names are the object properties. -For example, if you import a CSV file of computer asset data, Import-CSV creates a collection of custom objects from the input. +You can create custom objects from the items in a CSV file. When you use the +`Import-Csv` cmdlet to import the CSV file, the cmdlet creates a custom object +(PSCustomObject) for each item in the file. The column names are the object +properties. +For example, if you import a CSV file of computer asset data, `Import-CSV` +creates a collection of custom objects from the input. ``` -#In Servers.csv -AssetID, Name, OS, Department -003, Server01, Windows Server 2012, IT -103, Server33, Windows 7, Marketing +#In Servers.csv +AssetID, Name, OS, Department +003, Server01, Windows Server 2012, IT +103, Server33, Windows 7, Marketing 212, Server35, Windows 8, Finance ``` +```powershell +PS C:\> $a = Import-Csv Servers.csv +PS C:\> $a - -``` -PS C:\> $a = Import-Csv Servers.csv -PS C:\> $a - -AssetID Name OS Department -------- ---- -- ---------- -003 Server01 Windows Server 2012 IT -103 Server33 Windows 7 Marketing +AssetID Name OS Department +------- ---- -- ---------- +003 Server01 Windows Server 2012 IT +103 Server33 Windows 7 Marketing 212 Server35 Windows 8 Finance ``` - Use the Get-Member cmdlet to confirm the object type. - -``` +```powershell PS C:\> $a | Get-Member ``` +```Output +TypeName: System.Management.Automation.PSCustomObject - -``` -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() -AssetID NoteProperty System.String AssetID=003 -Department NoteProperty System.String Department=IT -Name NoteProperty System.String Name=Server01 +Name MemberType Definition +---- ---------- ---------- +Equals Method bool Equals(System.Object obj) +GetHashCode Method int GetHashCode() +GetType Method type GetType() +ToString Method string ToString() +AssetID NoteProperty System.String AssetID=003 +Department NoteProperty System.String Department=IT +Name NoteProperty System.String Name=Server01 OS NoteProperty System.String OS=Windows Server 2012 ``` - You can use the custom objects just as you would standard objects. - -``` +```powershell PS C:\> $a | where {$_.OS -eq "Windows 8"} ``` - - -``` -AssetID Name OS Department -------- ---- -- ---------- +```output +AssetID Name OS Department +------- ---- -- ---------- 212 Server35 Windows 8 Finance ``` - For more information, see the help topic for the Import-Csv cmdlet. - ## SEE ALSO [about_Objects](about_Objects.md) @@ -243,9 +257,8 @@ For more information, see the help topic for the Import-Csv cmdlet. [about_Pipelines](about_Pipelines.md) -Get-Member - -Import-Csv +[Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) -New-Object +[Import-Csv](../../Microsoft.PowerShell.Utility/Import-Csv.md) +[New-Object](../../Microsoft.PowerShell.Utility/New-Object.md) diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Objects.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Objects.md index 88ab499af532..58308cabd6d7 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Objects.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Objects.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -58,20 +58,13 @@ directory objects are passed down the pipeline to the second command. The second command `where { $_.PsIsContainer -eq $false }` uses the PsIsContainer property of all file system objects to select only -files, which have a value of False ($false) in their PsIsContainer +files, which have a value of False (\$false) in their PsIsContainer property. Folders, which are containers and, thus, have a value of -True ($true) in their PsIsContainer property, are not selected. +True (\$true) in their PsIsContainer property, are not selected. The second command passes only the file objects to the third command `Format-List`, which displays the file objects in a list. -## For More Information - -Now that you understand a bit about objects, see the [about_Methods](about_Methods.md) -help topic to learn how to find and use object methods, the -[about_Properties](about_Properties.md) topic to learn how to find and use object properties, -and the [Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) topic, to learn how to find an object type. - ## See Also [about_Methods](about_Methods.md) diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md index 6e83191b889c..01d129ccc4bb 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -10,84 +10,85 @@ title: about_Operator_Precedence ## SHORT DESCRIPTION -Lists the Windows PowerShell operators in precedence order. +Lists the PowerShell operators in precedence order. -[This topic was contributed by Kirk Munro, a Windows PowerShell MVP +[This topic was contributed by Kirk Munro, a PowerShell MVP from Ottawa, Ontario] ## LONG DESCRIPTION -Windows PowerShell operators let you construct simple, but powerful -expressions. This topic lists the operators in precedence order. -Precedence order is the order in which Windows PowerShell evaluates -the operators when multiple operators appear in the same expression. - -When operators have equal precedence, Windows PowerShell evaluates -them from left to right. The exceptions are the assignment operators, -the cast operators, and the negation operators (!, -not, -bnot), -which are evaluated from right to left. - -You can use enclosures, such as parentheses, to override the -standard precedence order and force Windows PowerShell to evaluate -the enclosed part of an expression before an unenclosed part. - -In the following list, operators are listed in the order that they -are evaluated. Operators on the same line, or in the same group, have -equal precedence. - -The Operator column lists the operators. The Reference column lists -the Windows PowerShell Help topic in which the operator is described. -To display the topic, type `get-help `. - -|OPERATOR|REFERENCE| -|--------|---------| -|`$() @()`|[about_Operators](#index-operator)| -|`.` (dereference) `::` (static)|[about_Operators](about_Operators.md)| -|`[0]` (index operator)|[about_Operators](about_Operators.md)| +PowerShell operators let you construct simple, but powerful +expressions. This topic lists the operators in precedence order. Precedence +order is the order in which PowerShell evaluates the operators when +multiple operators appear in the same expression. + +When operators have equal precedence, PowerShell evaluates them from +left to right. The exceptions are the assignment operators, the cast +operators, and the negation operators (!, -not, -bnot), which are evaluated +from right to left. + +You can use enclosures, such as parentheses, to override the standard +precedence order and force PowerShell to evaluate the enclosed part of +an expression before an unenclosed part. + +In the following list, operators are listed in the order that they are +evaluated. Operators on the same line, or in the same group, have equal +precedence. + +The Operator column lists the operators. The Reference column lists the +PowerShell Help topic in which the operator is described. To display +the topic, type `get-help `. + +|OPERATOR |REFERENCE| +|------------------------|---------| +|`$() @()` |[about_Operators](#index-operator)| +|`.` (dereference) |[about_Operators](about_Operators.md)| +|`::` (static) |[about_Operators](about_Operators.md)| +|`[0]` (index operator) |[about_Operators](about_Operators.md)| |`[int]` (cast operators)|[about_Operators](about_Operators.md)| -|`-split` (unary)
`-join` (unary)|[about_Split](about_Split.md)
[about_Join](about_Join.md)| -|`,` (comma operator)|[about_Operators](about_Operators.md)| -|`++ --`|[about_Assignment_Operators](about_Assignment_Operators.md)| -|`-not`
`! -bNot`|[about_Logical_Operators](about_logical_operators.md)
[about_Comparison_Operators](about_Comparison_Operators.md)| -|`..` (range operator)|[about_Operators](about_Operators.md)| -|`-f` (format operator)|[about_Operators](about_Operators.md)| -|`* / %`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`+ -`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| - - -The following group of operators have equal precedence. Their -case-sensitive and explicitly case-insensitive variants have -the same precedence. - -|OPERATOR|REFERENCE| -|--------|---------| -|`-split` (unary)|[about_Split](about_Split.md)| -|`-join` (unary)|[about_Join](about_Join.md)| -|`-is -isnot -as`|[about_Type_Operators](about_Type_Operators.md)| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`,` (comma operator) |[about_Operators](about_Operators.md)| +|`++ --` |[about_Assignment_Operators](about_Assignment_Operators.md)| +|`-not` |[about_Logical_Operators](about_logical_operators.md)| +|`! -bNot` |[about_Comparison_Operators](about_Comparison_Operators.md)| +|`..` (range operator) |[about_Operators](about_Operators.md)| +|`-f` (format operator) |[about_Operators](about_Operators.md)| +|`* / % + -` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| + +The following group of operators have equal precedence. Their case-sensitive +and explicitly case-insensitive variants have the same precedence. + +|OPERATOR |REFERENCE| +|-------------------------|---------| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`-is -isnot -as` |[about_Type_Operators](about_Type_Operators.md)| |`-eq -ne -gt -gt -lt -le`|[about_Comparison_Operators](about_Comparison_Operators.md)| -|`-like -notlike`|[about_comparison_operators](about_comparison_operators.md)| -|`-match -notmatch`|[about_comparison_operators](about_comparison_operators.md)| -|`-in -notIn`|[about_comparison_operators](about_comparison_operators.md)| -|`-contains -notContains`|[about_comparison_operators](about_comparison_operators.md)| -|`-replace`|[about_comparison_operators](about_comparison_operators.md)| +|`-like -notlike` |[about_comparison_operators](about_comparison_operators.md)| +|`-match -notmatch` |[about_comparison_operators](about_comparison_operators.md)| +|`-in -notIn` |[about_comparison_operators](about_comparison_operators.md)| +|`-contains -notContains` |[about_comparison_operators](about_comparison_operators.md)| +|`-replace` |[about_comparison_operators](about_comparison_operators.md)| The list resumes here with the following operators in precedence order: -|OPERATOR|REFERENCE| -|--------|---------| -|`-band -bor -bxor`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`-and -or -xor`|[about_comparison_operators](about_comparison_operators.md)| -|`.` (dot-source)
`&` (call)|[about_Scopes](about_Scopes.md)
[about_Operators](about_Operators.md)| +|OPERATOR |REFERENCE| +|--------------------------|---------| +|`-band -bor -bxor` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| +|`-and -or -xor` |[about_comparison_operators](about_comparison_operators.md)| +|`.` (dot-source) |[about_Scopes](about_Scopes.md)| +|`&` (call) |[about_Operators](about_Operators.md)| || (pipeline operator)|[about_Operators](about_Operators.md)| -|`> >> 2> 2>> 2>&1`|[about_Redirection](about_Redirection.md)| -|`= += -= *= /= %=`|[about_Assignment_Operators](about_Assignment_Operators.md)| +|`> >> 2> 2>> 2>&1` |[about_Redirection](about_Redirection.md)| +|`= += -= *= /= %=` |[about_Assignment_Operators](about_Assignment_Operators.md)| # EXAMPLES -The following two commands show the arithmetic operators and -the effect of using parentheses to force Windows PowerShell to -evaluate the enclosed part of the expression first. +The following two commands show the arithmetic operators and the effect of +using parentheses to force PowerShell to evaluate the enclosed part of +the expression first. ```powershell C:\PS> 2 + 3 * 4 @@ -97,8 +98,8 @@ C:\PS> (2 + 3) * 4 20 ``` -The following example gets the read-only text files from the local -directory and saves them in the `$read_only` variable. +The following example gets the read-only text files from the local directory +and saves them in the `$read_only` variable. ```powershell $read_only = get-childitem *.txt | where-object {$_.isReadOnly} @@ -109,37 +110,37 @@ It is equivalent to the following example. $read_only = ( get-childitem *.txt | where-object {$_.isReadOnly} ) ``` -Because the pipeline operator (|) has a higher precedence than the -assignment operator (=), the files that the Get-ChildItem cmdlet -gets are sent to the Where-Object cmdlet for filtering before they -are assigned to the $read_only variable. +Because the pipeline operator (|) has a higher precedence than the assignment +operator (=), the files that the Get-ChildItem cmdlet gets are sent to the +Where-Object cmdlet for filtering before they are assigned to the $read_only +variable. -The following example demonstrates that the index operator takes -precedence over the cast operator. +The following example demonstrates that the index operator takes precedence +over the cast operator. -The first expression creates an array of three strings. Then, it -uses the index operator with a value of 0 to select the first object -in the array, which is the first string. Finally, it casts the -selected object as a string. In this case, the cast has no effect. +The first expression creates an array of three strings. Then, it uses the +index operator with a value of 0 to select the first object in the array, +which is the first string. Finally, it casts the selected object as a string. +In this case, the cast has no effect. ```powershell C:\PS> [string]@('Windows','PowerShell','2.0')[0] Windows ``` -The second expression uses parentheses to force the cast operation -to occur before the index selection. As a result, the entire array -is cast as a (single) string. Then, the index operator selects -the first item in the string array, which is the first character. +The second expression uses parentheses to force the cast operation to occur +before the index selection. As a result, the entire array is cast as a +(single) string. Then, the index operator selects the first item in the string +array, which is the first character. ```powershell C:\PS> ([string]@('Windows','PowerShell','2.0'))[0] W ``` -In the following example, because the -gt (greater-than) operator -has a higher precedence than the -and (logical AND) operator, the -result of the expression is FALSE. +In the following example, because the -gt (greater-than) operator has a higher +precedence than the -and (logical AND) operator, the result of the expression +is FALSE. ```powershell C:\PS> 2 -gt 4 -and 1 @@ -160,11 +161,11 @@ C:\PS> 2 -gt (4 -and 1) True ``` -However, this example demonstrates an important principle of managing -operator precedence. When an expression is difficult for people to -interpret, use parentheses to force the evaluation order, even when it -forces the default operator precedence. The parentheses make your -intentions clear to people who are reading and maintaining your scripts. +However, this example demonstrates an important principle of managing operator +precedence. When an expression is difficult for people to interpret, use +parentheses to force the evaluation order, even when it forces the default +operator precedence. The parentheses make your intentions clear to people who +are reading and maintaining your scripts. ## SEE ALSO @@ -185,4 +186,3 @@ intentions clear to people who are reading and maintaining your scripts. [about_Split](about_Split.md) [about_Type_Operators](about_Type_Operators.md) - diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md index 46c3c136e573..e9c4ebaefa98 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,449 +7,409 @@ title: about_Parameters_Default_Values --- # About Parameters Default Values -## about_Parameters_Default_Values - ## SHORT DESCRIPTION -Describes how to set custom default values for the parameters of cmdlets and advanced functions. +Describes how to set custom default values for the parameters of cmdlets and +advanced functions. ## LONG DESCRIPTION -The $PSDefaultParameterValues preference variable lets you specify custom default values for any cmdlet or advanced function. Cmdlets and functions use the custom default value unless you specify another value in the command. -The authors of cmdlets and advanced functions set standard default values for their parameters. Typically, the standard default values are useful, but they might not be appropriate for all environments. +The \$PSDefaultParameterValues preference variable lets you specify custom +default values for any cmdlet or advanced function. Cmdlets and functions use +the custom default value unless you specify another value in the command. + +The authors of cmdlets and advanced functions set standard default values for +their parameters. Typically, the standard default values are useful, but they +might not be appropriate for all environments. -This feature is especially useful when you must specify the same alternate parameter value nearly every time you use the command or when a particular parameter value is difficult to remember, such as an e-mail server name or project GUID. +This feature is especially useful when you must specify the same alternate +parameter value nearly every time you use the command or when a particular +parameter value is difficult to remember, such as an e-mail server name or +project GUID. -If the desired default value varies predictably, you can specify a script block that provides different default values for a parameter under different conditions. +If the desired default value varies predictably, you can specify a script +block that provides different default values for a parameter under different +conditions. -$PSDefaultParameterValues was introduced in Windows PowerShell® 3.0. +\$PSDefaultParameterValues was introduced in PowerShell 3.0. +## SYNTAX -### SYNTAX The syntax of the $PSDefaultParameterValues preference variable is as follows: +```powershell +$PSDefaultParameterValues=@{":"=""} + +$PSDefaultParameterValues=@{":"={}} -``` -$PSDefaultParameterValues=@{":"=""} - -$PSDefaultParameterValues=@{":"={}} - $PSDefaultParameterValues["Disabled"]=$true | $false ``` - Wildcard characters are permitted in the CmdletName and ParameterName values. -The value of $PSDefaultParameterValues is a System.Management.Automation.DefaultParameterDictionary, a type of hash table that validates the format of keys. Enter a hash table where the key consists of the cmdlet name and parameter name separated by a colon (:) and the value is the custom default value. - -To set, change, add, or remove entries from $PSDefaultParameterValues, use the methods that you would use to edit a standard hash table. +The value of \$PSDefaultParameterValues is a +System.Management.Automation.DefaultParameterDictionary, a type of hash table +that validates the format of keys. Enter a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (:) and the value +is the custom default value. -The must be the name of a cmdlet or the name of an advanced function that uses the CmdletBinding attribute. You cannot use $PSDefaultParameterValues to specify default values for scripts or simple functions. +To set, change, add, or remove entries from \$PSDefaultParameterValues, use the +methods that you would use to edit a standard hash table. -The default value can be an object or a script block. If the value is a script block, Windows PowerShell evaluates the script block and uses the result as the parameter value. When the specified parameter takes a script block value, enclose the script block value in a second set of braces, such as: +The \ must be the name of a cmdlet or the name of an advanced +function that uses the CmdletBinding attribute. You cannot use +$PSDefaultParameterValues to specify default values for scripts or simple +functions. +The default value can be an object or a script block. If the value is a script +block, PowerShell evaluates the script block and uses the result as the +parameter value. When the specified parameter takes a script block value, +enclose the script block value in a second set of braces, such as: -``` +```powershell $PSDefaultParameterValues=@{ "Invoke-Command:ScriptBlock"={{Get-Process}} } ``` +For information about hash tables, see +[about_Hash_Tables](about_Hash_Tables.md). For information about script +blocks, see [about_Script_Blocks](about_Script_Blocks.md). For information +about preference variables, see +[about_Preference_Variables](about_Preference_Variables.md). -For information about hash tables, see about_Hash_Tables. For information about script blocks, see about_Script_Blocks. For information about preference variables, see about_Preference_Variables. - +## EXAMPLES -### EXAMPLES -The following command sets a custom default value for the SmtpServer parameter of the Send-MailMessage cmdlet. +The following command sets a custom default value for the SmtpServer parameter +of the Send-MailMessage cmdlet. - -``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"} +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" +} ``` +To set default values for multiple parameters, use a semi-colon (;) to +separate each Name\=Value pair. The following command adds a custom default +value for the LogName parameter of the `Get-WinEvent` cmdlet. -To set default values for multiple parameters, use a semi-colon (;) to separate each Name\=Value pair. The following command adds a custom default value for the LogName parameter of the Get-WinEvent cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5"; + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" +} ``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"} -``` - -You can use wildcard characters in the name of the cmdlet and parameter. The following command sets the Verbose common parameter to $true in all commands. Use $true and $false to set values for switch parameters, such as Verbose. +You can use wildcard characters in the name of the cmdlet and parameter. The +following command sets the Verbose common parameter to \$true in all commands. +Use \$true and \$false to set values for switch parameters, such as +**Verbose**. - -``` +```powershell $PSDefaultParameterValues = @{"*:Verbose"=$true} ``` +If a parameter takes multiple values (an array), you can set multiple values +as the default value. The following command sets the default value of the +**ComputerName** parameter of the Invoke-Command cmdlet to "Server01" and +"Server02". -If a parameter takes multiple values (an array), you can set multiple values as the default value. The following command sets the default value of the ComputerName parameter of the Invoke-Command cmdlet to "Server01" and "Server02". - - -``` -$PSDefaultParameterValues = @{"Invoke-Command:ComputerName"="Server01","Server02"} -``` - - -You can use a script block to specify different default values for a parameter under different conditions. Windows PowerShell evaluates the script block and uses the result as the default parameter value. - -The following command sets the default value of the Autosize parameter of the Format-Table cmdlet to $true when the host program is the Windows PowerShell console. - - -``` -$PSDefaultParameterValues=@{"Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}}} -``` - - -If a parameter takes a script block value, enclose the script block in an extra set of braces. When Windows PowerShell evaluates the outer script block, the result is the inner script block, which is set as the default parameter value. - -The following command sets the default value of the ScriptBlock parameter of Invoke-Command. Because the script block is enclosed in a second set of braces, the enclosed script block is passed to the Invoke-Command cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Invoke-Command:ComputerName"="Server01","Server02" +} ``` -$PSDefaultParameterValues=@{"Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}}} -``` - - - -### HOW TO SET $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. - -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues +You can use a script block to specify different default values for a parameter +under different conditions. PowerShell evaluates the script block and uses the +result as the default parameter value. -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. +The following command sets the default value of the Autosize parameter of the +Format-Table cmdlet to \$true when the host program is the PowerShell console. - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +$PSDefaultParameterValues=@{ + "Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}} +} ``` +If a parameter takes a script block value, enclose the script block in an +extra set of braces. When PowerShell evaluates the outer script block, the +result is the inner script block, which is set as the default parameter value. +The following command sets the default value of the ScriptBlock parameter of +`Invoke-Command`. Because the script block is enclosed in a second set of +braces, the enclosed script block is passed to the `Invoke-Command` cmdlet. -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational -Get*:Verbose True +```powershell +$PSDefaultParameterValues=@{ + "Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}} +} ``` +### HOW TO SET \$PSDefaultParameterValues -To get the value of a key, use the following command syntax: +\$PSDefaultParameterValues is a preference variable, so it exists only in the +session in which it is set. It has no default value. +To set \$PSDefaultParameterValues, type the variable name and one or more +key-value pairs at the command line. -``` -$PSDefaultParameterValues[""] -``` +If you type another \$PSDefaultParameterValues command, its value replaces the +original value. The original is not retained. +To save \$PSDefaultParameterValues for future sessions, add a +\$PSDefaultParameterValues command to your PowerShell profile. For more +information, see [about_Profiles](about_Profiles.md). -For example: +### HOW TO GET \$PSDefaultParameterValues +To get the value of \$PSDefaultParameterValues, at the command prompt, type: +```powershell +$PSDefaultParameterValues ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] -Server01AB234x5 -``` - - - -### HOW TO ADD VALUES TO $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. +For example, the first command sets the value of \$PSDefaultParameterValues. +The second command gets the value of \$PSDefaultParameterValues. -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues - -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. - - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +PS C:\> $PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" + "Get-*:Verbose"=$true +} ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To get the value of a \ key, use the following +command syntax: -To get the value of a key, use the following command syntax: - - -``` +```powershell $PSDefaultParameterValues[""] ``` - For example: - -``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] +```powershell +PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] Server01AB234x5 ``` +### HOW TO ADD VALUES TO PSDefaultParameterValues +To add or remove values from \$PSDefaultParameterValues, use the methods that +you would use for a standard hash table. -### HOW TO ADD VALUES TO $PSDefaultParameterValues -To add or remove values from $PSDefaultParameterValues, use the methods that you would use for a standard hash table. - -For example, to add a value to $PSDefaultParameterValues without affecting the existing values, use the Add method of hash tables. +For example, to add a value to \$PSDefaultParameterValues without affecting the +existing values, use the Add method of hash tables. The syntax of the Add method is as follows: - ``` .Add(Key, Value) ``` +where the Key is ":" and the value is the parameter +value. -where the Key is ":" and the value is the parameter value. - -Use the following command format to call the Add method on $PSDefaultParameterValues. Be sure to use a comma (,) to separate the key from the value, instead of the equal sign (\=). - +Use the following command format to call the Add method on +\$PSDefaultParameterValues. Be sure to use a comma (,) to separate the key +from the value, instead of the equal sign (\=). +```powershell +$PSDefaultParameterValues.Add( + ":", "" +) ``` -$PSDefaultParameterValues.Add(":", "") -``` - -For example, the following command adds "PowerShell" as the default value of the Name parameter of the Get-Process cmdlet. +For example, the following command adds "PowerShell" as the default value of +the Name parameter of the Get-Process cmdlet. - -``` +```powershell $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO REMOVE VALUES FROM \$PSDefaultParameterValues - -### HOW TO REMOVE VALUES FROM $PSDefaultParameterValues -To remove a value from $PSDefaultParameterValues, use the Remove method of hash tables. +To remove a value from \$PSDefaultParameterValues, use the Remove method of +hash tables. The syntax of the Remove method is as follows: - -``` +```powershell .Remove(Key) ``` +Use the following command format to call the Remove method on +\$PSDefaultParameterValues. -Use the following command format to call the Remove method on $PSDefaultParameterValues. - - -``` +```powershell $PSDefaultParameterValues.Remove(":") ``` +For example, the following command removes the Name parameter of the +`Get-Process` cmdlet and its values. -For example, the following command removes the Name parameter of the Get-Process cmdlet and its values. - - -``` +```powershell $PSDefaultParameterValues.Remove("Get-Process:Name") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Remove("Get-Process:Name") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO CHANGE VALUES IN \$PSDefaultParameterValues +To change a value in $PSDefaultParameterValues, use the following command +format. -### HOW TO CHANGE VALUES IN $PSDefaultParameterValues -To change a value in $PSDefaultParameterValues, use the following command format. - - -``` +```powershell $PSDefaultParameterValues["CmdletName:ParameterName"]="" ``` - The following example shows the effect of this command. +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - +```powershell +$PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" -``` - +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO DISABLE AND RE-ENABLE \$PSDefaultParameterValues +You can temporarily disable and then re-enable \$PSDefaultParameterValues. This +is very useful if you're running scripts that might assume different default +parameter values. -### HOW TO DISABLE AND RE-ENABLE $PSDefaultParameterValues -You can temporarily disable and then re-enable $PSDefaultParameterValues. This is very useful if you're running scripts that might assume different default parameter values. - -To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of $True. +To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of +\$True. For example, - -``` +```powershell $PSDefaultParameterValues.Add("Disabled", $true) ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$true ``` +The other values in \$PSDefaultParameterValues are preserved, but not +effective. -The other values in $PSDefaultParameterValues are preserved, but not effective. - +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Disabled True -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Disabled True +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To re-enable \$PSDefaultParameterValues, remove the Disabled key or change the +value of the Disabled key to \$False. -To re-enable $PSDefaultParameterValues, remove the Disabled key or change the value of the Disabled key to $False. - - -``` +```powershell $PSDefaultParameterValues.Remove("Disabled") ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$false ``` - -The previous value of $PSDefaultParameterValues is effective again. - +The previous value of \$PSDefaultParameterValues is effective again. ## KEYWORDS + about_PSDefaultParameterValues about_Parameters_DefaultValues about_DefaultValues - ## SEE ALSO [about_Hash_Tables](about_Hash_Tables.md) @@ -459,4 +419,3 @@ about_DefaultValues [about_Profiles](about_Profiles.md) [about_Script_Blocks](about_Script_Blocks.md) - diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Prompts.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Prompts.md index 52e5fba3fc21..6f1820bea646 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Prompts.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Prompts.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,308 +7,284 @@ title: about_Prompts --- # About Prompts -## about_Prompts - ## SHORT DESCRIPTION -Describes the Prompt function and demonstrates how to create a custom Prompt function. +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: +The PowerShell command prompt indicates that PowerShell is ready to run a +command: ``` PS C:\> ``` +The PowerShell prompt is determined by the built-in Prompt function. You can +customize the prompt by creating your own Prompt function and saving it in +your PowerShell profile. -The Windows PowerShell prompt is determined by the built-in Prompt function. You can customize the prompt by creating your own Prompt function and saving it in your Windows PowerShell profile. - +## ABOUT THE PROMPT FUNCTION -### ABOUT 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 determines the appearance of the PowerShell prompt. +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: - -``` +```powershell function Prompt { } ``` +The Prompt function must return an object. As a best practice, return a string +or an object that is formatted as a string. The maximum recommended length is +80 characters. -The Prompt function must return an object. As a best practice, return a string or an object that is formatted as a string. The maximum recommended length is 80 characters. - -For example, the following prompt function returns a "Hello, World" string followed by a caret (>). +For example, the following prompt function returns a "Hello, World" string +followed by a caret (>). - -``` -PS C:\> function prompt {"Hello, World > "} +```powershell +PS C:\> function prompt {"Hello, World > "} Hello, World > ``` - - ### GETTING THE PROMPT FUNCTION -To get the Prompt function, use the Get-Command cmdlet or use the Get-Item cmdlet in the Function drive. -Functions are commands. So, you can use the Get-Command cmdlet to get functions, including the Prompt function. +To get the Prompt function, use the `Get-Command` cmdlet or use the `Get-Item` +cmdlet in the Function drive. For example: +```powershell +PS C:\> Get-Command Prompt -``` -PS C:\> Get-Command Prompt - -CommandType Name ModuleName ------------ ---- ---------- +CommandType Name ModuleName +----------- ---- ---------- Function prompt ``` - -To get the script that sets the value of the prompt, use the dot method to get the ScriptBlock property of the Prompt function. +To get the script that sets the value of the prompt, use the dot method to get +the ScriptBlock property of the Prompt function. For example: +```powershell +PS C:\> (Get-Command Prompt).ScriptBlock -``` -PS C:\> (Get-Command Prompt).ScriptBlock - -"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -# .Link -# http://go.microsoft.com/fwlink/?LinkID=225750 +"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPr +omptLevel + 1)) " +# .Link +# http://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml ``` +Like all functions, the Prompt function is stored in the Function: drive. To +display the script that creates the current Prompt function, type: -Like all functions, the Prompt function is stored in the Function: drive. To display the script that creates the current Prompt function, type: - - -``` +```powershell (Get-Item function:prompt).ScriptBlock ``` - ### THE DEFAULT PROMPT -The default prompt appears only when the Prompt function generates an error or does not return an object. -The default Windows PowerShell prompt is: +The default prompt appears only when the Prompt function generates an error or +does not return an object. +The default PowerShell prompt is: ``` PS> ``` +For example, the following command sets the Prompt function to $null, which is +invalid. As a result, the default prompt appears. -For example, the following command sets the Prompt function to $null, which is invalid. As a result, the default prompt appears. - - -``` -PS C:\> function prompt {$null} +```powershell +PS C:\> function prompt {$null} PS> ``` - -Because Windows PowerShell comes with a built-in prompt, you usually do not see the default prompt. - +Because PowerShell comes with a built-in prompt, you usually do not see the +default prompt. ### BUILT-IN PROMPT -Windows PowerShell includes a built-in prompt function. - -In Windows PowerShell 3.0, the built-in prompt function is: - - -``` -function prompt -{ - "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -} -``` - -This simplified prompt starts with "PS" followed by the current location, and one ">" for each nested prompt level. +PowerShell includes a built-in prompt function. -In Windows PowerShell 2.0, the built-in prompt function is: - - -``` -function prompt -{ - $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } - else { '' }) + 'PS ' + $(Get-Location) ` - + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' +```powershell +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: -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: - - -``` +```Output [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 (>). -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: -``` -For example: - PS C:\ps-test> +```Output +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.) -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: -For example, when you are debugging in a nested prompt, the prompt resembles the following prompt: - - -``` +```Output [DBG] PS C:\ps-test>>> ``` - - ### CHANGES TO THE PROMPT -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: +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 +```Output +PS Hello, World> Enter-PSSession Server01 [Server01]: PS Hello, World> ``` +Other PowerShell host applications and alternate shells might have their own +custom command prompts. -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. - +For more information about the \$PSDebugContext and $NestedPromptLevel +automatic variables, see [about_Automatic_Variables](about_Automatic_Variables.md). ### HOW TO CUSTOMIZE 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: +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: -``` +```powershell function prompt { } ``` - -Then, between the braces, enter the commands or the string that creates your prompt. +Then, between the braces, enter the commands or the string that creates your +prompt. For example, the following prompt includes your computer name: - -``` +```powershell function prompt {"PS [$env:COMPUTERNAME]> "} ``` - On the Server01 computer, the prompt resembles the following prompt: - -``` +```Output PS [Server01] > ``` - The following prompt function includes the current date and time: - -``` +```powershell function prompt {"$(get-date)> "} ``` - The prompt resembles the following prompt: - -``` +```Output 03/15/2012 17:49:47> ``` - You can also change the default Prompt function: -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) { '>>' }) + '> ' +For example, the following modified Prompt function adds "[ADMIN]:" to the +built-in PowerShell prompt when PowerShell is opened by using the "Run as +administrator" option: + +```powershell +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 PowerShell by using the "Run as administrator" option, a prompt +that resembles the following prompt appears: -When you start Windows PowerShell by using the "Run as administrator" option, a prompt that resembles the following prompt appears: - - -``` +```Output [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. -The following Prompt function displays the history ID of the next command. To view the command history, use the Get-History cmdlet. - +```powershell +function prompt { + # The at sign creates an array in case only one history item exists. + $history = @(get-history) + if($history.Count -gt 0) + { + $lastItem = $history[$history.Count - 1] + $lastId = $lastItem.Id + } -``` -function prompt -{ - # The at sign creates an array in case only one history item exists. - $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 >" + $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, PowerShell uses the default prompt, "PS>". -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 -ForegroundColor $Color - return " " +```powershell +function prompt { + $color = Get-Random -Min 1 -Max 16 + Write-Host ("PS " + $(Get-Location) +">") -NoNewLine ` + -ForegroundColor $Color + return " " } ``` - - ### SAVING THE PROMPT FUNCTION -Like any function, the Prompt function exists 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. +Like any function, the Prompt function exists only in the current session. To +save the Prompt function for future sessions, add it to your PowerShell +profiles. For more information about profiles, see about_Profiles. ## SEE ALSO -Get-Location +[Get-Location](../../Microsoft.PowerShell.Management/Get-Location.md) -Enter-PSSession +[Enter-PSSession](../Enter-PSSession.md) -Get-History +[Get-History](../Get-History.md) -Get-Random +[Get-Random](../../Microsoft.PowerShell.Utility/Get-Random.md) -Write-Host +[Write-Host](../../Microsoft.PowerShell.Utility/Write-Host.md) [about_Profiles](about_Profiles.md) diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md deleted file mode 100644 index af9999f5f30a..000000000000 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -ms.date: 2017-06-09 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_packagemanagement ---- - -# About PackageManagement -## about_PackageManagement -# TOPIC - -about_PackageManagement - -# SHORT DESCRIPTION - -PackageManagement is an aggregator for software package managers. - -# LONG DESCRIPTION - -PackageManagement functionality was introduced in Windows PowerShell 5.0. - -PackageManagement is a unified interface for software package management systems; you -can run PackageManagement cmdlets to perform software discovery, installation, and -inventory (SDII) tasks. Regardless of the underlying installation technology, -you can run the common cmdlets in the PackageManagement module to search for, -install, or uninstall packages; add, remove, and query package repositories; and -run queries on a computer to determine which software packages are installed. - -PackageManagement supports a flexible plug-in model that enables support for other -software package management systems. - -The PackageManagement module is included with Windows PowerShell 5.0 and later releases -of Windows PowerShell, and works on three levels of package management -structure: package providers, package sources, and the packages themselves. - -Term Description ----------- ------------------------------ -Package manager Software package management system. In -PackageManagement terms, this is a package provider. -Package provider PackageManagement term for a package manager. Examples -can include Windows Installer, Chocolatey, -and others. -Package source A URL, local folder, or network shared folder that -you configure package providers to use as a -repository. -Package A piece of software that a package provider manages, -and that is stored in a specific package source. - -The PackageManagement module includes the following cmdlets. You can find the -Help for these cmdlets on TechNet starting on the following page: -http://technet.microsoft.com/library/dn890951(v=wps.640).aspx. - -Cmdlet Description ----------- ------------------------------ -Get-PackageProvider Returns a list of package providers that are -connected to PackageManagement. -Get-PackageSource Gets a list of package sources that are -registered for a package provider. -Register-PackageSource Adds a package source for a specified -package provider. -Set-PackageSource Sets properties on an existing package -source. -Unregister-PackageSource Removes a registered package source. -Get-Package Returns a list of installed software -packages. -Find-Package Finds software packages in available -package sources. -Install-Package Installs one or more software packages. -Save-Package Saves packages to the local computer -without installing them. -Uninstall-Package Uninstalls one or more software packages. - -PackageManagement Package Provider Bootstrapping and Dynamic Cmdlet Parameters - -By default, PackageManagement ships with a core bootstrap provider. You can install -additional package providers as you need them by bootstrapping the providers; -that is, responding to a prompt to install the provider automatically, from a -web service. You can specify a package provider with any PackageManagement cmdlet; -if the specified provider is not available, PackageManagement prompts you to bootstrap ---or automatically install--the provider. In the following examples, if the -Chocolatey provider is not already installed, PackageManagement bootstrapping installs -the provider. - -Find-Package -Provider Chocolatey - -If the Chocolatey provider is not already installed, when you run the -preceding command, you are prompted to install it. - -Install-Package -ForceBootstrap - -If the Chocolatey provider is not already installed, when you run the -preceding command, the provider is installed; but because the ForceBootstrap -parameter has been added to the command, you are not prompted to install it; -both the provider and the package are installed automatically. - -When you try to install a package, if you do not already have the supporting -provider installed, and you do not add the ForceBootstrap parameter to your -command, PackageManagement prompts you to install the provider. - -Specifying a package provider in your PackageManagement command can make -dynamic parameters available that are specific to that package provider. -When you run Get-Help for a specific PackageManagement cmdlet, a list of -parameter sets are returned, grouping dynamic parameters for available -package providers in separate parameter sets. - -More Information About the PackageManagement Project - -For more information about the PackageManagement open development project, -including how to create a PackageManagement package provider, see the -PackageManagement project on GitHub at https://oneget.org. - -# SEE ALSO - -Get-PackageProvider - -Get-PackageSource - -Register-PackageSource - -Set-PackageSource - -Unregister-PackageSource - -Get-Package - -Find-Package - -Install-Package - -Save-Package - -Uninstall-Package - diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_pipelines.md index ec7b65c085af..97cd9535c505 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,41 +7,39 @@ title: about_pipelines --- # About Pipelines -## about_Pipelines - - ### Short Description -Combining commands into pipelines in the Windows PowerShell +Combining commands into pipelines in the 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. +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 powerful -command chain or "pipeline" that is comprised of a series of simple commands. +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 powerful command +chain or "pipeline" that is comprised of a series of simple commands. For example, + ```powershell 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` processes -the objects and send them down the pipeline. Because there are no more commands in -the pipeline, the results are displayed at the console. +`Command-2` processes the objects and sends them to `Command-3`. `Command-3` +processes the objects and send them down the pipeline. Because there are no +more commands 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. +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. +Here is a simple example. The following command gets the Notepad process and +then stops it. For example, ```powershell @@ -49,77 +47,69 @@ 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 object -to the `Stop-Process` cmdlet, which stops the Notepad process. Notice that the -`Stop-Process` command does not have a Name or ID parameter to specify the process, -because the specified process is submitted through the pipeline. +the Notepad process. It uses a pipeline operator (`|`) to send the process +object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice +that the `Stop-Process` command does not have a Name or ID parameter to +specify the process, because the specified process is submitted through the +pipeline. Here is a practical example. This command pipeline gets the text files in the -current directory, selects only the files that are more than 10,000 bytes long, -sorts them by length, and displays the name and length of each file in a table. +current directory, selects only the files that are more than 10,000 bytes +long, sorts them by length, and displays the name and length of each file in a +table. ```powershell 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 command -is written horizontally, but we will show the process vertically in the following -graphic. +This pipeline is comprised of four commands in the specified order. The +command is written horizontally, but we will show the process vertically in +the following graphic. `Get-ChildItem` `-Path` *.txt - **|** - -| (FileInfo objects ) -| ( .txt ) - - **|** - - **V** +``` +| +| (FileInfo objects for *.txt) +| +V +``` `Where-Object` {$_.length `-gt` 10000} - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| +V +``` `Sort-Object` `-Property` Length - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) -| ( Sorted by length ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.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** - ``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| ( Sorted by length ) +| ( Formatted in a table ) +| +V +``` + +```output Name Length ---- ------ tmp1.txt 82920 @@ -129,13 +119,13 @@ tmp3.txt 114000 ### Using Pipelines +The PowerShell cmdlets were designed to be used in pipelines. For example, 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. -The Windows PowerShell cmdlets were designed to be used in pipelines. For example, -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 `Start-Service` -or `Stop-Service` cmdlets (although disabled services cannot be restarted in this way). +For example, you can pipe any service from the `Get-Service` cmdlet to the +`Start-Service` or `Stop-Service` cmdlets (although disabled services cannot +be restarted in this way). This command pipeline starts the WMI service on the computer: @@ -144,90 +134,98 @@ For example, Get-Service wmi | Start-Service ``` -The cmdlets that get and set objects of the Windows PowerShell providers, such as the +The cmdlets that get and set objects of the PowerShell providers, such 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` command in the -Windows PowerShell registry provider to the `New-ItemProperty` cmdlet. This command adds -a new registry entry, NoOfEmployees, with a value of 8124, to the MyCompany registry key. +For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` +command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. +This command adds a new registry entry, NoOfEmployees, with a value of 8124, +to the MyCompany registry key. For example, ```powershell -Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 +Get-Item -Path HKLM:\Software\MyCompany | + New-ItemProperty -Name NoOfEmployees -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 any objects to -these cmdlets. +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 any 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. +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. For example, + ```powershell Get-Process | Sort-Object -Property handles ``` -Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and -`Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out -cmdlets, such as `Out-Printer`. +Also, you can pipe any objects to the formatting cmdlets, such as +`Format-List` 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. +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. For example, + ```powershell Get-Process winlogon | Format-List -Property * ``` -With a bit of practice, you'll find that combining simple commands into pipelines -saves time and typing, and makes your scripting more efficient. +With a bit of practice, you'll find that combining simple commands into +pipelines 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 command +to another command, PowerShell tries to associate the piped objects with one +of the parameters of the receiving cmdlet. -When you "pipe" objects, that is send the objects in the output of one command 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 associates input objects -with cmdlet parameters, tries to find a parameter that meets the following criteria: +To do so, the PowerShell "parameter binding" component, which associates 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 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 `-InputObject` 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`. +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 `-InputObject` 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 PowerShell prompts you -for the missing parameter values. +If the parameter binding component of PowerShell cannot associate the piped +objects with a parameter of the receiving cmdlet, the command fails and +PowerShell prompts you for the missing parameter values. -You cannot force the parameter binding component to associate the piped objects with a particular -parameter -- you cannot even suggest a parameter. Instead, the logic of the component manages -the piping as efficiently as possible. +You cannot force the parameter binding component to associate the piped +objects with a particular parameter. You cannot even suggest a parameter. +Instead, the logic of the 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. -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: +For example, piping objects representing the services on the computer to a +`Format-Table` command, such as: ```powershell Get-Service | Format-Table -Property name, dependentservices ``` -is much like saving the service objects in a variable and using the InputObject parameter -of `Format-Table` to submit the service object. +is much like saving the service objects in a variable and using the +InputObject parameter of `Format-Table` to submit the service object. For example, + ```powershell $services = Get-Service Format-Table -InputObject $services -Property name, dependentservices @@ -236,51 +234,58 @@ Format-Table -InputObject $services -Property name, dependentservices or imbedding the command in the parameter value For example, + ```powershell -Format-Table -InputObject (Get-Service wmi) -Property name, dependentservices +Format-Table -InputObject (Get-Service wmi) -Property name,dependentservices ``` -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 you use a -command parameter, the objects are sent as a single array object. +However, there is an important difference. When you pipe multiple objects to a +command, PowerShell sends the objects to the command one at a time. When you +use a command parameter, the objects are sent as a single array object. + +This seemingly technical difference can have interesting, and sometimes +useful, consequences. -This seemingly technical difference can have interesting, and sometimes useful, consequences. +For example, if you pipe multiple process objects from the `Get-Process` +cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one +at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the +process objects, and their properties and methods. -For example, if you pipe multiple process objects from the `Get-Process` cmdlet 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 their properties and methods. -(`Get-Member` eliminates duplicates, so if the objects are all of the same type, it displays only -one object type.) +NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the +same type, it displays only one object type. -In this case, `Get-Member` displays the properties and methods of each process object, that is, a -System.Diagnostics.Process object. +In this case, `Get-Member` displays the properties and methods of each process +object, that is, a System.Diagnostics.Process object. For example, + ```powershell Get-Process | Get-Member ``` -``` +```Output TypeName: System.Diagnostics.Process -Name MemberType Definition ----- ---------- ---------- -Handles AliasProperty Handles = Handlecount -Name AliasProperty Name = ProcessName -NPM AliasProperty NPM = NonpagedSystemMemorySize +Name MemberType Definition +---- ---------- ---------- +Handles AliasProperty Handles = Handlecount +Name AliasProperty Name = ProcessName +NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then `Get-Member` receives an -array of System.Diagnostics.Process objects as a single unit, and it displays the properties -of an array of objects. (Note the array symbol ([]) after the System.Object type name.) +However, if you use the InputObject parameter of `Get-Member`, then +`Get-Member` receives an array of System.Diagnostics.Process objects as a +single unit, and it displays the properties of an array of objects. (Note the +array symbol ([]) after the System.Object type name.) For example, + ```powershell Get-Member -InputObject (Get-Process) ``` -``` +```Output TypeName: System.Object[] Name MemberType Definition @@ -291,30 +296,32 @@ Clone Method System.Object Clone() ... ``` -This result might not be what you intended, but after you understand it, you 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. +This result might not be what you intended, but after you understand it, you +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. For example, + ```powershell (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. +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** or **Parameter** -parameters to determine which, if any, of a cmdlet's parameters 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** or **Parameter** parameters to determine which, if any, of a +cmdlet's parameters accepts pipeline input. -In the `Get-Help` default display, the "Accept 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. +In the `Get-Help` default display, the "Accept 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` cmdlet accepts -pipeline input, type: +For example, to determine which of the parameters of the `Start-Service` +cmdlet accepts pipeline input, type: ```powershell Get-Help Start-Service -Full @@ -326,108 +333,115 @@ or Get-Help Start-Service -Parameter * ``` -For example, the help for the `Start-Service` cmdlet shows that the **InputObject** and **Name** -parameters accept pipeline input ("true"). All other parameters have a value of "false" -in the "Accept pipeline input?" row. +For example, the help for the `Start-Service` cmdlet shows that the +**InputObject** and **Name** parameters accept pipeline input ("true"). All +other parameters have a value of "false" in the "Accept pipeline input?" row. ``` -InputObject - 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. +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? true - Position? 0 - Default value None - Accept pipeline input? True (ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByValue) +Accept wildcard characters? false -Name - Specifies the service names for the service to be started. +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. +The parameter name is optional. You can use Name or its alias, ServiceName, +or you can omit the parameter name. - Required? true - Position? 0 - Default value None - Accept pipeline input? True (ByPropertyName, ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByPropertyName, ByValue) +Accept wildcard characters? false ``` This means that you can send objects (PsObjects) through the pipeline to the -`Where-Object` cmdlet and Windows PowerShell will associate the object with the +`Where-Object` cmdlet and PowerShell will associate the object with the **InputObject** and **Name** parameters. ### 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 objects -that have the same .NET type as their parameter value or objects that can 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. + that have the same .NET type as their parameter value or objects that can be + converted to that type. -- ByPropertyName: Parameters that accept input "by property name" can accept piped -objects only when a property of the object has the same name as the parameter. + 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. -For example, the Name parameter of `Start-Service` can accept objects that have -a Name property. +- ByPropertyName: Parameters that accept input "by property name" can accept + piped objects only when a property of the object has the same name as the + parameter. -(To list the properties of an object, pipe it to `Get-Member`.) + For example, the Name parameter of `Start-Service` can accept objects that + 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 parameters are -designed to take input from the pipeline easily. +Some parameters can accept objects by value or by property name. These +parameters 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 failure and -rewrite the command. +If a command fails because of a pipeline error, you can investigate the +failure 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 destination path and -then piping the path to the `Move-ItemProperty` cmdlet. +registry key to another by using the `Get-Item` cmdlet to get the destination +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. The `Move-ItemProperty` -command specifies the current path and name of the registry entry to be moved. +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. The `Move-ItemProperty` command specifies the +current path and name of the registry entry to be moved. For example, + ```powershell 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 +The command fails and 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 pipeline input. +```output +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 +pipeline input. At line:1 char:23 -+ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name product ++ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name p ``` -To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of -Windows PowerShell. The following command traces the Parameter Binding component 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 reference. +To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding +component of PowerShell. The following command traces the Parameter Binding +component 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 reference. For example, + ```powershell -Trace-Command -Name parameterbinding -Expression {Get-Item -Path HKLM:\software\mycompany\sales | -Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} -PSHost -FilePath debug.txt +Trace-Command -Name parameterbinding -Expression { + Get-Item -Path HKLM:\software\mycompany\sales | + Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} ` + -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. +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`] @@ -442,31 +456,35 @@ 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 parameter -of `Move-ItemProperty` failed. +Finally, it shows that the attempt to bind the path to the **Destination** +parameter 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 ValueFromPipelineByPropertyName NO COERCION -Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION +Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyName NO CO +ERCION +Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COE +RCION ... +``` - -To investigate the failure, use the `Get-Help` cmdlet to view the attributes of the -**Destination** parameter. The following command gets detailed information about the -**Destination** parameter. +To investigate the failure, use the `Get-Help` cmdlet to view the attributes +of the **Destination** parameter. The following command gets detailed +information about the **Destination** parameter. ```powershell Get-Help Move-ItemProperty -Parameter Destination ``` -The results show that **Destination** takes pipeline input only "by property name". -That is, the piped object must have a property named Destination. +The results show that **Destination** takes pipeline input only "by property +name". That is, the piped object must have a property named Destination. ``` -Destination @@ -479,11 +497,12 @@ That is, the piped object must have a property named Destination. Accept wildcard characters? false ``` -To see the properties of the object being piped to the `Move-ItemProperty` cmdlet, -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. +To see the properties of the object being piped to the `Move-ItemProperty` +cmdlet, 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. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` @@ -491,11 +510,13 @@ 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-ItemProperty` cmdlet. We can -use a `Get-ItemProperty` command to get the path, but the name and destination must be specified -in the `Move-ItemProperty` part of the command. +To fix the command, we must specify the destination in the `Move-ItemProperty` +cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name +and destination must be specified in the `Move-ItemProperty` part of the +command. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\design | Move-ItemProperty -Dest HKLM:\software\mycompany\design -Name product @@ -510,9 +531,11 @@ Get-Itemproperty HKLM:\software\mycompany\sales The results show that the Product registry entry was moved to the Sales key. -``` -PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany\sales -PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany +```Output +PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany\sales +PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany PSChildName : sales PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_profiles.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_profiles.md index b7eabd81d0ce..eea0dd9f0d50 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_profiles.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_profiles.md @@ -1,104 +1,99 @@ --- -ms.date: 2017-06-25 +ms.date: 2017-11-30 schema: 2.0.0 keywords: powershell,cmdlet title: about_Profiles --- # About Profiles -## about_Profiles +## SHORT DESCRIPTION -# SHORT DESCRIPTION +Describes how to create and use a PowerShell profile. -Describes how to create and use a Windows PowerShell profile. +## LONG DESCRIPTION -# LONG DESCRIPTION +You can create a PowerShell profile to customize your environment and to add +session-specific elements to every PowerShell session that you start. -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 PowerShell profile is a script that runs when 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 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. -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. +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. -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 PowerShell console +(PowerShell.exe) to start PowerShell without any profiles. And, it explains +the effect of the PowerShell execution policy on profiles. -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 -# THE PROFILE FILES +PowerShell supports several profile files. Also, PowerShell host programs can +support their own host-specific profiles. - -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 +For example, the 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\Profile.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 | +|Description | Path | +|--------------------------|------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Profile.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 +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\Microsoft.PowerShellISE_profile.ps1 | -| All users, Current Host | $PsHome\Microsoft.PowerShellISE_profile.ps1 | +In addition, other programs that host PowerShell can support their own +profiles. For example, PowerShell Integrated Scripting Environment (ISE) +supports the following host-specific profiles. -In Windows PowerShell Help, the "CurrentUser, Current Host" profile is the profile most -often referred to as "your Windows PowerShell profile". +|Description | Path | +|--------------------------|-------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Microsoft.PowerShellISE_profile.ps1 | +|All users, Current Host |$PsHome\Microsoft.PowerShellISE_profile.ps1| -# THE $PROFILE VARIABLE +In PowerShell Help, the "CurrentUser, Current Host" profile is the profile +most often referred to as "your PowerShell profile". +## THE $PROFILE VARIABLE -The `$Profile` automatic variable stores the paths to the Windows PowerShell -profiles that are available in the current session. +The `$Profile` automatic variable stores the paths to the 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. +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 | +|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. +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 PowerShell host application that you use. To see the current values of the `$Profile` variable, type: @@ -107,24 +102,22 @@ $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: +following command opens the "Current User, Current Host" profile in Notepad: ```powershell notepad $profile ``` -The following command determines whether an "All Users, All Hosts" profile -has been created on the local computer: +The following command determines whether an "All Users, All Hosts" profile has +been created on the local computer: ```powershell Test-Path -Path $profile.AllUsersAllHosts ``` -# HOW TO CREATE A PROFILE +## HOW TO CREATE A PROFILE - -To create a Windows PowerShell profile, use the following command format: +To create a PowerShell profile, use the following command format: ```powershell if (!(Test-Path -Path )) @@ -132,7 +125,7 @@ if (!(Test-Path -Path )) ``` For example, to create a profile for the current user in the current -Windows PowerShell host application, use the following command: +PowerShell host application, use the following command: ```powershell if (!(Test-Path -Path $profile)) @@ -140,21 +133,18 @@ if (!(Test-Path -Path $profile)) ``` In this command, the If statement prevents you from overwriting an existing -profile. Replace the value of the placeholder with the path +profile. Replace the value of the \ 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 +> Note: To create "All Users" profiles in Windows Vista and later versions of +> Windows, start 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. +You can open any 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: +To open the profile of the current user in the current PowerShell host +application in Notepad, type: ```powershell notepad $profile @@ -167,106 +157,99 @@ 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. +To apply the changes, save the profile file, and then restart PowerShell. -# HOW TO CHOOSE A PROFILE +## 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 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: +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 - + `$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 +implementation of 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. +Many of the items that you create in 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](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), -and Windows PowerShell snap-ins that you add to the session. +variables, aliases, functions, commands (except for +[Set-ExecutionPolicy](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), +and PowerShell modules 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. +To save these items and make them available in all future sessions, add them +to a 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. +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 +## 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. +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: +### 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: ```powershell function Pro {notepad $profile.CurrentUserAllHosts} ``` -- Add a function that opens Windows PowerShell Help in a compiled HTML -Help file (.chm) +### Add a function that opens PowerShell Help in a compiled HTML + Help file (.chm) ```powershell -function Get-CHM -{ -Invoke-Item -Path "$env:windir\help\mui\0409\WindowsPowerShellHelp.chm" +function Get-CHM { + Invoke-Item -Path "$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. +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 +### Add a function that lists the aliases for any cmdlet ```powershell -function Get-CmdletAlias ($cmdletname) -{ -Get-Alias | Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | Format-Table -Property Definition, Name -AutoSize +function Get-CmdletAlias ($cmdletname) { + Get-Alias | + Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | + Format-Table -Property Definition, Name -AutoSize } ``` -- Customize your console +### Customize your console ```powershell -function Color-Console -{ -$Host.ui.rawui.backgroundcolor = "white" -$Host.ui.rawui.foregroundcolor = "black" -$hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime -$hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" -$Host.UI.RawUI.WindowTitle = "Windows PowerShell $hostversion ($hosttime)" -Clear-Host +function Color-Console { + $Host.ui.rawui.backgroundcolor = "white" + $Host.ui.rawui.foregroundcolor = "black" + $hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime + $hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" + $Host.UI.RawUI.WindowTitle = "PowerShell $hostversion ($hosttime)" + Clear-Host } Color-Console ``` -- Add a customized Windows PowerShell prompt that includes the computer -name and the current path +### Add a customized PowerShell prompt ```powershell function Prompt @@ -275,18 +258,16 @@ $env:COMPUTERNAME + "\" + (Get-Location) + "> " } ``` -For more information about the Windows PowerShell prompt, see +For more information about the PowerShell prompt, see [about_Prompts](about_Prompts.md). -# THE NOPROFILE PARAMETER +## THE NOPROFILE PARAMETER +To start PowerShell without profiles, use the **NoProfile** parameter of +PowerShell.exe, the program that starts PowerShell. -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. +To begin, open a program that can start PowerShell, such as Cmd.exe or +PowerShell itself. You can also use the Run dialog box in Windows. Type: @@ -294,56 +275,58 @@ Type: PowerShell -NoProfile ``` -For a complete list of the parameters of PowerShell.exe, -type: +For a complete list of the parameters of PowerShell.exe, type: ``` PowerShell -? ``` -# PROFILES AND EXECUTION POLICY - +## 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. +The 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. +one of the few commands that applies in all 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 +## PROFILES AND REMOTE SESSIONS +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 +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 sessions. +To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) +cmdlet. -To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) cmdlet. - -For example, the following command runs the "Current user, Current Host" profile from -the local computer in the session in $s. +For example, the following command runs the "Current user, Current Host" +profile from the local computer in the session in $s. ```powershell Invoke-Command -Session $s -FilePath $profile ``` -The following command runs the "Current user, Current Host" 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. +The following command runs the "Current user, Current Host" 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. ```powershell -Invoke-Command -SessionName $s -ScriptBlock {Invoke-Command -FilePath "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"} +Invoke-Command -SessionName $s -ScriptBlock { +$path = "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1" +Invoke-Command -FilePath $path +} ``` After running this command, the commands that the profile adds to the session are available in $s. -# SEE ALSO +## SEE ALSO [about_Automatic_Variables](about_Automatic_Variables.md) diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md index 7a62b5bef11e..0f745ac3aa94 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,232 +7,246 @@ title: about_Object_Creation --- # About Object Creation -## about_Object_Creation - ## SHORT DESCRIPTION -Explains how to create objects in Windows PowerShell®. +Explains how to create objects in PowerShell. ## LONG DESCRIPTION -You can create objects in Windows PowerShell and use the objects that you create in commands and scripts. - -There are several ways to create objects: - -New-Object: -The New-Object cmdlet creates an instance of a .NET Framework object or COM object. +You can create objects in PowerShell and use the objects that you create in +commands and scripts. -Hash tables: +There are several ways to create objects: -Beginning in Windows PowerShell 3.0, you can create objects from hash tables of property names and property values. +- `New-Object`: This cmdlet creates an instance of a .NET Framework object or + COM object. -Import-Csv: +- Hash tables: Beginning in PowerShell 3.0, you can create objects + from hash tables of property names and property values. -The Import-Csv cmdlet creates custom objects (PSCustomObject) from the items in a CSV file. Each row is an object instance and each column is an object property. +- `Import-Csv`: This cmdlet creates custom objects (PSCustomObject) from the + items in a CSV file. Each row is an object instance and each column is an + object property. This topic will demonstrate and discuss each of these methods. - ## NEW-OBJECT -The New-Object cmdlet provides a robust and consistent way to create new objects. The cmdlet works with almost all types and in all supported versions of Windows PowerShell. -To create a new object, specify either the type of a .NET Framework class or a ProgID of a COM object. +The `New-Object` cmdlet provides a robust and consistent way to create new +objects. The cmdlet works with almost all types and in all supported versions +of PowerShell. -For example, the following command creates a Version object. +To create a new object, specify either the type of a .NET Framework class or a +ProgID of a COM object. +For example, the following command creates a Version object. -``` -PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 +```powershell +PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 PS C:\> $v ``` - - -``` -Major Minor Build Revision ------ ----- ----- -------- +```Output +Major Minor Build Revision +----- ----- ----- -------- 2 0 0 1 ``` +```powershell +PS C:\> $v | Get-Member - -``` -PS C:\> $v | Get-Member - TypeName: System.Version ``` - For more information, see the help topic for the New-Object cmdlet. - ### CREATE OBJECTS FROM HASH TABLES -Beginning in Windows PowerShell 3.0, you can create an object from a hash table of properties and property values. -The syntax is as follows: +Beginning in PowerShell 3.0, you can create an object from a hash table of +properties and property values. +The syntax is as follows: ``` -[]@{=;=} +[]@{ + = + = +} ``` - -This method works only for classes that have a null constructor, that is, a constructor that has no parameters. The object properties must be public and settable. - +This method works only for classes that have a null constructor, that is, a +constructor that has no parameters. The object properties must be public and +settable. ### CREATE CUSTOM OBJECTS FROM HASH TABLES -Custom objects are very useful and they are very easy to create by using the hash table method. To create a custom object, use the PSCustomObject class, a class designed specifically for this purpose. - -Custom objects are an excellent way to return customized output from a function or script; far more useful than returning formatted output that cannot be reformatted or piped to other commands. - -The commands in the Test-Object function set some variable values and then use those values to create a custom object. (You can see this object in use in the example section of the Update-Help cmdlet help topic.) - -``` -function Test-Object -{ $ModuleName = "PSScheduledJob" - $HelpCulture = "en-us" - $HelpVersion = "3.1.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} - - $ModuleName = "PSWorkflow" - $HelpCulture = "en-us" - $HelpVersion = "3.0.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} +Custom objects are very useful and they are very easy to create by using the +hash table method. To create a custom object, use the PSCustomObject class, a +class designed specifically for this purpose. + +Custom objects are an excellent way to return customized output from a +function or script; far more useful than returning formatted output that +cannot be reformatted or piped to other commands. + +The commands in the `Test-Object function` set some variable values and then +use those values to create a custom object. You can see this object in use in +the example section of the `Update-Help` cmdlet help topic. + +```powershell +function Test-Object { + $ModuleName = "PSScheduledJob" + $HelpCulture = "en-us" + $HelpVersion = "3.1.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } + $ModuleName = "PSWorkflow" + $HelpCulture = "en-us" + $HelpVersion = "3.0.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } } ``` +The output of this function is a collection of custom objects formatted as a +table by default. -The output of this function is a collection of custom objects formatted as a table by default. - +```powershell +PS C:\> Test-Object -``` -PS C:\> Test-Object - -ModuleName UICulture Version ---------- --------- ------- -PSScheduledJob en-us 3.1.0.0 +ModuleName UICulture Version +--------- --------- ------- +PSScheduledJob en-us 3.1.0.0 PSWorkflow en-us 3.0.0.0 ``` +Users can manage the properties of the custom objects just as they do with +standard objects. -Users can manage the properties of the custom objects just as they do with standard objects. - - -``` -PS C:\> (Test-Object).ModuleName - PSScheduledJob +```powershell +PS C:\> (Test-Object).ModuleName + PSScheduledJob PSWorkflow ``` - - #### CREATE NON-CUSTOM OBJECTS FROM HASH TABLES -You can also use hash tables to create objects for non-custom classes. When you create an object for a non-custom class, the full namespace name is required unless class is in the System namespace. Use only the properties of the class. -For example, the following command creates a session option object. +You can also use hash tables to create objects for non-custom classes. When +you create an object for a non-custom class, the full namespace name is +required unless class is in the System namespace. Use only the properties of +the class. +For example, the following command creates a session option object. +```powershell +[System.Management.Automation.Remoting.PSSessionOption]@{ + IdleTimeout=43200000 + SkipCnCheck=$True +} ``` -[System.Management.Automation.Remoting.PSSessionOption]@{IdleTimeout=43200000; SkipCnCheck=$True} -``` - -The requirements of the hash table feature, especially the null constructor requirement, eliminate many existing classes. However, most Windows PowerShell option classes are designed to work with this feature, as well as other very useful classes, such as the ScheduledJobTrigger class. +The requirements of the hash table feature, especially the null constructor +requirement, eliminate many existing classes. However, most PowerShell option +classes are designed to work with this feature, as well as other very useful +classes, such as the ScheduledJobTrigger class. +```powershell +[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{ + Frequency="Daily" + At="15:00" +} -``` -[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{Frequency="Daily";At="15:00"} - -Id Frequency Time DaysOfWeek Enabled --- --------- ---- ---------- ------- -0 Daily 6/6/2012 3:00:00 PM True +Id Frequency Time DaysOfWeek Enabled +-- --------- ---- ---------- ------- +0 Daily 6/6/2012 3:00:00 PM True ``` +You can also use the hash table feature when setting parameter values. For +example, the value of the **SessionOption** parameter of the New-PSSession +cmdlet and the value of the JobTrigger parameter of `Register-ScheduledJob` +can be a hash table. -You can also use the hash table feature when setting parameter values. For example, the value of the SessionOption parameter of the New-PSSession cmdlet and the value of the JobTrigger parameter of Register-ScheduledJob can be a hash table. - - -``` -New-PSSession -ComputerName Server01 -SessionOption @{IdleTimeout=43200000; SkipCnCheck=$True} -Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{Frequency="Daily";At="15:00"} +```powershell +New-PSSession -ComputerName Server01 -SessionOption @{ + IdleTimeout=43200000 + SkipCnCheck=$True +} +Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{ + Frequency="Daily" + At="15:00" +} ``` - - ### IMPORT-CSV -You can create custom objects from the items in a CSV file. When you use the Import-Csv cmdlet to import the CSV file, the cmdlet creates a custom object (PSCustomObject) for each item in the file. The column names are the object properties. -For example, if you import a CSV file of computer asset data, Import-CSV creates a collection of custom objects from the input. +You can create custom objects from the items in a CSV file. When you use the +`Import-Csv` cmdlet to import the CSV file, the cmdlet creates a custom object +(PSCustomObject) for each item in the file. The column names are the object +properties. +For example, if you import a CSV file of computer asset data, `Import-CSV` +creates a collection of custom objects from the input. ``` -#In Servers.csv -AssetID, Name, OS, Department -003, Server01, Windows Server 2012, IT -103, Server33, Windows 7, Marketing +#In Servers.csv +AssetID, Name, OS, Department +003, Server01, Windows Server 2012, IT +103, Server33, Windows 7, Marketing 212, Server35, Windows 8, Finance ``` +```powershell +PS C:\> $a = Import-Csv Servers.csv +PS C:\> $a - -``` -PS C:\> $a = Import-Csv Servers.csv -PS C:\> $a - -AssetID Name OS Department -------- ---- -- ---------- -003 Server01 Windows Server 2012 IT -103 Server33 Windows 7 Marketing +AssetID Name OS Department +------- ---- -- ---------- +003 Server01 Windows Server 2012 IT +103 Server33 Windows 7 Marketing 212 Server35 Windows 8 Finance ``` - Use the Get-Member cmdlet to confirm the object type. - -``` +```powershell PS C:\> $a | Get-Member ``` +```Output +TypeName: System.Management.Automation.PSCustomObject - -``` -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() -AssetID NoteProperty System.String AssetID=003 -Department NoteProperty System.String Department=IT -Name NoteProperty System.String Name=Server01 +Name MemberType Definition +---- ---------- ---------- +Equals Method bool Equals(System.Object obj) +GetHashCode Method int GetHashCode() +GetType Method type GetType() +ToString Method string ToString() +AssetID NoteProperty System.String AssetID=003 +Department NoteProperty System.String Department=IT +Name NoteProperty System.String Name=Server01 OS NoteProperty System.String OS=Windows Server 2012 ``` - You can use the custom objects just as you would standard objects. - -``` +```powershell PS C:\> $a | where {$_.OS -eq "Windows 8"} ``` - - -``` -AssetID Name OS Department -------- ---- -- ---------- +```output +AssetID Name OS Department +------- ---- -- ---------- 212 Server35 Windows 8 Finance ``` - For more information, see the help topic for the Import-Csv cmdlet. - ## SEE ALSO [about_Objects](about_Objects.md) @@ -243,9 +257,8 @@ For more information, see the help topic for the Import-Csv cmdlet. [about_Pipelines](about_Pipelines.md) -Get-Member - -Import-Csv +[Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) -New-Object +[Import-Csv](../../Microsoft.PowerShell.Utility/Import-Csv.md) +[New-Object](../../Microsoft.PowerShell.Utility/New-Object.md) diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Objects.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Objects.md index 88ab499af532..58308cabd6d7 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Objects.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Objects.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -58,20 +58,13 @@ directory objects are passed down the pipeline to the second command. The second command `where { $_.PsIsContainer -eq $false }` uses the PsIsContainer property of all file system objects to select only -files, which have a value of False ($false) in their PsIsContainer +files, which have a value of False (\$false) in their PsIsContainer property. Folders, which are containers and, thus, have a value of -True ($true) in their PsIsContainer property, are not selected. +True (\$true) in their PsIsContainer property, are not selected. The second command passes only the file objects to the third command `Format-List`, which displays the file objects in a list. -## For More Information - -Now that you understand a bit about objects, see the [about_Methods](about_Methods.md) -help topic to learn how to find and use object methods, the -[about_Properties](about_Properties.md) topic to learn how to find and use object properties, -and the [Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) topic, to learn how to find an object type. - ## See Also [about_Methods](about_Methods.md) diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md index 6e83191b889c..01d129ccc4bb 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -10,84 +10,85 @@ title: about_Operator_Precedence ## SHORT DESCRIPTION -Lists the Windows PowerShell operators in precedence order. +Lists the PowerShell operators in precedence order. -[This topic was contributed by Kirk Munro, a Windows PowerShell MVP +[This topic was contributed by Kirk Munro, a PowerShell MVP from Ottawa, Ontario] ## LONG DESCRIPTION -Windows PowerShell operators let you construct simple, but powerful -expressions. This topic lists the operators in precedence order. -Precedence order is the order in which Windows PowerShell evaluates -the operators when multiple operators appear in the same expression. - -When operators have equal precedence, Windows PowerShell evaluates -them from left to right. The exceptions are the assignment operators, -the cast operators, and the negation operators (!, -not, -bnot), -which are evaluated from right to left. - -You can use enclosures, such as parentheses, to override the -standard precedence order and force Windows PowerShell to evaluate -the enclosed part of an expression before an unenclosed part. - -In the following list, operators are listed in the order that they -are evaluated. Operators on the same line, or in the same group, have -equal precedence. - -The Operator column lists the operators. The Reference column lists -the Windows PowerShell Help topic in which the operator is described. -To display the topic, type `get-help `. - -|OPERATOR|REFERENCE| -|--------|---------| -|`$() @()`|[about_Operators](#index-operator)| -|`.` (dereference) `::` (static)|[about_Operators](about_Operators.md)| -|`[0]` (index operator)|[about_Operators](about_Operators.md)| +PowerShell operators let you construct simple, but powerful +expressions. This topic lists the operators in precedence order. Precedence +order is the order in which PowerShell evaluates the operators when +multiple operators appear in the same expression. + +When operators have equal precedence, PowerShell evaluates them from +left to right. The exceptions are the assignment operators, the cast +operators, and the negation operators (!, -not, -bnot), which are evaluated +from right to left. + +You can use enclosures, such as parentheses, to override the standard +precedence order and force PowerShell to evaluate the enclosed part of +an expression before an unenclosed part. + +In the following list, operators are listed in the order that they are +evaluated. Operators on the same line, or in the same group, have equal +precedence. + +The Operator column lists the operators. The Reference column lists the +PowerShell Help topic in which the operator is described. To display +the topic, type `get-help `. + +|OPERATOR |REFERENCE| +|------------------------|---------| +|`$() @()` |[about_Operators](#index-operator)| +|`.` (dereference) |[about_Operators](about_Operators.md)| +|`::` (static) |[about_Operators](about_Operators.md)| +|`[0]` (index operator) |[about_Operators](about_Operators.md)| |`[int]` (cast operators)|[about_Operators](about_Operators.md)| -|`-split` (unary)
`-join` (unary)|[about_Split](about_Split.md)
[about_Join](about_Join.md)| -|`,` (comma operator)|[about_Operators](about_Operators.md)| -|`++ --`|[about_Assignment_Operators](about_Assignment_Operators.md)| -|`-not`
`! -bNot`|[about_Logical_Operators](about_logical_operators.md)
[about_Comparison_Operators](about_Comparison_Operators.md)| -|`..` (range operator)|[about_Operators](about_Operators.md)| -|`-f` (format operator)|[about_Operators](about_Operators.md)| -|`* / %`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`+ -`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| - - -The following group of operators have equal precedence. Their -case-sensitive and explicitly case-insensitive variants have -the same precedence. - -|OPERATOR|REFERENCE| -|--------|---------| -|`-split` (unary)|[about_Split](about_Split.md)| -|`-join` (unary)|[about_Join](about_Join.md)| -|`-is -isnot -as`|[about_Type_Operators](about_Type_Operators.md)| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`,` (comma operator) |[about_Operators](about_Operators.md)| +|`++ --` |[about_Assignment_Operators](about_Assignment_Operators.md)| +|`-not` |[about_Logical_Operators](about_logical_operators.md)| +|`! -bNot` |[about_Comparison_Operators](about_Comparison_Operators.md)| +|`..` (range operator) |[about_Operators](about_Operators.md)| +|`-f` (format operator) |[about_Operators](about_Operators.md)| +|`* / % + -` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| + +The following group of operators have equal precedence. Their case-sensitive +and explicitly case-insensitive variants have the same precedence. + +|OPERATOR |REFERENCE| +|-------------------------|---------| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`-is -isnot -as` |[about_Type_Operators](about_Type_Operators.md)| |`-eq -ne -gt -gt -lt -le`|[about_Comparison_Operators](about_Comparison_Operators.md)| -|`-like -notlike`|[about_comparison_operators](about_comparison_operators.md)| -|`-match -notmatch`|[about_comparison_operators](about_comparison_operators.md)| -|`-in -notIn`|[about_comparison_operators](about_comparison_operators.md)| -|`-contains -notContains`|[about_comparison_operators](about_comparison_operators.md)| -|`-replace`|[about_comparison_operators](about_comparison_operators.md)| +|`-like -notlike` |[about_comparison_operators](about_comparison_operators.md)| +|`-match -notmatch` |[about_comparison_operators](about_comparison_operators.md)| +|`-in -notIn` |[about_comparison_operators](about_comparison_operators.md)| +|`-contains -notContains` |[about_comparison_operators](about_comparison_operators.md)| +|`-replace` |[about_comparison_operators](about_comparison_operators.md)| The list resumes here with the following operators in precedence order: -|OPERATOR|REFERENCE| -|--------|---------| -|`-band -bor -bxor`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`-and -or -xor`|[about_comparison_operators](about_comparison_operators.md)| -|`.` (dot-source)
`&` (call)|[about_Scopes](about_Scopes.md)
[about_Operators](about_Operators.md)| +|OPERATOR |REFERENCE| +|--------------------------|---------| +|`-band -bor -bxor` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| +|`-and -or -xor` |[about_comparison_operators](about_comparison_operators.md)| +|`.` (dot-source) |[about_Scopes](about_Scopes.md)| +|`&` (call) |[about_Operators](about_Operators.md)| || (pipeline operator)|[about_Operators](about_Operators.md)| -|`> >> 2> 2>> 2>&1`|[about_Redirection](about_Redirection.md)| -|`= += -= *= /= %=`|[about_Assignment_Operators](about_Assignment_Operators.md)| +|`> >> 2> 2>> 2>&1` |[about_Redirection](about_Redirection.md)| +|`= += -= *= /= %=` |[about_Assignment_Operators](about_Assignment_Operators.md)| # EXAMPLES -The following two commands show the arithmetic operators and -the effect of using parentheses to force Windows PowerShell to -evaluate the enclosed part of the expression first. +The following two commands show the arithmetic operators and the effect of +using parentheses to force PowerShell to evaluate the enclosed part of +the expression first. ```powershell C:\PS> 2 + 3 * 4 @@ -97,8 +98,8 @@ C:\PS> (2 + 3) * 4 20 ``` -The following example gets the read-only text files from the local -directory and saves them in the `$read_only` variable. +The following example gets the read-only text files from the local directory +and saves them in the `$read_only` variable. ```powershell $read_only = get-childitem *.txt | where-object {$_.isReadOnly} @@ -109,37 +110,37 @@ It is equivalent to the following example. $read_only = ( get-childitem *.txt | where-object {$_.isReadOnly} ) ``` -Because the pipeline operator (|) has a higher precedence than the -assignment operator (=), the files that the Get-ChildItem cmdlet -gets are sent to the Where-Object cmdlet for filtering before they -are assigned to the $read_only variable. +Because the pipeline operator (|) has a higher precedence than the assignment +operator (=), the files that the Get-ChildItem cmdlet gets are sent to the +Where-Object cmdlet for filtering before they are assigned to the $read_only +variable. -The following example demonstrates that the index operator takes -precedence over the cast operator. +The following example demonstrates that the index operator takes precedence +over the cast operator. -The first expression creates an array of three strings. Then, it -uses the index operator with a value of 0 to select the first object -in the array, which is the first string. Finally, it casts the -selected object as a string. In this case, the cast has no effect. +The first expression creates an array of three strings. Then, it uses the +index operator with a value of 0 to select the first object in the array, +which is the first string. Finally, it casts the selected object as a string. +In this case, the cast has no effect. ```powershell C:\PS> [string]@('Windows','PowerShell','2.0')[0] Windows ``` -The second expression uses parentheses to force the cast operation -to occur before the index selection. As a result, the entire array -is cast as a (single) string. Then, the index operator selects -the first item in the string array, which is the first character. +The second expression uses parentheses to force the cast operation to occur +before the index selection. As a result, the entire array is cast as a +(single) string. Then, the index operator selects the first item in the string +array, which is the first character. ```powershell C:\PS> ([string]@('Windows','PowerShell','2.0'))[0] W ``` -In the following example, because the -gt (greater-than) operator -has a higher precedence than the -and (logical AND) operator, the -result of the expression is FALSE. +In the following example, because the -gt (greater-than) operator has a higher +precedence than the -and (logical AND) operator, the result of the expression +is FALSE. ```powershell C:\PS> 2 -gt 4 -and 1 @@ -160,11 +161,11 @@ C:\PS> 2 -gt (4 -and 1) True ``` -However, this example demonstrates an important principle of managing -operator precedence. When an expression is difficult for people to -interpret, use parentheses to force the evaluation order, even when it -forces the default operator precedence. The parentheses make your -intentions clear to people who are reading and maintaining your scripts. +However, this example demonstrates an important principle of managing operator +precedence. When an expression is difficult for people to interpret, use +parentheses to force the evaluation order, even when it forces the default +operator precedence. The parentheses make your intentions clear to people who +are reading and maintaining your scripts. ## SEE ALSO @@ -185,4 +186,3 @@ intentions clear to people who are reading and maintaining your scripts. [about_Split](about_Split.md) [about_Type_Operators](about_Type_Operators.md) - diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md index 46c3c136e573..e9c4ebaefa98 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,449 +7,409 @@ title: about_Parameters_Default_Values --- # About Parameters Default Values -## about_Parameters_Default_Values - ## SHORT DESCRIPTION -Describes how to set custom default values for the parameters of cmdlets and advanced functions. +Describes how to set custom default values for the parameters of cmdlets and +advanced functions. ## LONG DESCRIPTION -The $PSDefaultParameterValues preference variable lets you specify custom default values for any cmdlet or advanced function. Cmdlets and functions use the custom default value unless you specify another value in the command. -The authors of cmdlets and advanced functions set standard default values for their parameters. Typically, the standard default values are useful, but they might not be appropriate for all environments. +The \$PSDefaultParameterValues preference variable lets you specify custom +default values for any cmdlet or advanced function. Cmdlets and functions use +the custom default value unless you specify another value in the command. + +The authors of cmdlets and advanced functions set standard default values for +their parameters. Typically, the standard default values are useful, but they +might not be appropriate for all environments. -This feature is especially useful when you must specify the same alternate parameter value nearly every time you use the command or when a particular parameter value is difficult to remember, such as an e-mail server name or project GUID. +This feature is especially useful when you must specify the same alternate +parameter value nearly every time you use the command or when a particular +parameter value is difficult to remember, such as an e-mail server name or +project GUID. -If the desired default value varies predictably, you can specify a script block that provides different default values for a parameter under different conditions. +If the desired default value varies predictably, you can specify a script +block that provides different default values for a parameter under different +conditions. -$PSDefaultParameterValues was introduced in Windows PowerShell® 3.0. +\$PSDefaultParameterValues was introduced in PowerShell 3.0. +## SYNTAX -### SYNTAX The syntax of the $PSDefaultParameterValues preference variable is as follows: +```powershell +$PSDefaultParameterValues=@{":"=""} + +$PSDefaultParameterValues=@{":"={}} -``` -$PSDefaultParameterValues=@{":"=""} - -$PSDefaultParameterValues=@{":"={}} - $PSDefaultParameterValues["Disabled"]=$true | $false ``` - Wildcard characters are permitted in the CmdletName and ParameterName values. -The value of $PSDefaultParameterValues is a System.Management.Automation.DefaultParameterDictionary, a type of hash table that validates the format of keys. Enter a hash table where the key consists of the cmdlet name and parameter name separated by a colon (:) and the value is the custom default value. - -To set, change, add, or remove entries from $PSDefaultParameterValues, use the methods that you would use to edit a standard hash table. +The value of \$PSDefaultParameterValues is a +System.Management.Automation.DefaultParameterDictionary, a type of hash table +that validates the format of keys. Enter a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (:) and the value +is the custom default value. -The must be the name of a cmdlet or the name of an advanced function that uses the CmdletBinding attribute. You cannot use $PSDefaultParameterValues to specify default values for scripts or simple functions. +To set, change, add, or remove entries from \$PSDefaultParameterValues, use the +methods that you would use to edit a standard hash table. -The default value can be an object or a script block. If the value is a script block, Windows PowerShell evaluates the script block and uses the result as the parameter value. When the specified parameter takes a script block value, enclose the script block value in a second set of braces, such as: +The \ must be the name of a cmdlet or the name of an advanced +function that uses the CmdletBinding attribute. You cannot use +$PSDefaultParameterValues to specify default values for scripts or simple +functions. +The default value can be an object or a script block. If the value is a script +block, PowerShell evaluates the script block and uses the result as the +parameter value. When the specified parameter takes a script block value, +enclose the script block value in a second set of braces, such as: -``` +```powershell $PSDefaultParameterValues=@{ "Invoke-Command:ScriptBlock"={{Get-Process}} } ``` +For information about hash tables, see +[about_Hash_Tables](about_Hash_Tables.md). For information about script +blocks, see [about_Script_Blocks](about_Script_Blocks.md). For information +about preference variables, see +[about_Preference_Variables](about_Preference_Variables.md). -For information about hash tables, see about_Hash_Tables. For information about script blocks, see about_Script_Blocks. For information about preference variables, see about_Preference_Variables. - +## EXAMPLES -### EXAMPLES -The following command sets a custom default value for the SmtpServer parameter of the Send-MailMessage cmdlet. +The following command sets a custom default value for the SmtpServer parameter +of the Send-MailMessage cmdlet. - -``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"} +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" +} ``` +To set default values for multiple parameters, use a semi-colon (;) to +separate each Name\=Value pair. The following command adds a custom default +value for the LogName parameter of the `Get-WinEvent` cmdlet. -To set default values for multiple parameters, use a semi-colon (;) to separate each Name\=Value pair. The following command adds a custom default value for the LogName parameter of the Get-WinEvent cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5"; + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" +} ``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"} -``` - -You can use wildcard characters in the name of the cmdlet and parameter. The following command sets the Verbose common parameter to $true in all commands. Use $true and $false to set values for switch parameters, such as Verbose. +You can use wildcard characters in the name of the cmdlet and parameter. The +following command sets the Verbose common parameter to \$true in all commands. +Use \$true and \$false to set values for switch parameters, such as +**Verbose**. - -``` +```powershell $PSDefaultParameterValues = @{"*:Verbose"=$true} ``` +If a parameter takes multiple values (an array), you can set multiple values +as the default value. The following command sets the default value of the +**ComputerName** parameter of the Invoke-Command cmdlet to "Server01" and +"Server02". -If a parameter takes multiple values (an array), you can set multiple values as the default value. The following command sets the default value of the ComputerName parameter of the Invoke-Command cmdlet to "Server01" and "Server02". - - -``` -$PSDefaultParameterValues = @{"Invoke-Command:ComputerName"="Server01","Server02"} -``` - - -You can use a script block to specify different default values for a parameter under different conditions. Windows PowerShell evaluates the script block and uses the result as the default parameter value. - -The following command sets the default value of the Autosize parameter of the Format-Table cmdlet to $true when the host program is the Windows PowerShell console. - - -``` -$PSDefaultParameterValues=@{"Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}}} -``` - - -If a parameter takes a script block value, enclose the script block in an extra set of braces. When Windows PowerShell evaluates the outer script block, the result is the inner script block, which is set as the default parameter value. - -The following command sets the default value of the ScriptBlock parameter of Invoke-Command. Because the script block is enclosed in a second set of braces, the enclosed script block is passed to the Invoke-Command cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Invoke-Command:ComputerName"="Server01","Server02" +} ``` -$PSDefaultParameterValues=@{"Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}}} -``` - - - -### HOW TO SET $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. - -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues +You can use a script block to specify different default values for a parameter +under different conditions. PowerShell evaluates the script block and uses the +result as the default parameter value. -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. +The following command sets the default value of the Autosize parameter of the +Format-Table cmdlet to \$true when the host program is the PowerShell console. - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +$PSDefaultParameterValues=@{ + "Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}} +} ``` +If a parameter takes a script block value, enclose the script block in an +extra set of braces. When PowerShell evaluates the outer script block, the +result is the inner script block, which is set as the default parameter value. +The following command sets the default value of the ScriptBlock parameter of +`Invoke-Command`. Because the script block is enclosed in a second set of +braces, the enclosed script block is passed to the `Invoke-Command` cmdlet. -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational -Get*:Verbose True +```powershell +$PSDefaultParameterValues=@{ + "Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}} +} ``` +### HOW TO SET \$PSDefaultParameterValues -To get the value of a key, use the following command syntax: +\$PSDefaultParameterValues is a preference variable, so it exists only in the +session in which it is set. It has no default value. +To set \$PSDefaultParameterValues, type the variable name and one or more +key-value pairs at the command line. -``` -$PSDefaultParameterValues[""] -``` +If you type another \$PSDefaultParameterValues command, its value replaces the +original value. The original is not retained. +To save \$PSDefaultParameterValues for future sessions, add a +\$PSDefaultParameterValues command to your PowerShell profile. For more +information, see [about_Profiles](about_Profiles.md). -For example: +### HOW TO GET \$PSDefaultParameterValues +To get the value of \$PSDefaultParameterValues, at the command prompt, type: +```powershell +$PSDefaultParameterValues ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] -Server01AB234x5 -``` - - - -### HOW TO ADD VALUES TO $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. +For example, the first command sets the value of \$PSDefaultParameterValues. +The second command gets the value of \$PSDefaultParameterValues. -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues - -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. - - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +PS C:\> $PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" + "Get-*:Verbose"=$true +} ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To get the value of a \ key, use the following +command syntax: -To get the value of a key, use the following command syntax: - - -``` +```powershell $PSDefaultParameterValues[""] ``` - For example: - -``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] +```powershell +PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] Server01AB234x5 ``` +### HOW TO ADD VALUES TO PSDefaultParameterValues +To add or remove values from \$PSDefaultParameterValues, use the methods that +you would use for a standard hash table. -### HOW TO ADD VALUES TO $PSDefaultParameterValues -To add or remove values from $PSDefaultParameterValues, use the methods that you would use for a standard hash table. - -For example, to add a value to $PSDefaultParameterValues without affecting the existing values, use the Add method of hash tables. +For example, to add a value to \$PSDefaultParameterValues without affecting the +existing values, use the Add method of hash tables. The syntax of the Add method is as follows: - ``` .Add(Key, Value) ``` +where the Key is ":" and the value is the parameter +value. -where the Key is ":" and the value is the parameter value. - -Use the following command format to call the Add method on $PSDefaultParameterValues. Be sure to use a comma (,) to separate the key from the value, instead of the equal sign (\=). - +Use the following command format to call the Add method on +\$PSDefaultParameterValues. Be sure to use a comma (,) to separate the key +from the value, instead of the equal sign (\=). +```powershell +$PSDefaultParameterValues.Add( + ":", "" +) ``` -$PSDefaultParameterValues.Add(":", "") -``` - -For example, the following command adds "PowerShell" as the default value of the Name parameter of the Get-Process cmdlet. +For example, the following command adds "PowerShell" as the default value of +the Name parameter of the Get-Process cmdlet. - -``` +```powershell $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO REMOVE VALUES FROM \$PSDefaultParameterValues - -### HOW TO REMOVE VALUES FROM $PSDefaultParameterValues -To remove a value from $PSDefaultParameterValues, use the Remove method of hash tables. +To remove a value from \$PSDefaultParameterValues, use the Remove method of +hash tables. The syntax of the Remove method is as follows: - -``` +```powershell .Remove(Key) ``` +Use the following command format to call the Remove method on +\$PSDefaultParameterValues. -Use the following command format to call the Remove method on $PSDefaultParameterValues. - - -``` +```powershell $PSDefaultParameterValues.Remove(":") ``` +For example, the following command removes the Name parameter of the +`Get-Process` cmdlet and its values. -For example, the following command removes the Name parameter of the Get-Process cmdlet and its values. - - -``` +```powershell $PSDefaultParameterValues.Remove("Get-Process:Name") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Remove("Get-Process:Name") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO CHANGE VALUES IN \$PSDefaultParameterValues +To change a value in $PSDefaultParameterValues, use the following command +format. -### HOW TO CHANGE VALUES IN $PSDefaultParameterValues -To change a value in $PSDefaultParameterValues, use the following command format. - - -``` +```powershell $PSDefaultParameterValues["CmdletName:ParameterName"]="" ``` - The following example shows the effect of this command. +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - +```powershell +$PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" -``` - +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO DISABLE AND RE-ENABLE \$PSDefaultParameterValues +You can temporarily disable and then re-enable \$PSDefaultParameterValues. This +is very useful if you're running scripts that might assume different default +parameter values. -### HOW TO DISABLE AND RE-ENABLE $PSDefaultParameterValues -You can temporarily disable and then re-enable $PSDefaultParameterValues. This is very useful if you're running scripts that might assume different default parameter values. - -To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of $True. +To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of +\$True. For example, - -``` +```powershell $PSDefaultParameterValues.Add("Disabled", $true) ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$true ``` +The other values in \$PSDefaultParameterValues are preserved, but not +effective. -The other values in $PSDefaultParameterValues are preserved, but not effective. - +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Disabled True -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Disabled True +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To re-enable \$PSDefaultParameterValues, remove the Disabled key or change the +value of the Disabled key to \$False. -To re-enable $PSDefaultParameterValues, remove the Disabled key or change the value of the Disabled key to $False. - - -``` +```powershell $PSDefaultParameterValues.Remove("Disabled") ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$false ``` - -The previous value of $PSDefaultParameterValues is effective again. - +The previous value of \$PSDefaultParameterValues is effective again. ## KEYWORDS + about_PSDefaultParameterValues about_Parameters_DefaultValues about_DefaultValues - ## SEE ALSO [about_Hash_Tables](about_Hash_Tables.md) @@ -459,4 +419,3 @@ about_DefaultValues [about_Profiles](about_Profiles.md) [about_Script_Blocks](about_Script_Blocks.md) - diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Prompts.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Prompts.md index 52e5fba3fc21..6f1820bea646 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Prompts.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Prompts.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,308 +7,284 @@ title: about_Prompts --- # About Prompts -## about_Prompts - ## SHORT DESCRIPTION -Describes the Prompt function and demonstrates how to create a custom Prompt function. +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: +The PowerShell command prompt indicates that PowerShell is ready to run a +command: ``` PS C:\> ``` +The PowerShell prompt is determined by the built-in Prompt function. You can +customize the prompt by creating your own Prompt function and saving it in +your PowerShell profile. -The Windows PowerShell prompt is determined by the built-in Prompt function. You can customize the prompt by creating your own Prompt function and saving it in your Windows PowerShell profile. - +## ABOUT THE PROMPT FUNCTION -### ABOUT 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 determines the appearance of the PowerShell prompt. +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: - -``` +```powershell function Prompt { } ``` +The Prompt function must return an object. As a best practice, return a string +or an object that is formatted as a string. The maximum recommended length is +80 characters. -The Prompt function must return an object. As a best practice, return a string or an object that is formatted as a string. The maximum recommended length is 80 characters. - -For example, the following prompt function returns a "Hello, World" string followed by a caret (>). +For example, the following prompt function returns a "Hello, World" string +followed by a caret (>). - -``` -PS C:\> function prompt {"Hello, World > "} +```powershell +PS C:\> function prompt {"Hello, World > "} Hello, World > ``` - - ### GETTING THE PROMPT FUNCTION -To get the Prompt function, use the Get-Command cmdlet or use the Get-Item cmdlet in the Function drive. -Functions are commands. So, you can use the Get-Command cmdlet to get functions, including the Prompt function. +To get the Prompt function, use the `Get-Command` cmdlet or use the `Get-Item` +cmdlet in the Function drive. For example: +```powershell +PS C:\> Get-Command Prompt -``` -PS C:\> Get-Command Prompt - -CommandType Name ModuleName ------------ ---- ---------- +CommandType Name ModuleName +----------- ---- ---------- Function prompt ``` - -To get the script that sets the value of the prompt, use the dot method to get the ScriptBlock property of the Prompt function. +To get the script that sets the value of the prompt, use the dot method to get +the ScriptBlock property of the Prompt function. For example: +```powershell +PS C:\> (Get-Command Prompt).ScriptBlock -``` -PS C:\> (Get-Command Prompt).ScriptBlock - -"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -# .Link -# http://go.microsoft.com/fwlink/?LinkID=225750 +"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPr +omptLevel + 1)) " +# .Link +# http://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml ``` +Like all functions, the Prompt function is stored in the Function: drive. To +display the script that creates the current Prompt function, type: -Like all functions, the Prompt function is stored in the Function: drive. To display the script that creates the current Prompt function, type: - - -``` +```powershell (Get-Item function:prompt).ScriptBlock ``` - ### THE DEFAULT PROMPT -The default prompt appears only when the Prompt function generates an error or does not return an object. -The default Windows PowerShell prompt is: +The default prompt appears only when the Prompt function generates an error or +does not return an object. +The default PowerShell prompt is: ``` PS> ``` +For example, the following command sets the Prompt function to $null, which is +invalid. As a result, the default prompt appears. -For example, the following command sets the Prompt function to $null, which is invalid. As a result, the default prompt appears. - - -``` -PS C:\> function prompt {$null} +```powershell +PS C:\> function prompt {$null} PS> ``` - -Because Windows PowerShell comes with a built-in prompt, you usually do not see the default prompt. - +Because PowerShell comes with a built-in prompt, you usually do not see the +default prompt. ### BUILT-IN PROMPT -Windows PowerShell includes a built-in prompt function. - -In Windows PowerShell 3.0, the built-in prompt function is: - - -``` -function prompt -{ - "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -} -``` - -This simplified prompt starts with "PS" followed by the current location, and one ">" for each nested prompt level. +PowerShell includes a built-in prompt function. -In Windows PowerShell 2.0, the built-in prompt function is: - - -``` -function prompt -{ - $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } - else { '' }) + 'PS ' + $(Get-Location) ` - + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' +```powershell +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: -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: - - -``` +```Output [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 (>). -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: -``` -For example: - PS C:\ps-test> +```Output +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.) -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: -For example, when you are debugging in a nested prompt, the prompt resembles the following prompt: - - -``` +```Output [DBG] PS C:\ps-test>>> ``` - - ### CHANGES TO THE PROMPT -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: +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 +```Output +PS Hello, World> Enter-PSSession Server01 [Server01]: PS Hello, World> ``` +Other PowerShell host applications and alternate shells might have their own +custom command prompts. -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. - +For more information about the \$PSDebugContext and $NestedPromptLevel +automatic variables, see [about_Automatic_Variables](about_Automatic_Variables.md). ### HOW TO CUSTOMIZE 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: +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: -``` +```powershell function prompt { } ``` - -Then, between the braces, enter the commands or the string that creates your prompt. +Then, between the braces, enter the commands or the string that creates your +prompt. For example, the following prompt includes your computer name: - -``` +```powershell function prompt {"PS [$env:COMPUTERNAME]> "} ``` - On the Server01 computer, the prompt resembles the following prompt: - -``` +```Output PS [Server01] > ``` - The following prompt function includes the current date and time: - -``` +```powershell function prompt {"$(get-date)> "} ``` - The prompt resembles the following prompt: - -``` +```Output 03/15/2012 17:49:47> ``` - You can also change the default Prompt function: -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) { '>>' }) + '> ' +For example, the following modified Prompt function adds "[ADMIN]:" to the +built-in PowerShell prompt when PowerShell is opened by using the "Run as +administrator" option: + +```powershell +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 PowerShell by using the "Run as administrator" option, a prompt +that resembles the following prompt appears: -When you start Windows PowerShell by using the "Run as administrator" option, a prompt that resembles the following prompt appears: - - -``` +```Output [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. -The following Prompt function displays the history ID of the next command. To view the command history, use the Get-History cmdlet. - +```powershell +function prompt { + # The at sign creates an array in case only one history item exists. + $history = @(get-history) + if($history.Count -gt 0) + { + $lastItem = $history[$history.Count - 1] + $lastId = $lastItem.Id + } -``` -function prompt -{ - # The at sign creates an array in case only one history item exists. - $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 >" + $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, PowerShell uses the default prompt, "PS>". -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 -ForegroundColor $Color - return " " +```powershell +function prompt { + $color = Get-Random -Min 1 -Max 16 + Write-Host ("PS " + $(Get-Location) +">") -NoNewLine ` + -ForegroundColor $Color + return " " } ``` - - ### SAVING THE PROMPT FUNCTION -Like any function, the Prompt function exists 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. +Like any function, the Prompt function exists only in the current session. To +save the Prompt function for future sessions, add it to your PowerShell +profiles. For more information about profiles, see about_Profiles. ## SEE ALSO -Get-Location +[Get-Location](../../Microsoft.PowerShell.Management/Get-Location.md) -Enter-PSSession +[Enter-PSSession](../Enter-PSSession.md) -Get-History +[Get-History](../Get-History.md) -Get-Random +[Get-Random](../../Microsoft.PowerShell.Utility/Get-Random.md) -Write-Host +[Write-Host](../../Microsoft.PowerShell.Utility/Write-Host.md) [about_Profiles](about_Profiles.md) diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md deleted file mode 100644 index af9999f5f30a..000000000000 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -ms.date: 2017-06-09 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_packagemanagement ---- - -# About PackageManagement -## about_PackageManagement -# TOPIC - -about_PackageManagement - -# SHORT DESCRIPTION - -PackageManagement is an aggregator for software package managers. - -# LONG DESCRIPTION - -PackageManagement functionality was introduced in Windows PowerShell 5.0. - -PackageManagement is a unified interface for software package management systems; you -can run PackageManagement cmdlets to perform software discovery, installation, and -inventory (SDII) tasks. Regardless of the underlying installation technology, -you can run the common cmdlets in the PackageManagement module to search for, -install, or uninstall packages; add, remove, and query package repositories; and -run queries on a computer to determine which software packages are installed. - -PackageManagement supports a flexible plug-in model that enables support for other -software package management systems. - -The PackageManagement module is included with Windows PowerShell 5.0 and later releases -of Windows PowerShell, and works on three levels of package management -structure: package providers, package sources, and the packages themselves. - -Term Description ----------- ------------------------------ -Package manager Software package management system. In -PackageManagement terms, this is a package provider. -Package provider PackageManagement term for a package manager. Examples -can include Windows Installer, Chocolatey, -and others. -Package source A URL, local folder, or network shared folder that -you configure package providers to use as a -repository. -Package A piece of software that a package provider manages, -and that is stored in a specific package source. - -The PackageManagement module includes the following cmdlets. You can find the -Help for these cmdlets on TechNet starting on the following page: -http://technet.microsoft.com/library/dn890951(v=wps.640).aspx. - -Cmdlet Description ----------- ------------------------------ -Get-PackageProvider Returns a list of package providers that are -connected to PackageManagement. -Get-PackageSource Gets a list of package sources that are -registered for a package provider. -Register-PackageSource Adds a package source for a specified -package provider. -Set-PackageSource Sets properties on an existing package -source. -Unregister-PackageSource Removes a registered package source. -Get-Package Returns a list of installed software -packages. -Find-Package Finds software packages in available -package sources. -Install-Package Installs one or more software packages. -Save-Package Saves packages to the local computer -without installing them. -Uninstall-Package Uninstalls one or more software packages. - -PackageManagement Package Provider Bootstrapping and Dynamic Cmdlet Parameters - -By default, PackageManagement ships with a core bootstrap provider. You can install -additional package providers as you need them by bootstrapping the providers; -that is, responding to a prompt to install the provider automatically, from a -web service. You can specify a package provider with any PackageManagement cmdlet; -if the specified provider is not available, PackageManagement prompts you to bootstrap ---or automatically install--the provider. In the following examples, if the -Chocolatey provider is not already installed, PackageManagement bootstrapping installs -the provider. - -Find-Package -Provider Chocolatey - -If the Chocolatey provider is not already installed, when you run the -preceding command, you are prompted to install it. - -Install-Package -ForceBootstrap - -If the Chocolatey provider is not already installed, when you run the -preceding command, the provider is installed; but because the ForceBootstrap -parameter has been added to the command, you are not prompted to install it; -both the provider and the package are installed automatically. - -When you try to install a package, if you do not already have the supporting -provider installed, and you do not add the ForceBootstrap parameter to your -command, PackageManagement prompts you to install the provider. - -Specifying a package provider in your PackageManagement command can make -dynamic parameters available that are specific to that package provider. -When you run Get-Help for a specific PackageManagement cmdlet, a list of -parameter sets are returned, grouping dynamic parameters for available -package providers in separate parameter sets. - -More Information About the PackageManagement Project - -For more information about the PackageManagement open development project, -including how to create a PackageManagement package provider, see the -PackageManagement project on GitHub at https://oneget.org. - -# SEE ALSO - -Get-PackageProvider - -Get-PackageSource - -Register-PackageSource - -Set-PackageSource - -Unregister-PackageSource - -Get-Package - -Find-Package - -Install-Package - -Save-Package - -Uninstall-Package - diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_pipelines.md index 1ae1a64986f8..97cd9535c505 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,41 +7,39 @@ title: about_pipelines --- # About Pipelines -## about_Pipelines - - ### Short Description -Combining commands into pipelines in the Windows PowerShell +Combining commands into pipelines in the 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. +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 powerful -command chain or "pipeline" that is comprised of a series of simple commands. +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 powerful command +chain or "pipeline" that is comprised of a series of simple commands. For example, + ```powershell 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` processes -the objects and send them down the pipeline. Because there are no more commands in -the pipeline, the results are displayed at the console. +`Command-2` processes the objects and sends them to `Command-3`. `Command-3` +processes the objects and send them down the pipeline. Because there are no +more commands 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. +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. +Here is a simple example. The following command gets the Notepad process and +then stops it. For example, ```powershell @@ -49,77 +47,69 @@ 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 object -to the `Stop-Process` cmdlet, which stops the Notepad process. Notice that the -`Stop-Process` command does not have a Name or ID parameter to specify the process, -because the specified process is submitted through the pipeline. +the Notepad process. It uses a pipeline operator (`|`) to send the process +object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice +that the `Stop-Process` command does not have a Name or ID parameter to +specify the process, because the specified process is submitted through the +pipeline. Here is a practical example. This command pipeline gets the text files in the -current directory, selects only the files that are more than 10,000 bytes long, -sorts them by length, and displays the name and length of each file in a table. +current directory, selects only the files that are more than 10,000 bytes +long, sorts them by length, and displays the name and length of each file in a +table. ```powershell 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 command -is written horizontally, but we will show the process vertically in the following -graphic. +This pipeline is comprised of four commands in the specified order. The +command is written horizontally, but we will show the process vertically in +the following graphic. `Get-ChildItem` `-Path` *.txt - **|** - -| (FileInfo objects ) -| ( .txt ) - - **|** - - **V** +``` +| +| (FileInfo objects for *.txt) +| +V +``` `Where-Object` {$_.length `-gt` 10000} - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| +V +``` `Sort-Object` `-Property` Length - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) -| ( Sorted by length ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.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** - ``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| ( Sorted by length ) +| ( Formatted in a table ) +| +V +``` + +```output Name Length ---- ------ tmp1.txt 82920 @@ -129,13 +119,13 @@ tmp3.txt 114000 ### Using Pipelines +The PowerShell cmdlets were designed to be used in pipelines. For example, 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. -The Windows PowerShell cmdlets were designed to be used in pipelines. For example, -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 `Start-Service` -or `Stop-Service` cmdlets (although disabled services cannot be restarted in this way). +For example, you can pipe any service from the `Get-Service` cmdlet to the +`Start-Service` or `Stop-Service` cmdlets (although disabled services cannot +be restarted in this way). This command pipeline starts the WMI service on the computer: @@ -144,90 +134,98 @@ For example, Get-Service wmi | Start-Service ``` -The cmdlets that get and set objects of the Windows PowerShell providers, such as the +The cmdlets that get and set objects of the PowerShell providers, such 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` command in the -Windows PowerShell registry provider to the `New-ItemProperty` cmdlet. This command adds -a new registry entry, NoOfEmployees, with a value of 8124, to the MyCompany registry key. +For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` +command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. +This command adds a new registry entry, NoOfEmployees, with a value of 8124, +to the MyCompany registry key. For example, ```powershell -Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 +Get-Item -Path HKLM:\Software\MyCompany | + New-ItemProperty -Name NoOfEmployees -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 any objects to -these cmdlets. +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 any 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. +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. For example, + ```powershell Get-Process | Sort-Object -Property handles ``` -Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and -`Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out -cmdlets, such as `Out-Printer`. +Also, you can pipe any objects to the formatting cmdlets, such as +`Format-List` 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. +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. For example, + ```powershell Get-Process winlogon | Format-List -Property * ``` -With a bit of practice, you'll find that combining simple commands into pipelines -saves time and typing, and makes your scripting more efficient. +With a bit of practice, you'll find that combining simple commands into +pipelines 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 command +to another command, PowerShell tries to associate the piped objects with one +of the parameters of the receiving cmdlet. -When you "pipe" objects, that is send the objects in the output of one command 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 associates input objects -with cmdlet parameters, tries to find a parameter that meets the following criteria: +To do so, the PowerShell "parameter binding" component, which associates 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 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 `-InputObject` 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`. +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 `-InputObject` 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 PowerShell prompts you -for the missing parameter values. +If the parameter binding component of PowerShell cannot associate the piped +objects with a parameter of the receiving cmdlet, the command fails and +PowerShell prompts you for the missing parameter values. -You cannot force the parameter binding component to associate the piped objects with a particular -parameter -- you cannot even suggest a parameter. Instead, the logic of the component manages -the piping as efficiently as possible. +You cannot force the parameter binding component to associate the piped +objects with a particular parameter. You cannot even suggest a parameter. +Instead, the logic of the 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. -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: +For example, piping objects representing the services on the computer to a +`Format-Table` command, such as: ```powershell Get-Service | Format-Table -Property name, dependentservices ``` -is much like saving the service objects in a variable and using the InputObject parameter -of `Format-Table` to submit the service object. +is much like saving the service objects in a variable and using the +InputObject parameter of `Format-Table` to submit the service object. For example, + ```powershell $services = Get-Service Format-Table -InputObject $services -Property name, dependentservices @@ -236,51 +234,58 @@ Format-Table -InputObject $services -Property name, dependentservices or imbedding the command in the parameter value For example, + ```powershell -Format-Table -InputObject (Get-Service wmi) -Property name, dependentservices +Format-Table -InputObject (Get-Service wmi) -Property name,dependentservices ``` -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 you use a -command parameter, the objects are sent as a single array object. +However, there is an important difference. When you pipe multiple objects to a +command, PowerShell sends the objects to the command one at a time. When you +use a command parameter, the objects are sent as a single array object. + +This seemingly technical difference can have interesting, and sometimes +useful, consequences. -This seemingly technical difference can have interesting, and sometimes useful, consequences. +For example, if you pipe multiple process objects from the `Get-Process` +cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one +at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the +process objects, and their properties and methods. -For example, if you pipe multiple process objects from the `Get-Process` cmdlet 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 their properties and methods. -(`Get-Member` eliminates duplicates, so if the objects are all of the same type, it displays only -one object type.) +NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the +same type, it displays only one object type. -In this case, `Get-Member` displays the properties and methods of each process object, that is, a -System.Diagnostics.Process object. +In this case, `Get-Member` displays the properties and methods of each process +object, that is, a System.Diagnostics.Process object. For example, + ```powershell Get-Process | Get-Member ``` -``` +```Output TypeName: System.Diagnostics.Process -Name MemberType Definition ----- ---------- ---------- -Handles AliasProperty Handles = Handlecount -Name AliasProperty Name = ProcessName -NPM AliasProperty NPM = NonpagedSystemMemorySize +Name MemberType Definition +---- ---------- ---------- +Handles AliasProperty Handles = Handlecount +Name AliasProperty Name = ProcessName +NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then `Get-Member` receives an -array of System.Diagnostics.Process objects as a single unit, and it displays the properties -of an array of objects. (Note the array symbol ([]) after the System.Object type name.) +However, if you use the InputObject parameter of `Get-Member`, then +`Get-Member` receives an array of System.Diagnostics.Process objects as a +single unit, and it displays the properties of an array of objects. (Note the +array symbol ([]) after the System.Object type name.) For example, + ```powershell Get-Member -InputObject (Get-Process) ``` -``` +```Output TypeName: System.Object[] Name MemberType Definition @@ -291,30 +296,32 @@ Clone Method System.Object Clone() ... ``` -This result might not be what you intended, but after you understand it, you 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. +This result might not be what you intended, but after you understand it, you +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. For example, + ```powershell (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. +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** or **Parameter** -parameters to determine which, if any, of a cmdlet's parameters 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** or **Parameter** parameters to determine which, if any, of a +cmdlet's parameters accepts pipeline input. -In the `Get-Help` default display, the "Accept 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. +In the `Get-Help` default display, the "Accept 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` cmdlet accepts -pipeline input, type: +For example, to determine which of the parameters of the `Start-Service` +cmdlet accepts pipeline input, type: ```powershell Get-Help Start-Service -Full @@ -326,108 +333,115 @@ or Get-Help Start-Service -Parameter * ``` -For example, the help for the `Start-Service` cmdlet shows that the **InputObject** and **Name** -parameters accept pipeline input ("true"). All other parameters have a value of "false" -in the "Accept pipeline input?" row. +For example, the help for the `Start-Service` cmdlet shows that the +**InputObject** and **Name** parameters accept pipeline input ("true"). All +other parameters have a value of "false" in the "Accept pipeline input?" row. ``` -InputObject - 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. +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? true - Position? 0 - Default value None - Accept pipeline input? True (ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByValue) +Accept wildcard characters? false -Name - Specifies the service names for the service to be started. +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. +The parameter name is optional. You can use Name or its alias, ServiceName, +or you can omit the parameter name. - Required? true - Position? 0 - Default value None - Accept pipeline input? True (ByPropertyName, ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByPropertyName, ByValue) +Accept wildcard characters? false ``` This means that you can send objects (PsObjects) through the pipeline to the -`Where-Object` cmdlet and Windows PowerShell will associate the object with the +`Where-Object` cmdlet and PowerShell will associate the object with the **InputObject** and **Name** parameters. ### 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 objects -that have the same .NET type as their parameter value or objects that can 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. + that have the same .NET type as their parameter value or objects that can be + converted to that type. -- ByPropertyName: Parameters that accept input "by property name" can accept piped -objects only when a property of the object has the same name as the parameter. + 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. -For example, the Name parameter of `Start-Service` can accept objects that have -a Name property. +- ByPropertyName: Parameters that accept input "by property name" can accept + piped objects only when a property of the object has the same name as the + parameter. -(To list the properties of an object, pipe it to `Get-Member`.) + For example, the Name parameter of `Start-Service` can accept objects that + 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 parameters are -designed to take input from the pipeline easily. +Some parameters can accept objects by value or by property name. These +parameters 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 failure and -rewrite the command. +If a command fails because of a pipeline error, you can investigate the +failure 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 destination path and -then piping the path to the `Move-ItemProperty` cmdlet. +registry key to another by using the `Get-Item` cmdlet to get the destination +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. The `Move-ItemProperty` -command specifies the current path and name of the registry entry to be moved. +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. The `Move-ItemProperty` command specifies the +current path and name of the registry entry to be moved. For example, + ```powershell 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 +The command fails and 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 pipeline input. +```output +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 +pipeline input. At line:1 char:23 -+ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name product ++ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name p ``` -To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of -Windows PowerShell. The following command traces the Parameter Binding component 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 reference. +To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding +component of PowerShell. The following command traces the Parameter Binding +component 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 reference. For example, + ```powershell -Trace-Command -Name parameterbinding -Expression {Get-Item -Path HKLM:\software\mycompany\sales | -Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} -PSHost -FilePath debug.txt +Trace-Command -Name parameterbinding -Expression { + Get-Item -Path HKLM:\software\mycompany\sales | + Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} ` + -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. +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`] @@ -442,31 +456,35 @@ 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 parameter -of `Move-ItemProperty` failed. +Finally, it shows that the attempt to bind the path to the **Destination** +parameter 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 ValueFromPipelineByPropertyName NO COERCION -Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION +Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyName NO CO +ERCION +Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COE +RCION ... +``` - -To investigate the failure, use the `Get-Help` cmdlet to view the attributes of the -**Destination** parameter. The following command gets detailed information about the -**Destination** parameter. +To investigate the failure, use the `Get-Help` cmdlet to view the attributes +of the **Destination** parameter. The following command gets detailed +information about the **Destination** parameter. ```powershell Get-Help Move-ItemProperty -Parameter Destination ``` -The results show that **Destination** takes pipeline input only "by property name". -That is, the piped object must have a property named Destination. +The results show that **Destination** takes pipeline input only "by property +name". That is, the piped object must have a property named Destination. ``` -Destination @@ -479,11 +497,12 @@ That is, the piped object must have a property named Destination. Accept wildcard characters? false ``` -To see the properties of the object being piped to the `Move-ItemProperty` cmdlet, -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. +To see the properties of the object being piped to the `Move-ItemProperty` +cmdlet, 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. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` @@ -491,11 +510,13 @@ 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-ItemProperty` cmdlet. We can -use a `Get-ItemProperty` command to get the path, but the name and destination must be specified -in the `Move-ItemProperty` part of the command. +To fix the command, we must specify the destination in the `Move-ItemProperty` +cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name +and destination must be specified in the `Move-ItemProperty` part of the +command. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\design | Move-ItemProperty -Dest HKLM:\software\mycompany\design -Name product @@ -510,9 +531,11 @@ Get-Itemproperty HKLM:\software\mycompany\sales The results show that the Product registry entry was moved to the Sales key. -``` -PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany\sales -PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany +```Output +PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany\sales +PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany PSChildName : sales PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry @@ -528,4 +551,3 @@ Product : 18 [about_command_syntax](about_command_syntax.md) [about_foreach](about_foreach.md) - diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_profiles.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_profiles.md index b7eabd81d0ce..eea0dd9f0d50 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_profiles.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_profiles.md @@ -1,104 +1,99 @@ --- -ms.date: 2017-06-25 +ms.date: 2017-11-30 schema: 2.0.0 keywords: powershell,cmdlet title: about_Profiles --- # About Profiles -## about_Profiles +## SHORT DESCRIPTION -# SHORT DESCRIPTION +Describes how to create and use a PowerShell profile. -Describes how to create and use a Windows PowerShell profile. +## LONG DESCRIPTION -# LONG DESCRIPTION +You can create a PowerShell profile to customize your environment and to add +session-specific elements to every PowerShell session that you start. -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 PowerShell profile is a script that runs when 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 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. -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. +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. -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 PowerShell console +(PowerShell.exe) to start PowerShell without any profiles. And, it explains +the effect of the PowerShell execution policy on profiles. -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 -# THE PROFILE FILES +PowerShell supports several profile files. Also, PowerShell host programs can +support their own host-specific profiles. - -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 +For example, the 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\Profile.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 | +|Description | Path | +|--------------------------|------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Profile.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 +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\Microsoft.PowerShellISE_profile.ps1 | -| All users, Current Host | $PsHome\Microsoft.PowerShellISE_profile.ps1 | +In addition, other programs that host PowerShell can support their own +profiles. For example, PowerShell Integrated Scripting Environment (ISE) +supports the following host-specific profiles. -In Windows PowerShell Help, the "CurrentUser, Current Host" profile is the profile most -often referred to as "your Windows PowerShell profile". +|Description | Path | +|--------------------------|-------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Microsoft.PowerShellISE_profile.ps1 | +|All users, Current Host |$PsHome\Microsoft.PowerShellISE_profile.ps1| -# THE $PROFILE VARIABLE +In PowerShell Help, the "CurrentUser, Current Host" profile is the profile +most often referred to as "your PowerShell profile". +## THE $PROFILE VARIABLE -The `$Profile` automatic variable stores the paths to the Windows PowerShell -profiles that are available in the current session. +The `$Profile` automatic variable stores the paths to the 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. +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 | +|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. +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 PowerShell host application that you use. To see the current values of the `$Profile` variable, type: @@ -107,24 +102,22 @@ $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: +following command opens the "Current User, Current Host" profile in Notepad: ```powershell notepad $profile ``` -The following command determines whether an "All Users, All Hosts" profile -has been created on the local computer: +The following command determines whether an "All Users, All Hosts" profile has +been created on the local computer: ```powershell Test-Path -Path $profile.AllUsersAllHosts ``` -# HOW TO CREATE A PROFILE +## HOW TO CREATE A PROFILE - -To create a Windows PowerShell profile, use the following command format: +To create a PowerShell profile, use the following command format: ```powershell if (!(Test-Path -Path )) @@ -132,7 +125,7 @@ if (!(Test-Path -Path )) ``` For example, to create a profile for the current user in the current -Windows PowerShell host application, use the following command: +PowerShell host application, use the following command: ```powershell if (!(Test-Path -Path $profile)) @@ -140,21 +133,18 @@ if (!(Test-Path -Path $profile)) ``` In this command, the If statement prevents you from overwriting an existing -profile. Replace the value of the placeholder with the path +profile. Replace the value of the \ 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 +> Note: To create "All Users" profiles in Windows Vista and later versions of +> Windows, start 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. +You can open any 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: +To open the profile of the current user in the current PowerShell host +application in Notepad, type: ```powershell notepad $profile @@ -167,106 +157,99 @@ 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. +To apply the changes, save the profile file, and then restart PowerShell. -# HOW TO CHOOSE A PROFILE +## 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 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: +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 - + `$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 +implementation of 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. +Many of the items that you create in 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](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), -and Windows PowerShell snap-ins that you add to the session. +variables, aliases, functions, commands (except for +[Set-ExecutionPolicy](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), +and PowerShell modules 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. +To save these items and make them available in all future sessions, add them +to a 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. +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 +## 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. +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: +### 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: ```powershell function Pro {notepad $profile.CurrentUserAllHosts} ``` -- Add a function that opens Windows PowerShell Help in a compiled HTML -Help file (.chm) +### Add a function that opens PowerShell Help in a compiled HTML + Help file (.chm) ```powershell -function Get-CHM -{ -Invoke-Item -Path "$env:windir\help\mui\0409\WindowsPowerShellHelp.chm" +function Get-CHM { + Invoke-Item -Path "$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. +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 +### Add a function that lists the aliases for any cmdlet ```powershell -function Get-CmdletAlias ($cmdletname) -{ -Get-Alias | Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | Format-Table -Property Definition, Name -AutoSize +function Get-CmdletAlias ($cmdletname) { + Get-Alias | + Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | + Format-Table -Property Definition, Name -AutoSize } ``` -- Customize your console +### Customize your console ```powershell -function Color-Console -{ -$Host.ui.rawui.backgroundcolor = "white" -$Host.ui.rawui.foregroundcolor = "black" -$hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime -$hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" -$Host.UI.RawUI.WindowTitle = "Windows PowerShell $hostversion ($hosttime)" -Clear-Host +function Color-Console { + $Host.ui.rawui.backgroundcolor = "white" + $Host.ui.rawui.foregroundcolor = "black" + $hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime + $hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" + $Host.UI.RawUI.WindowTitle = "PowerShell $hostversion ($hosttime)" + Clear-Host } Color-Console ``` -- Add a customized Windows PowerShell prompt that includes the computer -name and the current path +### Add a customized PowerShell prompt ```powershell function Prompt @@ -275,18 +258,16 @@ $env:COMPUTERNAME + "\" + (Get-Location) + "> " } ``` -For more information about the Windows PowerShell prompt, see +For more information about the PowerShell prompt, see [about_Prompts](about_Prompts.md). -# THE NOPROFILE PARAMETER +## THE NOPROFILE PARAMETER +To start PowerShell without profiles, use the **NoProfile** parameter of +PowerShell.exe, the program that starts PowerShell. -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. +To begin, open a program that can start PowerShell, such as Cmd.exe or +PowerShell itself. You can also use the Run dialog box in Windows. Type: @@ -294,56 +275,58 @@ Type: PowerShell -NoProfile ``` -For a complete list of the parameters of PowerShell.exe, -type: +For a complete list of the parameters of PowerShell.exe, type: ``` PowerShell -? ``` -# PROFILES AND EXECUTION POLICY - +## 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. +The 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. +one of the few commands that applies in all 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 +## PROFILES AND REMOTE SESSIONS +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 +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 sessions. +To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) +cmdlet. -To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) cmdlet. - -For example, the following command runs the "Current user, Current Host" profile from -the local computer in the session in $s. +For example, the following command runs the "Current user, Current Host" +profile from the local computer in the session in $s. ```powershell Invoke-Command -Session $s -FilePath $profile ``` -The following command runs the "Current user, Current Host" 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. +The following command runs the "Current user, Current Host" 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. ```powershell -Invoke-Command -SessionName $s -ScriptBlock {Invoke-Command -FilePath "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"} +Invoke-Command -SessionName $s -ScriptBlock { +$path = "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1" +Invoke-Command -FilePath $path +} ``` After running this command, the commands that the profile adds to the session are available in $s. -# SEE ALSO +## SEE ALSO [about_Automatic_Variables](about_Automatic_Variables.md) diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md index ac34a820e26c..0f745ac3aa94 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Object_Creation.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,232 +7,246 @@ title: about_Object_Creation --- # About Object Creation -## about_Object_Creation - ## SHORT DESCRIPTION -Explains how to create objects in Windows PowerShell? +Explains how to create objects in PowerShell. ## LONG DESCRIPTION -You can create objects in Windows PowerShell and use the objects that you create in commands and scripts. - -There are several ways to create objects: - -New-Object: -The New-Object cmdlet creates an instance of a .NET Framework object or COM object. +You can create objects in PowerShell and use the objects that you create in +commands and scripts. -Hash tables: +There are several ways to create objects: -Beginning in Windows PowerShell 3.0, you can create objects from hash tables of property names and property values. +- `New-Object`: This cmdlet creates an instance of a .NET Framework object or + COM object. -Import-Csv: +- Hash tables: Beginning in PowerShell 3.0, you can create objects + from hash tables of property names and property values. -The Import-Csv cmdlet creates custom objects (PSCustomObject) from the items in a CSV file. Each row is an object instance and each column is an object property. +- `Import-Csv`: This cmdlet creates custom objects (PSCustomObject) from the + items in a CSV file. Each row is an object instance and each column is an + object property. This topic will demonstrate and discuss each of these methods. - ## NEW-OBJECT -The New-Object cmdlet provides a robust and consistent way to create new objects. The cmdlet works with almost all types and in all supported versions of Windows PowerShell. -To create a new object, specify either the type of a .NET Framework class or a ProgID of a COM object. +The `New-Object` cmdlet provides a robust and consistent way to create new +objects. The cmdlet works with almost all types and in all supported versions +of PowerShell. -For example, the following command creates a Version object. +To create a new object, specify either the type of a .NET Framework class or a +ProgID of a COM object. +For example, the following command creates a Version object. -``` -PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 +```powershell +PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 PS C:\> $v ``` - - -``` -Major Minor Build Revision ------ ----- ----- -------- +```Output +Major Minor Build Revision +----- ----- ----- -------- 2 0 0 1 ``` +```powershell +PS C:\> $v | Get-Member - -``` -PS C:\> $v | Get-Member - TypeName: System.Version ``` - For more information, see the help topic for the New-Object cmdlet. - ### CREATE OBJECTS FROM HASH TABLES -Beginning in Windows PowerShell 3.0, you can create an object from a hash table of properties and property values. -The syntax is as follows: +Beginning in PowerShell 3.0, you can create an object from a hash table of +properties and property values. +The syntax is as follows: ``` -[]@{=;=} +[]@{ + = + = +} ``` - -This method works only for classes that have a null constructor, that is, a constructor that has no parameters. The object properties must be public and settable. - +This method works only for classes that have a null constructor, that is, a +constructor that has no parameters. The object properties must be public and +settable. ### CREATE CUSTOM OBJECTS FROM HASH TABLES -Custom objects are very useful and they are very easy to create by using the hash table method. To create a custom object, use the PSCustomObject class, a class designed specifically for this purpose. - -Custom objects are an excellent way to return customized output from a function or script; far more useful than returning formatted output that cannot be reformatted or piped to other commands. - -The commands in the Test-Object function set some variable values and then use those values to create a custom object. (You can see this object in use in the example section of the Update-Help cmdlet help topic.) - -``` -function Test-Object -{ $ModuleName = "PSScheduledJob" - $HelpCulture = "en-us" - $HelpVersion = "3.1.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} - - $ModuleName = "PSWorkflow" - $HelpCulture = "en-us" - $HelpVersion = "3.0.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} +Custom objects are very useful and they are very easy to create by using the +hash table method. To create a custom object, use the PSCustomObject class, a +class designed specifically for this purpose. + +Custom objects are an excellent way to return customized output from a +function or script; far more useful than returning formatted output that +cannot be reformatted or piped to other commands. + +The commands in the `Test-Object function` set some variable values and then +use those values to create a custom object. You can see this object in use in +the example section of the `Update-Help` cmdlet help topic. + +```powershell +function Test-Object { + $ModuleName = "PSScheduledJob" + $HelpCulture = "en-us" + $HelpVersion = "3.1.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } + $ModuleName = "PSWorkflow" + $HelpCulture = "en-us" + $HelpVersion = "3.0.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } } ``` +The output of this function is a collection of custom objects formatted as a +table by default. -The output of this function is a collection of custom objects formatted as a table by default. - +```powershell +PS C:\> Test-Object -``` -PS C:\> Test-Object - -ModuleName UICulture Version ---------- --------- ------- -PSScheduledJob en-us 3.1.0.0 +ModuleName UICulture Version +--------- --------- ------- +PSScheduledJob en-us 3.1.0.0 PSWorkflow en-us 3.0.0.0 ``` +Users can manage the properties of the custom objects just as they do with +standard objects. -Users can manage the properties of the custom objects just as they do with standard objects. - - -``` -PS C:\> (Test-Object).ModuleName - PSScheduledJob +```powershell +PS C:\> (Test-Object).ModuleName + PSScheduledJob PSWorkflow ``` - - #### CREATE NON-CUSTOM OBJECTS FROM HASH TABLES -You can also use hash tables to create objects for non-custom classes. When you create an object for a non-custom class, the full namespace name is required unless class is in the System namespace. Use only the properties of the class. -For example, the following command creates a session option object. +You can also use hash tables to create objects for non-custom classes. When +you create an object for a non-custom class, the full namespace name is +required unless class is in the System namespace. Use only the properties of +the class. +For example, the following command creates a session option object. +```powershell +[System.Management.Automation.Remoting.PSSessionOption]@{ + IdleTimeout=43200000 + SkipCnCheck=$True +} ``` -[System.Management.Automation.Remoting.PSSessionOption]@{IdleTimeout=43200000; SkipCnCheck=$True} -``` - -The requirements of the hash table feature, especially the null constructor requirement, eliminate many existing classes. However, most Windows PowerShell option classes are designed to work with this feature, as well as other very useful classes, such as the ScheduledJobTrigger class. +The requirements of the hash table feature, especially the null constructor +requirement, eliminate many existing classes. However, most PowerShell option +classes are designed to work with this feature, as well as other very useful +classes, such as the ScheduledJobTrigger class. +```powershell +[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{ + Frequency="Daily" + At="15:00" +} -``` -[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{Frequency="Daily";At="15:00"} - -Id Frequency Time DaysOfWeek Enabled --- --------- ---- ---------- ------- -0 Daily 6/6/2012 3:00:00 PM True +Id Frequency Time DaysOfWeek Enabled +-- --------- ---- ---------- ------- +0 Daily 6/6/2012 3:00:00 PM True ``` +You can also use the hash table feature when setting parameter values. For +example, the value of the **SessionOption** parameter of the New-PSSession +cmdlet and the value of the JobTrigger parameter of `Register-ScheduledJob` +can be a hash table. -You can also use the hash table feature when setting parameter values. For example, the value of the SessionOption parameter of the New-PSSession cmdlet and the value of the JobTrigger parameter of Register-ScheduledJob can be a hash table. - - -``` -New-PSSession -ComputerName Server01 -SessionOption @{IdleTimeout=43200000; SkipCnCheck=$True} -Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{Frequency="Daily";At="15:00"} +```powershell +New-PSSession -ComputerName Server01 -SessionOption @{ + IdleTimeout=43200000 + SkipCnCheck=$True +} +Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{ + Frequency="Daily" + At="15:00" +} ``` - - ### IMPORT-CSV -You can create custom objects from the items in a CSV file. When you use the Import-Csv cmdlet to import the CSV file, the cmdlet creates a custom object (PSCustomObject) for each item in the file. The column names are the object properties. -For example, if you import a CSV file of computer asset data, Import-CSV creates a collection of custom objects from the input. +You can create custom objects from the items in a CSV file. When you use the +`Import-Csv` cmdlet to import the CSV file, the cmdlet creates a custom object +(PSCustomObject) for each item in the file. The column names are the object +properties. +For example, if you import a CSV file of computer asset data, `Import-CSV` +creates a collection of custom objects from the input. ``` -#In Servers.csv -AssetID, Name, OS, Department -003, Server01, Windows Server 2012, IT -103, Server33, Windows 7, Marketing +#In Servers.csv +AssetID, Name, OS, Department +003, Server01, Windows Server 2012, IT +103, Server33, Windows 7, Marketing 212, Server35, Windows 8, Finance ``` +```powershell +PS C:\> $a = Import-Csv Servers.csv +PS C:\> $a - -``` -PS C:\> $a = Import-Csv Servers.csv -PS C:\> $a - -AssetID Name OS Department -------- ---- -- ---------- -003 Server01 Windows Server 2012 IT -103 Server33 Windows 7 Marketing +AssetID Name OS Department +------- ---- -- ---------- +003 Server01 Windows Server 2012 IT +103 Server33 Windows 7 Marketing 212 Server35 Windows 8 Finance ``` - Use the Get-Member cmdlet to confirm the object type. - -``` +```powershell PS C:\> $a | Get-Member ``` +```Output +TypeName: System.Management.Automation.PSCustomObject - -``` -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() -AssetID NoteProperty System.String AssetID=003 -Department NoteProperty System.String Department=IT -Name NoteProperty System.String Name=Server01 +Name MemberType Definition +---- ---------- ---------- +Equals Method bool Equals(System.Object obj) +GetHashCode Method int GetHashCode() +GetType Method type GetType() +ToString Method string ToString() +AssetID NoteProperty System.String AssetID=003 +Department NoteProperty System.String Department=IT +Name NoteProperty System.String Name=Server01 OS NoteProperty System.String OS=Windows Server 2012 ``` - You can use the custom objects just as you would standard objects. - -``` +```powershell PS C:\> $a | where {$_.OS -eq "Windows 8"} ``` - - -``` -AssetID Name OS Department -------- ---- -- ---------- +```output +AssetID Name OS Department +------- ---- -- ---------- 212 Server35 Windows 8 Finance ``` - For more information, see the help topic for the Import-Csv cmdlet. - ## SEE ALSO [about_Objects](about_Objects.md) @@ -243,9 +257,8 @@ For more information, see the help topic for the Import-Csv cmdlet. [about_Pipelines](about_Pipelines.md) -Get-Member - -Import-Csv +[Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) -New-Object +[Import-Csv](../../Microsoft.PowerShell.Utility/Import-Csv.md) +[New-Object](../../Microsoft.PowerShell.Utility/New-Object.md) diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Objects.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Objects.md index 88ab499af532..58308cabd6d7 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Objects.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Objects.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -58,20 +58,13 @@ directory objects are passed down the pipeline to the second command. The second command `where { $_.PsIsContainer -eq $false }` uses the PsIsContainer property of all file system objects to select only -files, which have a value of False ($false) in their PsIsContainer +files, which have a value of False (\$false) in their PsIsContainer property. Folders, which are containers and, thus, have a value of -True ($true) in their PsIsContainer property, are not selected. +True (\$true) in their PsIsContainer property, are not selected. The second command passes only the file objects to the third command `Format-List`, which displays the file objects in a list. -## For More Information - -Now that you understand a bit about objects, see the [about_Methods](about_Methods.md) -help topic to learn how to find and use object methods, the -[about_Properties](about_Properties.md) topic to learn how to find and use object properties, -and the [Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) topic, to learn how to find an object type. - ## See Also [about_Methods](about_Methods.md) diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md index 6e83191b889c..01d129ccc4bb 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -10,84 +10,85 @@ title: about_Operator_Precedence ## SHORT DESCRIPTION -Lists the Windows PowerShell operators in precedence order. +Lists the PowerShell operators in precedence order. -[This topic was contributed by Kirk Munro, a Windows PowerShell MVP +[This topic was contributed by Kirk Munro, a PowerShell MVP from Ottawa, Ontario] ## LONG DESCRIPTION -Windows PowerShell operators let you construct simple, but powerful -expressions. This topic lists the operators in precedence order. -Precedence order is the order in which Windows PowerShell evaluates -the operators when multiple operators appear in the same expression. - -When operators have equal precedence, Windows PowerShell evaluates -them from left to right. The exceptions are the assignment operators, -the cast operators, and the negation operators (!, -not, -bnot), -which are evaluated from right to left. - -You can use enclosures, such as parentheses, to override the -standard precedence order and force Windows PowerShell to evaluate -the enclosed part of an expression before an unenclosed part. - -In the following list, operators are listed in the order that they -are evaluated. Operators on the same line, or in the same group, have -equal precedence. - -The Operator column lists the operators. The Reference column lists -the Windows PowerShell Help topic in which the operator is described. -To display the topic, type `get-help `. - -|OPERATOR|REFERENCE| -|--------|---------| -|`$() @()`|[about_Operators](#index-operator)| -|`.` (dereference) `::` (static)|[about_Operators](about_Operators.md)| -|`[0]` (index operator)|[about_Operators](about_Operators.md)| +PowerShell operators let you construct simple, but powerful +expressions. This topic lists the operators in precedence order. Precedence +order is the order in which PowerShell evaluates the operators when +multiple operators appear in the same expression. + +When operators have equal precedence, PowerShell evaluates them from +left to right. The exceptions are the assignment operators, the cast +operators, and the negation operators (!, -not, -bnot), which are evaluated +from right to left. + +You can use enclosures, such as parentheses, to override the standard +precedence order and force PowerShell to evaluate the enclosed part of +an expression before an unenclosed part. + +In the following list, operators are listed in the order that they are +evaluated. Operators on the same line, or in the same group, have equal +precedence. + +The Operator column lists the operators. The Reference column lists the +PowerShell Help topic in which the operator is described. To display +the topic, type `get-help `. + +|OPERATOR |REFERENCE| +|------------------------|---------| +|`$() @()` |[about_Operators](#index-operator)| +|`.` (dereference) |[about_Operators](about_Operators.md)| +|`::` (static) |[about_Operators](about_Operators.md)| +|`[0]` (index operator) |[about_Operators](about_Operators.md)| |`[int]` (cast operators)|[about_Operators](about_Operators.md)| -|`-split` (unary)
`-join` (unary)|[about_Split](about_Split.md)
[about_Join](about_Join.md)| -|`,` (comma operator)|[about_Operators](about_Operators.md)| -|`++ --`|[about_Assignment_Operators](about_Assignment_Operators.md)| -|`-not`
`! -bNot`|[about_Logical_Operators](about_logical_operators.md)
[about_Comparison_Operators](about_Comparison_Operators.md)| -|`..` (range operator)|[about_Operators](about_Operators.md)| -|`-f` (format operator)|[about_Operators](about_Operators.md)| -|`* / %`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`+ -`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| - - -The following group of operators have equal precedence. Their -case-sensitive and explicitly case-insensitive variants have -the same precedence. - -|OPERATOR|REFERENCE| -|--------|---------| -|`-split` (unary)|[about_Split](about_Split.md)| -|`-join` (unary)|[about_Join](about_Join.md)| -|`-is -isnot -as`|[about_Type_Operators](about_Type_Operators.md)| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`,` (comma operator) |[about_Operators](about_Operators.md)| +|`++ --` |[about_Assignment_Operators](about_Assignment_Operators.md)| +|`-not` |[about_Logical_Operators](about_logical_operators.md)| +|`! -bNot` |[about_Comparison_Operators](about_Comparison_Operators.md)| +|`..` (range operator) |[about_Operators](about_Operators.md)| +|`-f` (format operator) |[about_Operators](about_Operators.md)| +|`* / % + -` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| + +The following group of operators have equal precedence. Their case-sensitive +and explicitly case-insensitive variants have the same precedence. + +|OPERATOR |REFERENCE| +|-------------------------|---------| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`-is -isnot -as` |[about_Type_Operators](about_Type_Operators.md)| |`-eq -ne -gt -gt -lt -le`|[about_Comparison_Operators](about_Comparison_Operators.md)| -|`-like -notlike`|[about_comparison_operators](about_comparison_operators.md)| -|`-match -notmatch`|[about_comparison_operators](about_comparison_operators.md)| -|`-in -notIn`|[about_comparison_operators](about_comparison_operators.md)| -|`-contains -notContains`|[about_comparison_operators](about_comparison_operators.md)| -|`-replace`|[about_comparison_operators](about_comparison_operators.md)| +|`-like -notlike` |[about_comparison_operators](about_comparison_operators.md)| +|`-match -notmatch` |[about_comparison_operators](about_comparison_operators.md)| +|`-in -notIn` |[about_comparison_operators](about_comparison_operators.md)| +|`-contains -notContains` |[about_comparison_operators](about_comparison_operators.md)| +|`-replace` |[about_comparison_operators](about_comparison_operators.md)| The list resumes here with the following operators in precedence order: -|OPERATOR|REFERENCE| -|--------|---------| -|`-band -bor -bxor`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`-and -or -xor`|[about_comparison_operators](about_comparison_operators.md)| -|`.` (dot-source)
`&` (call)|[about_Scopes](about_Scopes.md)
[about_Operators](about_Operators.md)| +|OPERATOR |REFERENCE| +|--------------------------|---------| +|`-band -bor -bxor` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| +|`-and -or -xor` |[about_comparison_operators](about_comparison_operators.md)| +|`.` (dot-source) |[about_Scopes](about_Scopes.md)| +|`&` (call) |[about_Operators](about_Operators.md)| || (pipeline operator)|[about_Operators](about_Operators.md)| -|`> >> 2> 2>> 2>&1`|[about_Redirection](about_Redirection.md)| -|`= += -= *= /= %=`|[about_Assignment_Operators](about_Assignment_Operators.md)| +|`> >> 2> 2>> 2>&1` |[about_Redirection](about_Redirection.md)| +|`= += -= *= /= %=` |[about_Assignment_Operators](about_Assignment_Operators.md)| # EXAMPLES -The following two commands show the arithmetic operators and -the effect of using parentheses to force Windows PowerShell to -evaluate the enclosed part of the expression first. +The following two commands show the arithmetic operators and the effect of +using parentheses to force PowerShell to evaluate the enclosed part of +the expression first. ```powershell C:\PS> 2 + 3 * 4 @@ -97,8 +98,8 @@ C:\PS> (2 + 3) * 4 20 ``` -The following example gets the read-only text files from the local -directory and saves them in the `$read_only` variable. +The following example gets the read-only text files from the local directory +and saves them in the `$read_only` variable. ```powershell $read_only = get-childitem *.txt | where-object {$_.isReadOnly} @@ -109,37 +110,37 @@ It is equivalent to the following example. $read_only = ( get-childitem *.txt | where-object {$_.isReadOnly} ) ``` -Because the pipeline operator (|) has a higher precedence than the -assignment operator (=), the files that the Get-ChildItem cmdlet -gets are sent to the Where-Object cmdlet for filtering before they -are assigned to the $read_only variable. +Because the pipeline operator (|) has a higher precedence than the assignment +operator (=), the files that the Get-ChildItem cmdlet gets are sent to the +Where-Object cmdlet for filtering before they are assigned to the $read_only +variable. -The following example demonstrates that the index operator takes -precedence over the cast operator. +The following example demonstrates that the index operator takes precedence +over the cast operator. -The first expression creates an array of three strings. Then, it -uses the index operator with a value of 0 to select the first object -in the array, which is the first string. Finally, it casts the -selected object as a string. In this case, the cast has no effect. +The first expression creates an array of three strings. Then, it uses the +index operator with a value of 0 to select the first object in the array, +which is the first string. Finally, it casts the selected object as a string. +In this case, the cast has no effect. ```powershell C:\PS> [string]@('Windows','PowerShell','2.0')[0] Windows ``` -The second expression uses parentheses to force the cast operation -to occur before the index selection. As a result, the entire array -is cast as a (single) string. Then, the index operator selects -the first item in the string array, which is the first character. +The second expression uses parentheses to force the cast operation to occur +before the index selection. As a result, the entire array is cast as a +(single) string. Then, the index operator selects the first item in the string +array, which is the first character. ```powershell C:\PS> ([string]@('Windows','PowerShell','2.0'))[0] W ``` -In the following example, because the -gt (greater-than) operator -has a higher precedence than the -and (logical AND) operator, the -result of the expression is FALSE. +In the following example, because the -gt (greater-than) operator has a higher +precedence than the -and (logical AND) operator, the result of the expression +is FALSE. ```powershell C:\PS> 2 -gt 4 -and 1 @@ -160,11 +161,11 @@ C:\PS> 2 -gt (4 -and 1) True ``` -However, this example demonstrates an important principle of managing -operator precedence. When an expression is difficult for people to -interpret, use parentheses to force the evaluation order, even when it -forces the default operator precedence. The parentheses make your -intentions clear to people who are reading and maintaining your scripts. +However, this example demonstrates an important principle of managing operator +precedence. When an expression is difficult for people to interpret, use +parentheses to force the evaluation order, even when it forces the default +operator precedence. The parentheses make your intentions clear to people who +are reading and maintaining your scripts. ## SEE ALSO @@ -185,4 +186,3 @@ intentions clear to people who are reading and maintaining your scripts. [about_Split](about_Split.md) [about_Type_Operators](about_Type_Operators.md) - diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md index d2fc74e0c5c4..e9c4ebaefa98 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,449 +7,409 @@ title: about_Parameters_Default_Values --- # About Parameters Default Values -## about_Parameters_Default_Values - ## SHORT DESCRIPTION -Describes how to set custom default values for the parameters of cmdlets and advanced functions. +Describes how to set custom default values for the parameters of cmdlets and +advanced functions. ## LONG DESCRIPTION -The $PSDefaultParameterValues preference variable lets you specify custom default values for any cmdlet or advanced function. Cmdlets and functions use the custom default value unless you specify another value in the command. -The authors of cmdlets and advanced functions set standard default values for their parameters. Typically, the standard default values are useful, but they might not be appropriate for all environments. +The \$PSDefaultParameterValues preference variable lets you specify custom +default values for any cmdlet or advanced function. Cmdlets and functions use +the custom default value unless you specify another value in the command. + +The authors of cmdlets and advanced functions set standard default values for +their parameters. Typically, the standard default values are useful, but they +might not be appropriate for all environments. -This feature is especially useful when you must specify the same alternate parameter value nearly every time you use the command or when a particular parameter value is difficult to remember, such as an e-mail server name or project GUID. +This feature is especially useful when you must specify the same alternate +parameter value nearly every time you use the command or when a particular +parameter value is difficult to remember, such as an e-mail server name or +project GUID. -If the desired default value varies predictably, you can specify a script block that provides different default values for a parameter under different conditions. +If the desired default value varies predictably, you can specify a script +block that provides different default values for a parameter under different +conditions. -$PSDefaultParameterValues was introduced in Windows PowerShell?3.0. +\$PSDefaultParameterValues was introduced in PowerShell 3.0. +## SYNTAX -### SYNTAX The syntax of the $PSDefaultParameterValues preference variable is as follows: +```powershell +$PSDefaultParameterValues=@{":"=""} + +$PSDefaultParameterValues=@{":"={}} -``` -$PSDefaultParameterValues=@{":"=""} - -$PSDefaultParameterValues=@{":"={}} - $PSDefaultParameterValues["Disabled"]=$true | $false ``` - Wildcard characters are permitted in the CmdletName and ParameterName values. -The value of $PSDefaultParameterValues is a System.Management.Automation.DefaultParameterDictionary, a type of hash table that validates the format of keys. Enter a hash table where the key consists of the cmdlet name and parameter name separated by a colon (:) and the value is the custom default value. - -To set, change, add, or remove entries from $PSDefaultParameterValues, use the methods that you would use to edit a standard hash table. +The value of \$PSDefaultParameterValues is a +System.Management.Automation.DefaultParameterDictionary, a type of hash table +that validates the format of keys. Enter a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (:) and the value +is the custom default value. -The must be the name of a cmdlet or the name of an advanced function that uses the CmdletBinding attribute. You cannot use $PSDefaultParameterValues to specify default values for scripts or simple functions. +To set, change, add, or remove entries from \$PSDefaultParameterValues, use the +methods that you would use to edit a standard hash table. -The default value can be an object or a script block. If the value is a script block, Windows PowerShell evaluates the script block and uses the result as the parameter value. When the specified parameter takes a script block value, enclose the script block value in a second set of braces, such as: +The \ must be the name of a cmdlet or the name of an advanced +function that uses the CmdletBinding attribute. You cannot use +$PSDefaultParameterValues to specify default values for scripts or simple +functions. +The default value can be an object or a script block. If the value is a script +block, PowerShell evaluates the script block and uses the result as the +parameter value. When the specified parameter takes a script block value, +enclose the script block value in a second set of braces, such as: -``` +```powershell $PSDefaultParameterValues=@{ "Invoke-Command:ScriptBlock"={{Get-Process}} } ``` +For information about hash tables, see +[about_Hash_Tables](about_Hash_Tables.md). For information about script +blocks, see [about_Script_Blocks](about_Script_Blocks.md). For information +about preference variables, see +[about_Preference_Variables](about_Preference_Variables.md). -For information about hash tables, see about_Hash_Tables. For information about script blocks, see about_Script_Blocks. For information about preference variables, see about_Preference_Variables. - +## EXAMPLES -### EXAMPLES -The following command sets a custom default value for the SmtpServer parameter of the Send-MailMessage cmdlet. +The following command sets a custom default value for the SmtpServer parameter +of the Send-MailMessage cmdlet. - -``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"} +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" +} ``` +To set default values for multiple parameters, use a semi-colon (;) to +separate each Name\=Value pair. The following command adds a custom default +value for the LogName parameter of the `Get-WinEvent` cmdlet. -To set default values for multiple parameters, use a semi-colon (;) to separate each Name\=Value pair. The following command adds a custom default value for the LogName parameter of the Get-WinEvent cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5"; + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" +} ``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"} -``` - -You can use wildcard characters in the name of the cmdlet and parameter. The following command sets the Verbose common parameter to $true in all commands. Use $true and $false to set values for switch parameters, such as Verbose. +You can use wildcard characters in the name of the cmdlet and parameter. The +following command sets the Verbose common parameter to \$true in all commands. +Use \$true and \$false to set values for switch parameters, such as +**Verbose**. - -``` +```powershell $PSDefaultParameterValues = @{"*:Verbose"=$true} ``` +If a parameter takes multiple values (an array), you can set multiple values +as the default value. The following command sets the default value of the +**ComputerName** parameter of the Invoke-Command cmdlet to "Server01" and +"Server02". -If a parameter takes multiple values (an array), you can set multiple values as the default value. The following command sets the default value of the ComputerName parameter of the Invoke-Command cmdlet to "Server01" and "Server02". - - -``` -$PSDefaultParameterValues = @{"Invoke-Command:ComputerName"="Server01","Server02"} -``` - - -You can use a script block to specify different default values for a parameter under different conditions. Windows PowerShell evaluates the script block and uses the result as the default parameter value. - -The following command sets the default value of the Autosize parameter of the Format-Table cmdlet to $true when the host program is the Windows PowerShell console. - - -``` -$PSDefaultParameterValues=@{"Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}}} -``` - - -If a parameter takes a script block value, enclose the script block in an extra set of braces. When Windows PowerShell evaluates the outer script block, the result is the inner script block, which is set as the default parameter value. - -The following command sets the default value of the ScriptBlock parameter of Invoke-Command. Because the script block is enclosed in a second set of braces, the enclosed script block is passed to the Invoke-Command cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Invoke-Command:ComputerName"="Server01","Server02" +} ``` -$PSDefaultParameterValues=@{"Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}}} -``` - - - -### HOW TO SET $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. - -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues +You can use a script block to specify different default values for a parameter +under different conditions. PowerShell evaluates the script block and uses the +result as the default parameter value. -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. +The following command sets the default value of the Autosize parameter of the +Format-Table cmdlet to \$true when the host program is the PowerShell console. - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +$PSDefaultParameterValues=@{ + "Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}} +} ``` +If a parameter takes a script block value, enclose the script block in an +extra set of braces. When PowerShell evaluates the outer script block, the +result is the inner script block, which is set as the default parameter value. +The following command sets the default value of the ScriptBlock parameter of +`Invoke-Command`. Because the script block is enclosed in a second set of +braces, the enclosed script block is passed to the `Invoke-Command` cmdlet. -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational -Get*:Verbose True +```powershell +$PSDefaultParameterValues=@{ + "Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}} +} ``` +### HOW TO SET \$PSDefaultParameterValues -To get the value of a key, use the following command syntax: +\$PSDefaultParameterValues is a preference variable, so it exists only in the +session in which it is set. It has no default value. +To set \$PSDefaultParameterValues, type the variable name and one or more +key-value pairs at the command line. -``` -$PSDefaultParameterValues[""] -``` +If you type another \$PSDefaultParameterValues command, its value replaces the +original value. The original is not retained. +To save \$PSDefaultParameterValues for future sessions, add a +\$PSDefaultParameterValues command to your PowerShell profile. For more +information, see [about_Profiles](about_Profiles.md). -For example: +### HOW TO GET \$PSDefaultParameterValues +To get the value of \$PSDefaultParameterValues, at the command prompt, type: +```powershell +$PSDefaultParameterValues ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] -Server01AB234x5 -``` - - - -### HOW TO ADD VALUES TO $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. +For example, the first command sets the value of \$PSDefaultParameterValues. +The second command gets the value of \$PSDefaultParameterValues. -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues - -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. - - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +PS C:\> $PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" + "Get-*:Verbose"=$true +} ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To get the value of a \ key, use the following +command syntax: -To get the value of a key, use the following command syntax: - - -``` +```powershell $PSDefaultParameterValues[""] ``` - For example: - -``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] +```powershell +PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] Server01AB234x5 ``` +### HOW TO ADD VALUES TO PSDefaultParameterValues +To add or remove values from \$PSDefaultParameterValues, use the methods that +you would use for a standard hash table. -### HOW TO ADD VALUES TO $PSDefaultParameterValues -To add or remove values from $PSDefaultParameterValues, use the methods that you would use for a standard hash table. - -For example, to add a value to $PSDefaultParameterValues without affecting the existing values, use the Add method of hash tables. +For example, to add a value to \$PSDefaultParameterValues without affecting the +existing values, use the Add method of hash tables. The syntax of the Add method is as follows: - ``` .Add(Key, Value) ``` +where the Key is ":" and the value is the parameter +value. -where the Key is ":" and the value is the parameter value. - -Use the following command format to call the Add method on $PSDefaultParameterValues. Be sure to use a comma (,) to separate the key from the value, instead of the equal sign (\=). - +Use the following command format to call the Add method on +\$PSDefaultParameterValues. Be sure to use a comma (,) to separate the key +from the value, instead of the equal sign (\=). +```powershell +$PSDefaultParameterValues.Add( + ":", "" +) ``` -$PSDefaultParameterValues.Add(":", "") -``` - -For example, the following command adds "PowerShell" as the default value of the Name parameter of the Get-Process cmdlet. +For example, the following command adds "PowerShell" as the default value of +the Name parameter of the Get-Process cmdlet. - -``` +```powershell $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO REMOVE VALUES FROM \$PSDefaultParameterValues - -### HOW TO REMOVE VALUES FROM $PSDefaultParameterValues -To remove a value from $PSDefaultParameterValues, use the Remove method of hash tables. +To remove a value from \$PSDefaultParameterValues, use the Remove method of +hash tables. The syntax of the Remove method is as follows: - -``` +```powershell .Remove(Key) ``` +Use the following command format to call the Remove method on +\$PSDefaultParameterValues. -Use the following command format to call the Remove method on $PSDefaultParameterValues. - - -``` +```powershell $PSDefaultParameterValues.Remove(":") ``` +For example, the following command removes the Name parameter of the +`Get-Process` cmdlet and its values. -For example, the following command removes the Name parameter of the Get-Process cmdlet and its values. - - -``` +```powershell $PSDefaultParameterValues.Remove("Get-Process:Name") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Remove("Get-Process:Name") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO CHANGE VALUES IN \$PSDefaultParameterValues +To change a value in $PSDefaultParameterValues, use the following command +format. -### HOW TO CHANGE VALUES IN $PSDefaultParameterValues -To change a value in $PSDefaultParameterValues, use the following command format. - - -``` +```powershell $PSDefaultParameterValues["CmdletName:ParameterName"]="" ``` - The following example shows the effect of this command. +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - +```powershell +$PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" -``` - +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO DISABLE AND RE-ENABLE \$PSDefaultParameterValues +You can temporarily disable and then re-enable \$PSDefaultParameterValues. This +is very useful if you're running scripts that might assume different default +parameter values. -### HOW TO DISABLE AND RE-ENABLE $PSDefaultParameterValues -You can temporarily disable and then re-enable $PSDefaultParameterValues. This is very useful if you're running scripts that might assume different default parameter values. - -To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of $True. +To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of +\$True. For example, - -``` +```powershell $PSDefaultParameterValues.Add("Disabled", $true) ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$true ``` +The other values in \$PSDefaultParameterValues are preserved, but not +effective. -The other values in $PSDefaultParameterValues are preserved, but not effective. - +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Disabled True -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Disabled True +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To re-enable \$PSDefaultParameterValues, remove the Disabled key or change the +value of the Disabled key to \$False. -To re-enable $PSDefaultParameterValues, remove the Disabled key or change the value of the Disabled key to $False. - - -``` +```powershell $PSDefaultParameterValues.Remove("Disabled") ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$false ``` - -The previous value of $PSDefaultParameterValues is effective again. - +The previous value of \$PSDefaultParameterValues is effective again. ## KEYWORDS + about_PSDefaultParameterValues about_Parameters_DefaultValues about_DefaultValues - ## SEE ALSO [about_Hash_Tables](about_Hash_Tables.md) @@ -459,4 +419,3 @@ about_DefaultValues [about_Profiles](about_Profiles.md) [about_Script_Blocks](about_Script_Blocks.md) - diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Prompts.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Prompts.md index 22a263dff4f8..6f1820bea646 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Prompts.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Prompts.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,308 +7,284 @@ title: about_Prompts --- # About Prompts -## about_Prompts - ## SHORT DESCRIPTION -Describes the Prompt function and demonstrates how to create a custom Prompt function. +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: +The PowerShell command prompt indicates that PowerShell is ready to run a +command: ``` PS C:\> ``` +The PowerShell prompt is determined by the built-in Prompt function. You can +customize the prompt by creating your own Prompt function and saving it in +your PowerShell profile. -The Windows PowerShell prompt is determined by the built-in Prompt function. You can customize the prompt by creating your own Prompt function and saving it in your Windows PowerShell profile. - +## ABOUT THE PROMPT FUNCTION -### ABOUT 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 determines the appearance of the PowerShell prompt. +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: - -``` +```powershell function Prompt { } ``` +The Prompt function must return an object. As a best practice, return a string +or an object that is formatted as a string. The maximum recommended length is +80 characters. -The Prompt function must return an object. As a best practice, return a string or an object that is formatted as a string. The maximum recommended length is 80 characters. - -For example, the following prompt function returns a "Hello, World" string followed by a caret (>). +For example, the following prompt function returns a "Hello, World" string +followed by a caret (>). - -``` -PS C:\> function prompt {"Hello, World > "} +```powershell +PS C:\> function prompt {"Hello, World > "} Hello, World > ``` - - ### GETTING THE PROMPT FUNCTION -To get the Prompt function, use the Get-Command cmdlet or use the Get-Item cmdlet in the Function drive. -Functions are commands. So, you can use the Get-Command cmdlet to get functions, including the Prompt function. +To get the Prompt function, use the `Get-Command` cmdlet or use the `Get-Item` +cmdlet in the Function drive. For example: +```powershell +PS C:\> Get-Command Prompt -``` -PS C:\> Get-Command Prompt - -CommandType Name ModuleName ------------ ---- ---------- +CommandType Name ModuleName +----------- ---- ---------- Function prompt ``` - -To get the script that sets the value of the prompt, use the dot method to get the ScriptBlock property of the Prompt function. +To get the script that sets the value of the prompt, use the dot method to get +the ScriptBlock property of the Prompt function. For example: +```powershell +PS C:\> (Get-Command Prompt).ScriptBlock -``` -PS C:\> (Get-Command Prompt).ScriptBlock - -"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -# .Link -# http://go.microsoft.com/fwlink/?LinkID=225750 +"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPr +omptLevel + 1)) " +# .Link +# http://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml ``` +Like all functions, the Prompt function is stored in the Function: drive. To +display the script that creates the current Prompt function, type: -Like all functions, the Prompt function is stored in the Function: drive. To display the script that creates the current Prompt function, type: - - -``` +```powershell (Get-Item function:prompt).ScriptBlock ``` - ### THE DEFAULT PROMPT -The default prompt appears only when the Prompt function generates an error or does not return an object. -The default Windows PowerShell prompt is: +The default prompt appears only when the Prompt function generates an error or +does not return an object. +The default PowerShell prompt is: ``` PS> ``` +For example, the following command sets the Prompt function to $null, which is +invalid. As a result, the default prompt appears. -For example, the following command sets the Prompt function to $null, which is invalid. As a result, the default prompt appears. - - -``` -PS C:\> function prompt {$null} +```powershell +PS C:\> function prompt {$null} PS> ``` - -Because Windows PowerShell comes with a built-in prompt, you usually do not see the default prompt. - +Because PowerShell comes with a built-in prompt, you usually do not see the +default prompt. ### BUILT-IN PROMPT -Windows PowerShell includes a built-in prompt function. - -In Windows PowerShell 3.0, the built-in prompt function is: - - -``` -function prompt -{ - "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -} -``` - -This simplified prompt starts with "PS" followed by the current location, and one ">" for each nested prompt level. +PowerShell includes a built-in prompt function. -In Windows PowerShell 2.0, the built-in prompt function is: - - -``` -function prompt -{ - $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } - else { '' }) + 'PS ' + $(Get-Location) ` - + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' +```powershell +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: -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: - - -``` +```Output [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 (>). -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: -``` -For example: - PS C:\ps-test> +```Output +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.) -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: -For example, when you are debugging in a nested prompt, the prompt resembles the following prompt: - - -``` +```Output [DBG] PS C:\ps-test>>> ``` - - ### CHANGES TO THE PROMPT -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: +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 +```Output +PS Hello, World> Enter-PSSession Server01 [Server01]: PS Hello, World> ``` +Other PowerShell host applications and alternate shells might have their own +custom command prompts. -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. - +For more information about the \$PSDebugContext and $NestedPromptLevel +automatic variables, see [about_Automatic_Variables](about_Automatic_Variables.md). ### HOW TO CUSTOMIZE 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: +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: -``` +```powershell function prompt { } ``` - -Then, between the braces, enter the commands or the string that creates your prompt. +Then, between the braces, enter the commands or the string that creates your +prompt. For example, the following prompt includes your computer name: - -``` +```powershell function prompt {"PS [$env:COMPUTERNAME]> "} ``` - On the Server01 computer, the prompt resembles the following prompt: - -``` +```Output PS [Server01] > ``` - The following prompt function includes the current date and time: - -``` +```powershell function prompt {"$(get-date)> "} ``` - The prompt resembles the following prompt: - -``` +```Output 03/15/2012 17:49:47> ``` - You can also change the default Prompt function: -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) { '>>' }) + '> ' +For example, the following modified Prompt function adds "[ADMIN]:" to the +built-in PowerShell prompt when PowerShell is opened by using the "Run as +administrator" option: + +```powershell +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 PowerShell by using the "Run as administrator" option, a prompt +that resembles the following prompt appears: -When you start Windows PowerShell by using the "Run as administrator" option, a prompt that resembles the following prompt appears: - - -``` +```Output [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. -The following Prompt function displays the history ID of the next command. To view the command history, use the Get-History cmdlet. - +```powershell +function prompt { + # The at sign creates an array in case only one history item exists. + $history = @(get-history) + if($history.Count -gt 0) + { + $lastItem = $history[$history.Count - 1] + $lastId = $lastItem.Id + } -``` -function prompt -{ - # The at sign creates an array in case only one history item exists. - $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 >" + $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, PowerShell uses the default prompt, "PS>". -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 -ForegroundColor $Color - return " " +```powershell +function prompt { + $color = Get-Random -Min 1 -Max 16 + Write-Host ("PS " + $(Get-Location) +">") -NoNewLine ` + -ForegroundColor $Color + return " " } ``` - - ### SAVING THE PROMPT FUNCTION -Like any function, the Prompt function exists 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. +Like any function, the Prompt function exists only in the current session. To +save the Prompt function for future sessions, add it to your PowerShell +profiles. For more information about profiles, see about_Profiles. ## SEE ALSO -Get-Location +[Get-Location](../../Microsoft.PowerShell.Management/Get-Location.md) -Enter-PSSession +[Enter-PSSession](../Enter-PSSession.md) -Get-History +[Get-History](../Get-History.md) -Get-Random +[Get-Random](../../Microsoft.PowerShell.Utility/Get-Random.md) -Write-Host +[Write-Host](../../Microsoft.PowerShell.Utility/Write-Host.md) [about_Profiles](about_Profiles.md) diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md index af9999f5f30a..7933f7f0a80e 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_packagemanagement.md @@ -1,93 +1,87 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet -title: about_packagemanagement +title: about_PackageManagement --- # About PackageManagement -## about_PackageManagement -# TOPIC -about_PackageManagement - -# SHORT DESCRIPTION +## SHORT DESCRIPTION PackageManagement is an aggregator for software package managers. -# LONG DESCRIPTION +## LONG DESCRIPTION PackageManagement functionality was introduced in Windows PowerShell 5.0. -PackageManagement is a unified interface for software package management systems; you -can run PackageManagement cmdlets to perform software discovery, installation, and -inventory (SDII) tasks. Regardless of the underlying installation technology, -you can run the common cmdlets in the PackageManagement module to search for, -install, or uninstall packages; add, remove, and query package repositories; and -run queries on a computer to determine which software packages are installed. - -PackageManagement supports a flexible plug-in model that enables support for other -software package management systems. - -The PackageManagement module is included with Windows PowerShell 5.0 and later releases -of Windows PowerShell, and works on three levels of package management -structure: package providers, package sources, and the packages themselves. - -Term Description ----------- ------------------------------ -Package manager Software package management system. In -PackageManagement terms, this is a package provider. -Package provider PackageManagement term for a package manager. Examples -can include Windows Installer, Chocolatey, -and others. -Package source A URL, local folder, or network shared folder that -you configure package providers to use as a -repository. -Package A piece of software that a package provider manages, -and that is stored in a specific package source. - -The PackageManagement module includes the following cmdlets. You can find the -Help for these cmdlets on TechNet starting on the following page: -http://technet.microsoft.com/library/dn890951(v=wps.640).aspx. - -Cmdlet Description ----------- ------------------------------ -Get-PackageProvider Returns a list of package providers that are -connected to PackageManagement. -Get-PackageSource Gets a list of package sources that are -registered for a package provider. -Register-PackageSource Adds a package source for a specified -package provider. -Set-PackageSource Sets properties on an existing package -source. -Unregister-PackageSource Removes a registered package source. -Get-Package Returns a list of installed software -packages. -Find-Package Finds software packages in available -package sources. -Install-Package Installs one or more software packages. -Save-Package Saves packages to the local computer -without installing them. -Uninstall-Package Uninstalls one or more software packages. - -PackageManagement Package Provider Bootstrapping and Dynamic Cmdlet Parameters - -By default, PackageManagement ships with a core bootstrap provider. You can install -additional package providers as you need them by bootstrapping the providers; -that is, responding to a prompt to install the provider automatically, from a -web service. You can specify a package provider with any PackageManagement cmdlet; -if the specified provider is not available, PackageManagement prompts you to bootstrap ---or automatically install--the provider. In the following examples, if the -Chocolatey provider is not already installed, PackageManagement bootstrapping installs -the provider. - +PackageManagement is a unified interface for software package management +systems; you can run PackageManagement cmdlets to perform software discovery, +installation, and inventory (SDII) tasks. Regardless of the underlying +installation technology, you can run the common cmdlets in the +PackageManagement module to search for, install, or uninstall packages; add, +remove, and query package repositories; and run queries on a computer to +determine which software packages are installed. + +PackageManagement supports a flexible plug-in model that enables support for +other software package management systems. + +The PackageManagement module is included with Windows PowerShell 5.0 and later +releases of Windows PowerShell, and works on three levels of package +management structure: package providers, package sources, and the packages +themselves. Let us define some terms: + +- Package manager: Software package management system. In PackageManagement + terms, this is a package provider. +- Package provider: PackageManagement term for a package manager. Examples can + include Windows Installer, Chocolatey, and others. +- Package source: A URL, local folder, or network shared folder that you + configure package providers to use as a repository. +- Package: A piece of software that a package provider manages, and that is + stored in a specific package source. + +The PackageManagement module includes the following cmdlets. For more +information, see the +[PackageManagement](/powershell/gallery/psget/oneget/packagemanagement_cmdlets) +help. + +- `Get-PackageProvider`: Returns a list of package providers that are + connected to PackageManagement. +- `Get-PackageSource`: Gets a list of package sources that are registered for + a package provider. +- `Register-PackageSource`: Adds a package source for a specified package + provider. +- `Set-PackageSource`: Sets properties on an existing package source. +- `Unregister-PackageSource`: Removes a registered package source. +- `Get-Package`: Returns a list of installed software packages. +- `Find-Package`: Finds software packages in available package sources. +- `Install-Package`: Installs one or more software packages. +- `Save-Package`: Saves packages to the local computer without installing + them. +- `Uninstall-Package`: Uninstalls one or more software packages. + +### Package Provider Bootstrapping and Dynamic Cmdlet Parameters + +By default, PackageManagement ships with a core bootstrap provider. You can +install additional package providers as you need them by bootstrapping the +providers; that is, responding to a prompt to install the provider +automatically, from a web service. You can specify a package provider with any +PackageManagement cmdlet; if the specified provider is not available, +PackageManagement prompts you to bootstrap (or automatically install) the +provider. In the following examples, if the Chocolatey provider is not already +installed, PackageManagement bootstrapping installs the provider. + +```powershell Find-Package -Provider Chocolatey +``` If the Chocolatey provider is not already installed, when you run the preceding command, you are prompted to install it. +```powershell Install-Package -ForceBootstrap +``` If the Chocolatey provider is not already installed, when you run the preceding command, the provider is installed; but because the ForceBootstrap @@ -99,10 +93,10 @@ provider installed, and you do not add the ForceBootstrap parameter to your command, PackageManagement prompts you to install the provider. Specifying a package provider in your PackageManagement command can make -dynamic parameters available that are specific to that package provider. -When you run Get-Help for a specific PackageManagement cmdlet, a list of -parameter sets are returned, grouping dynamic parameters for available -package providers in separate parameter sets. +dynamic parameters available that are specific to that package provider. When +you run Get-Help for a specific PackageManagement cmdlet, a list of parameter +sets are returned, grouping dynamic parameters for available package providers +in separate parameter sets. More Information About the PackageManagement Project @@ -131,4 +125,3 @@ Install-Package Save-Package Uninstall-Package - diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_pipelines.md index 1ae1a64986f8..97cd9535c505 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,41 +7,39 @@ title: about_pipelines --- # About Pipelines -## about_Pipelines - - ### Short Description -Combining commands into pipelines in the Windows PowerShell +Combining commands into pipelines in the 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. +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 powerful -command chain or "pipeline" that is comprised of a series of simple commands. +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 powerful command +chain or "pipeline" that is comprised of a series of simple commands. For example, + ```powershell 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` processes -the objects and send them down the pipeline. Because there are no more commands in -the pipeline, the results are displayed at the console. +`Command-2` processes the objects and sends them to `Command-3`. `Command-3` +processes the objects and send them down the pipeline. Because there are no +more commands 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. +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. +Here is a simple example. The following command gets the Notepad process and +then stops it. For example, ```powershell @@ -49,77 +47,69 @@ 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 object -to the `Stop-Process` cmdlet, which stops the Notepad process. Notice that the -`Stop-Process` command does not have a Name or ID parameter to specify the process, -because the specified process is submitted through the pipeline. +the Notepad process. It uses a pipeline operator (`|`) to send the process +object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice +that the `Stop-Process` command does not have a Name or ID parameter to +specify the process, because the specified process is submitted through the +pipeline. Here is a practical example. This command pipeline gets the text files in the -current directory, selects only the files that are more than 10,000 bytes long, -sorts them by length, and displays the name and length of each file in a table. +current directory, selects only the files that are more than 10,000 bytes +long, sorts them by length, and displays the name and length of each file in a +table. ```powershell 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 command -is written horizontally, but we will show the process vertically in the following -graphic. +This pipeline is comprised of four commands in the specified order. The +command is written horizontally, but we will show the process vertically in +the following graphic. `Get-ChildItem` `-Path` *.txt - **|** - -| (FileInfo objects ) -| ( .txt ) - - **|** - - **V** +``` +| +| (FileInfo objects for *.txt) +| +V +``` `Where-Object` {$_.length `-gt` 10000} - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| +V +``` `Sort-Object` `-Property` Length - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) -| ( Sorted by length ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.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** - ``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| ( Sorted by length ) +| ( Formatted in a table ) +| +V +``` + +```output Name Length ---- ------ tmp1.txt 82920 @@ -129,13 +119,13 @@ tmp3.txt 114000 ### Using Pipelines +The PowerShell cmdlets were designed to be used in pipelines. For example, 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. -The Windows PowerShell cmdlets were designed to be used in pipelines. For example, -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 `Start-Service` -or `Stop-Service` cmdlets (although disabled services cannot be restarted in this way). +For example, you can pipe any service from the `Get-Service` cmdlet to the +`Start-Service` or `Stop-Service` cmdlets (although disabled services cannot +be restarted in this way). This command pipeline starts the WMI service on the computer: @@ -144,90 +134,98 @@ For example, Get-Service wmi | Start-Service ``` -The cmdlets that get and set objects of the Windows PowerShell providers, such as the +The cmdlets that get and set objects of the PowerShell providers, such 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` command in the -Windows PowerShell registry provider to the `New-ItemProperty` cmdlet. This command adds -a new registry entry, NoOfEmployees, with a value of 8124, to the MyCompany registry key. +For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` +command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. +This command adds a new registry entry, NoOfEmployees, with a value of 8124, +to the MyCompany registry key. For example, ```powershell -Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 +Get-Item -Path HKLM:\Software\MyCompany | + New-ItemProperty -Name NoOfEmployees -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 any objects to -these cmdlets. +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 any 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. +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. For example, + ```powershell Get-Process | Sort-Object -Property handles ``` -Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and -`Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out -cmdlets, such as `Out-Printer`. +Also, you can pipe any objects to the formatting cmdlets, such as +`Format-List` 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. +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. For example, + ```powershell Get-Process winlogon | Format-List -Property * ``` -With a bit of practice, you'll find that combining simple commands into pipelines -saves time and typing, and makes your scripting more efficient. +With a bit of practice, you'll find that combining simple commands into +pipelines 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 command +to another command, PowerShell tries to associate the piped objects with one +of the parameters of the receiving cmdlet. -When you "pipe" objects, that is send the objects in the output of one command 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 associates input objects -with cmdlet parameters, tries to find a parameter that meets the following criteria: +To do so, the PowerShell "parameter binding" component, which associates 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 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 `-InputObject` 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`. +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 `-InputObject` 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 PowerShell prompts you -for the missing parameter values. +If the parameter binding component of PowerShell cannot associate the piped +objects with a parameter of the receiving cmdlet, the command fails and +PowerShell prompts you for the missing parameter values. -You cannot force the parameter binding component to associate the piped objects with a particular -parameter -- you cannot even suggest a parameter. Instead, the logic of the component manages -the piping as efficiently as possible. +You cannot force the parameter binding component to associate the piped +objects with a particular parameter. You cannot even suggest a parameter. +Instead, the logic of the 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. -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: +For example, piping objects representing the services on the computer to a +`Format-Table` command, such as: ```powershell Get-Service | Format-Table -Property name, dependentservices ``` -is much like saving the service objects in a variable and using the InputObject parameter -of `Format-Table` to submit the service object. +is much like saving the service objects in a variable and using the +InputObject parameter of `Format-Table` to submit the service object. For example, + ```powershell $services = Get-Service Format-Table -InputObject $services -Property name, dependentservices @@ -236,51 +234,58 @@ Format-Table -InputObject $services -Property name, dependentservices or imbedding the command in the parameter value For example, + ```powershell -Format-Table -InputObject (Get-Service wmi) -Property name, dependentservices +Format-Table -InputObject (Get-Service wmi) -Property name,dependentservices ``` -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 you use a -command parameter, the objects are sent as a single array object. +However, there is an important difference. When you pipe multiple objects to a +command, PowerShell sends the objects to the command one at a time. When you +use a command parameter, the objects are sent as a single array object. + +This seemingly technical difference can have interesting, and sometimes +useful, consequences. -This seemingly technical difference can have interesting, and sometimes useful, consequences. +For example, if you pipe multiple process objects from the `Get-Process` +cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one +at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the +process objects, and their properties and methods. -For example, if you pipe multiple process objects from the `Get-Process` cmdlet 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 their properties and methods. -(`Get-Member` eliminates duplicates, so if the objects are all of the same type, it displays only -one object type.) +NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the +same type, it displays only one object type. -In this case, `Get-Member` displays the properties and methods of each process object, that is, a -System.Diagnostics.Process object. +In this case, `Get-Member` displays the properties and methods of each process +object, that is, a System.Diagnostics.Process object. For example, + ```powershell Get-Process | Get-Member ``` -``` +```Output TypeName: System.Diagnostics.Process -Name MemberType Definition ----- ---------- ---------- -Handles AliasProperty Handles = Handlecount -Name AliasProperty Name = ProcessName -NPM AliasProperty NPM = NonpagedSystemMemorySize +Name MemberType Definition +---- ---------- ---------- +Handles AliasProperty Handles = Handlecount +Name AliasProperty Name = ProcessName +NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then `Get-Member` receives an -array of System.Diagnostics.Process objects as a single unit, and it displays the properties -of an array of objects. (Note the array symbol ([]) after the System.Object type name.) +However, if you use the InputObject parameter of `Get-Member`, then +`Get-Member` receives an array of System.Diagnostics.Process objects as a +single unit, and it displays the properties of an array of objects. (Note the +array symbol ([]) after the System.Object type name.) For example, + ```powershell Get-Member -InputObject (Get-Process) ``` -``` +```Output TypeName: System.Object[] Name MemberType Definition @@ -291,30 +296,32 @@ Clone Method System.Object Clone() ... ``` -This result might not be what you intended, but after you understand it, you 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. +This result might not be what you intended, but after you understand it, you +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. For example, + ```powershell (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. +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** or **Parameter** -parameters to determine which, if any, of a cmdlet's parameters 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** or **Parameter** parameters to determine which, if any, of a +cmdlet's parameters accepts pipeline input. -In the `Get-Help` default display, the "Accept 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. +In the `Get-Help` default display, the "Accept 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` cmdlet accepts -pipeline input, type: +For example, to determine which of the parameters of the `Start-Service` +cmdlet accepts pipeline input, type: ```powershell Get-Help Start-Service -Full @@ -326,108 +333,115 @@ or Get-Help Start-Service -Parameter * ``` -For example, the help for the `Start-Service` cmdlet shows that the **InputObject** and **Name** -parameters accept pipeline input ("true"). All other parameters have a value of "false" -in the "Accept pipeline input?" row. +For example, the help for the `Start-Service` cmdlet shows that the +**InputObject** and **Name** parameters accept pipeline input ("true"). All +other parameters have a value of "false" in the "Accept pipeline input?" row. ``` -InputObject - 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. +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? true - Position? 0 - Default value None - Accept pipeline input? True (ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByValue) +Accept wildcard characters? false -Name - Specifies the service names for the service to be started. +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. +The parameter name is optional. You can use Name or its alias, ServiceName, +or you can omit the parameter name. - Required? true - Position? 0 - Default value None - Accept pipeline input? True (ByPropertyName, ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByPropertyName, ByValue) +Accept wildcard characters? false ``` This means that you can send objects (PsObjects) through the pipeline to the -`Where-Object` cmdlet and Windows PowerShell will associate the object with the +`Where-Object` cmdlet and PowerShell will associate the object with the **InputObject** and **Name** parameters. ### 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 objects -that have the same .NET type as their parameter value or objects that can 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. + that have the same .NET type as their parameter value or objects that can be + converted to that type. -- ByPropertyName: Parameters that accept input "by property name" can accept piped -objects only when a property of the object has the same name as the parameter. + 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. -For example, the Name parameter of `Start-Service` can accept objects that have -a Name property. +- ByPropertyName: Parameters that accept input "by property name" can accept + piped objects only when a property of the object has the same name as the + parameter. -(To list the properties of an object, pipe it to `Get-Member`.) + For example, the Name parameter of `Start-Service` can accept objects that + 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 parameters are -designed to take input from the pipeline easily. +Some parameters can accept objects by value or by property name. These +parameters 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 failure and -rewrite the command. +If a command fails because of a pipeline error, you can investigate the +failure 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 destination path and -then piping the path to the `Move-ItemProperty` cmdlet. +registry key to another by using the `Get-Item` cmdlet to get the destination +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. The `Move-ItemProperty` -command specifies the current path and name of the registry entry to be moved. +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. The `Move-ItemProperty` command specifies the +current path and name of the registry entry to be moved. For example, + ```powershell 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 +The command fails and 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 pipeline input. +```output +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 +pipeline input. At line:1 char:23 -+ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name product ++ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name p ``` -To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of -Windows PowerShell. The following command traces the Parameter Binding component 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 reference. +To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding +component of PowerShell. The following command traces the Parameter Binding +component 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 reference. For example, + ```powershell -Trace-Command -Name parameterbinding -Expression {Get-Item -Path HKLM:\software\mycompany\sales | -Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} -PSHost -FilePath debug.txt +Trace-Command -Name parameterbinding -Expression { + Get-Item -Path HKLM:\software\mycompany\sales | + Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} ` + -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. +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`] @@ -442,31 +456,35 @@ 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 parameter -of `Move-ItemProperty` failed. +Finally, it shows that the attempt to bind the path to the **Destination** +parameter 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 ValueFromPipelineByPropertyName NO COERCION -Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION +Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyName NO CO +ERCION +Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COE +RCION ... +``` - -To investigate the failure, use the `Get-Help` cmdlet to view the attributes of the -**Destination** parameter. The following command gets detailed information about the -**Destination** parameter. +To investigate the failure, use the `Get-Help` cmdlet to view the attributes +of the **Destination** parameter. The following command gets detailed +information about the **Destination** parameter. ```powershell Get-Help Move-ItemProperty -Parameter Destination ``` -The results show that **Destination** takes pipeline input only "by property name". -That is, the piped object must have a property named Destination. +The results show that **Destination** takes pipeline input only "by property +name". That is, the piped object must have a property named Destination. ``` -Destination @@ -479,11 +497,12 @@ That is, the piped object must have a property named Destination. Accept wildcard characters? false ``` -To see the properties of the object being piped to the `Move-ItemProperty` cmdlet, -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. +To see the properties of the object being piped to the `Move-ItemProperty` +cmdlet, 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. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` @@ -491,11 +510,13 @@ 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-ItemProperty` cmdlet. We can -use a `Get-ItemProperty` command to get the path, but the name and destination must be specified -in the `Move-ItemProperty` part of the command. +To fix the command, we must specify the destination in the `Move-ItemProperty` +cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name +and destination must be specified in the `Move-ItemProperty` part of the +command. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\design | Move-ItemProperty -Dest HKLM:\software\mycompany\design -Name product @@ -510,9 +531,11 @@ Get-Itemproperty HKLM:\software\mycompany\sales The results show that the Product registry entry was moved to the Sales key. -``` -PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany\sales -PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany +```Output +PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany\sales +PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany PSChildName : sales PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry @@ -528,4 +551,3 @@ Product : 18 [about_command_syntax](about_command_syntax.md) [about_foreach](about_foreach.md) - diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_profiles.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_profiles.md index b7eabd81d0ce..eea0dd9f0d50 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_profiles.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_profiles.md @@ -1,104 +1,99 @@ --- -ms.date: 2017-06-25 +ms.date: 2017-11-30 schema: 2.0.0 keywords: powershell,cmdlet title: about_Profiles --- # About Profiles -## about_Profiles +## SHORT DESCRIPTION -# SHORT DESCRIPTION +Describes how to create and use a PowerShell profile. -Describes how to create and use a Windows PowerShell profile. +## LONG DESCRIPTION -# LONG DESCRIPTION +You can create a PowerShell profile to customize your environment and to add +session-specific elements to every PowerShell session that you start. -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 PowerShell profile is a script that runs when 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 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. -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. +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. -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 PowerShell console +(PowerShell.exe) to start PowerShell without any profiles. And, it explains +the effect of the PowerShell execution policy on profiles. -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 -# THE PROFILE FILES +PowerShell supports several profile files. Also, PowerShell host programs can +support their own host-specific profiles. - -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 +For example, the 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\Profile.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 | +|Description | Path | +|--------------------------|------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Profile.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 +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\Microsoft.PowerShellISE_profile.ps1 | -| All users, Current Host | $PsHome\Microsoft.PowerShellISE_profile.ps1 | +In addition, other programs that host PowerShell can support their own +profiles. For example, PowerShell Integrated Scripting Environment (ISE) +supports the following host-specific profiles. -In Windows PowerShell Help, the "CurrentUser, Current Host" profile is the profile most -often referred to as "your Windows PowerShell profile". +|Description | Path | +|--------------------------|-------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Microsoft.PowerShellISE_profile.ps1 | +|All users, Current Host |$PsHome\Microsoft.PowerShellISE_profile.ps1| -# THE $PROFILE VARIABLE +In PowerShell Help, the "CurrentUser, Current Host" profile is the profile +most often referred to as "your PowerShell profile". +## THE $PROFILE VARIABLE -The `$Profile` automatic variable stores the paths to the Windows PowerShell -profiles that are available in the current session. +The `$Profile` automatic variable stores the paths to the 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. +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 | +|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. +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 PowerShell host application that you use. To see the current values of the `$Profile` variable, type: @@ -107,24 +102,22 @@ $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: +following command opens the "Current User, Current Host" profile in Notepad: ```powershell notepad $profile ``` -The following command determines whether an "All Users, All Hosts" profile -has been created on the local computer: +The following command determines whether an "All Users, All Hosts" profile has +been created on the local computer: ```powershell Test-Path -Path $profile.AllUsersAllHosts ``` -# HOW TO CREATE A PROFILE +## HOW TO CREATE A PROFILE - -To create a Windows PowerShell profile, use the following command format: +To create a PowerShell profile, use the following command format: ```powershell if (!(Test-Path -Path )) @@ -132,7 +125,7 @@ if (!(Test-Path -Path )) ``` For example, to create a profile for the current user in the current -Windows PowerShell host application, use the following command: +PowerShell host application, use the following command: ```powershell if (!(Test-Path -Path $profile)) @@ -140,21 +133,18 @@ if (!(Test-Path -Path $profile)) ``` In this command, the If statement prevents you from overwriting an existing -profile. Replace the value of the placeholder with the path +profile. Replace the value of the \ 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 +> Note: To create "All Users" profiles in Windows Vista and later versions of +> Windows, start 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. +You can open any 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: +To open the profile of the current user in the current PowerShell host +application in Notepad, type: ```powershell notepad $profile @@ -167,106 +157,99 @@ 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. +To apply the changes, save the profile file, and then restart PowerShell. -# HOW TO CHOOSE A PROFILE +## 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 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: +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 - + `$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 +implementation of 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. +Many of the items that you create in 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](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), -and Windows PowerShell snap-ins that you add to the session. +variables, aliases, functions, commands (except for +[Set-ExecutionPolicy](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), +and PowerShell modules 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. +To save these items and make them available in all future sessions, add them +to a 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. +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 +## 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. +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: +### 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: ```powershell function Pro {notepad $profile.CurrentUserAllHosts} ``` -- Add a function that opens Windows PowerShell Help in a compiled HTML -Help file (.chm) +### Add a function that opens PowerShell Help in a compiled HTML + Help file (.chm) ```powershell -function Get-CHM -{ -Invoke-Item -Path "$env:windir\help\mui\0409\WindowsPowerShellHelp.chm" +function Get-CHM { + Invoke-Item -Path "$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. +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 +### Add a function that lists the aliases for any cmdlet ```powershell -function Get-CmdletAlias ($cmdletname) -{ -Get-Alias | Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | Format-Table -Property Definition, Name -AutoSize +function Get-CmdletAlias ($cmdletname) { + Get-Alias | + Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | + Format-Table -Property Definition, Name -AutoSize } ``` -- Customize your console +### Customize your console ```powershell -function Color-Console -{ -$Host.ui.rawui.backgroundcolor = "white" -$Host.ui.rawui.foregroundcolor = "black" -$hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime -$hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" -$Host.UI.RawUI.WindowTitle = "Windows PowerShell $hostversion ($hosttime)" -Clear-Host +function Color-Console { + $Host.ui.rawui.backgroundcolor = "white" + $Host.ui.rawui.foregroundcolor = "black" + $hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime + $hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" + $Host.UI.RawUI.WindowTitle = "PowerShell $hostversion ($hosttime)" + Clear-Host } Color-Console ``` -- Add a customized Windows PowerShell prompt that includes the computer -name and the current path +### Add a customized PowerShell prompt ```powershell function Prompt @@ -275,18 +258,16 @@ $env:COMPUTERNAME + "\" + (Get-Location) + "> " } ``` -For more information about the Windows PowerShell prompt, see +For more information about the PowerShell prompt, see [about_Prompts](about_Prompts.md). -# THE NOPROFILE PARAMETER +## THE NOPROFILE PARAMETER +To start PowerShell without profiles, use the **NoProfile** parameter of +PowerShell.exe, the program that starts PowerShell. -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. +To begin, open a program that can start PowerShell, such as Cmd.exe or +PowerShell itself. You can also use the Run dialog box in Windows. Type: @@ -294,56 +275,58 @@ Type: PowerShell -NoProfile ``` -For a complete list of the parameters of PowerShell.exe, -type: +For a complete list of the parameters of PowerShell.exe, type: ``` PowerShell -? ``` -# PROFILES AND EXECUTION POLICY - +## 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. +The 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. +one of the few commands that applies in all 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 +## PROFILES AND REMOTE SESSIONS +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 +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 sessions. +To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) +cmdlet. -To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) cmdlet. - -For example, the following command runs the "Current user, Current Host" profile from -the local computer in the session in $s. +For example, the following command runs the "Current user, Current Host" +profile from the local computer in the session in $s. ```powershell Invoke-Command -Session $s -FilePath $profile ``` -The following command runs the "Current user, Current Host" 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. +The following command runs the "Current user, Current Host" 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. ```powershell -Invoke-Command -SessionName $s -ScriptBlock {Invoke-Command -FilePath "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"} +Invoke-Command -SessionName $s -ScriptBlock { +$path = "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1" +Invoke-Command -FilePath $path +} ``` After running this command, the commands that the profile adds to the session are available in $s. -# SEE ALSO +## SEE ALSO [about_Automatic_Variables](about_Automatic_Variables.md) diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Object_Creation.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Object_Creation.md index 65a910c9ccab..0f745ac3aa94 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Object_Creation.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Object_Creation.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,232 +7,246 @@ title: about_Object_Creation --- # About Object Creation -## about_Object_Creation - ## SHORT DESCRIPTION -Explains how to create objects in Windows PowerShell. +Explains how to create objects in PowerShell. ## LONG DESCRIPTION -You can create objects in Windows PowerShell and use the objects that you create in commands and scripts. - -There are several ways to create objects: - -New-Object: -The New-Object cmdlet creates an instance of a .NET Framework object or COM object. +You can create objects in PowerShell and use the objects that you create in +commands and scripts. -Hash tables: +There are several ways to create objects: -Beginning in Windows PowerShell 3.0, you can create objects from hash tables of property names and property values. +- `New-Object`: This cmdlet creates an instance of a .NET Framework object or + COM object. -Import-Csv: +- Hash tables: Beginning in PowerShell 3.0, you can create objects + from hash tables of property names and property values. -The Import-Csv cmdlet creates custom objects (PSCustomObject) from the items in a CSV file. Each row is an object instance and each column is an object property. +- `Import-Csv`: This cmdlet creates custom objects (PSCustomObject) from the + items in a CSV file. Each row is an object instance and each column is an + object property. This topic will demonstrate and discuss each of these methods. - ## NEW-OBJECT -The New-Object cmdlet provides a robust and consistent way to create new objects. The cmdlet works with almost all types and in all supported versions of Windows PowerShell. -To create a new object, specify either the type of a .NET Framework class or a ProgID of a COM object. +The `New-Object` cmdlet provides a robust and consistent way to create new +objects. The cmdlet works with almost all types and in all supported versions +of PowerShell. -For example, the following command creates a Version object. +To create a new object, specify either the type of a .NET Framework class or a +ProgID of a COM object. +For example, the following command creates a Version object. -``` -PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 +```powershell +PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 PS C:\> $v ``` - - -``` -Major Minor Build Revision ------ ----- ----- -------- +```Output +Major Minor Build Revision +----- ----- ----- -------- 2 0 0 1 ``` +```powershell +PS C:\> $v | Get-Member - -``` -PS C:\> $v | Get-Member - TypeName: System.Version ``` - For more information, see the help topic for the New-Object cmdlet. - ### CREATE OBJECTS FROM HASH TABLES -Beginning in Windows PowerShell 3.0, you can create an object from a hash table of properties and property values. -The syntax is as follows: +Beginning in PowerShell 3.0, you can create an object from a hash table of +properties and property values. +The syntax is as follows: ``` -[]@{=;=} +[]@{ + = + = +} ``` - -This method works only for classes that have a null constructor, that is, a constructor that has no parameters. The object properties must be public and settable. - +This method works only for classes that have a null constructor, that is, a +constructor that has no parameters. The object properties must be public and +settable. ### CREATE CUSTOM OBJECTS FROM HASH TABLES -Custom objects are very useful and they are very easy to create by using the hash table method. To create a custom object, use the PSCustomObject class, a class designed specifically for this purpose. - -Custom objects are an excellent way to return customized output from a function or script; far more useful than returning formatted output that cannot be reformatted or piped to other commands. - -The commands in the Test-Object function set some variable values and then use those values to create a custom object. (You can see this object in use in the example section of the Update-Help cmdlet help topic.) - -``` -function Test-Object -{ $ModuleName = "PSScheduledJob" - $HelpCulture = "en-us" - $HelpVersion = "3.1.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} - - $ModuleName = "PSWorkflow" - $HelpCulture = "en-us" - $HelpVersion = "3.0.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} +Custom objects are very useful and they are very easy to create by using the +hash table method. To create a custom object, use the PSCustomObject class, a +class designed specifically for this purpose. + +Custom objects are an excellent way to return customized output from a +function or script; far more useful than returning formatted output that +cannot be reformatted or piped to other commands. + +The commands in the `Test-Object function` set some variable values and then +use those values to create a custom object. You can see this object in use in +the example section of the `Update-Help` cmdlet help topic. + +```powershell +function Test-Object { + $ModuleName = "PSScheduledJob" + $HelpCulture = "en-us" + $HelpVersion = "3.1.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } + $ModuleName = "PSWorkflow" + $HelpCulture = "en-us" + $HelpVersion = "3.0.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } } ``` +The output of this function is a collection of custom objects formatted as a +table by default. -The output of this function is a collection of custom objects formatted as a table by default. - +```powershell +PS C:\> Test-Object -``` -PS C:\> Test-Object - -ModuleName UICulture Version ---------- --------- ------- -PSScheduledJob en-us 3.1.0.0 +ModuleName UICulture Version +--------- --------- ------- +PSScheduledJob en-us 3.1.0.0 PSWorkflow en-us 3.0.0.0 ``` +Users can manage the properties of the custom objects just as they do with +standard objects. -Users can manage the properties of the custom objects just as they do with standard objects. - - -``` -PS C:\> (Test-Object).ModuleName - PSScheduledJob +```powershell +PS C:\> (Test-Object).ModuleName + PSScheduledJob PSWorkflow ``` - - #### CREATE NON-CUSTOM OBJECTS FROM HASH TABLES -You can also use hash tables to create objects for non-custom classes. When you create an object for a non-custom class, the full namespace name is required unless class is in the System namespace. Use only the properties of the class. -For example, the following command creates a session option object. +You can also use hash tables to create objects for non-custom classes. When +you create an object for a non-custom class, the full namespace name is +required unless class is in the System namespace. Use only the properties of +the class. +For example, the following command creates a session option object. +```powershell +[System.Management.Automation.Remoting.PSSessionOption]@{ + IdleTimeout=43200000 + SkipCnCheck=$True +} ``` -[System.Management.Automation.Remoting.PSSessionOption]@{IdleTimeout=43200000; SkipCnCheck=$True} -``` - -The requirements of the hash table feature, especially the null constructor requirement, eliminate many existing classes. However, most Windows PowerShell option classes are designed to work with this feature, as well as other very useful classes, such as the ScheduledJobTrigger class. +The requirements of the hash table feature, especially the null constructor +requirement, eliminate many existing classes. However, most PowerShell option +classes are designed to work with this feature, as well as other very useful +classes, such as the ScheduledJobTrigger class. +```powershell +[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{ + Frequency="Daily" + At="15:00" +} -``` -[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{Frequency="Daily";At="15:00"} - -Id Frequency Time DaysOfWeek Enabled --- --------- ---- ---------- ------- -0 Daily 6/6/2012 3:00:00 PM True +Id Frequency Time DaysOfWeek Enabled +-- --------- ---- ---------- ------- +0 Daily 6/6/2012 3:00:00 PM True ``` +You can also use the hash table feature when setting parameter values. For +example, the value of the **SessionOption** parameter of the New-PSSession +cmdlet and the value of the JobTrigger parameter of `Register-ScheduledJob` +can be a hash table. -You can also use the hash table feature when setting parameter values. For example, the value of the SessionOption parameter of the New-PSSession cmdlet and the value of the JobTrigger parameter of Register-ScheduledJob can be a hash table. - - -``` -New-PSSession -ComputerName Server01 -SessionOption @{IdleTimeout=43200000; SkipCnCheck=$True} -Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{Frequency="Daily";At="15:00"} +```powershell +New-PSSession -ComputerName Server01 -SessionOption @{ + IdleTimeout=43200000 + SkipCnCheck=$True +} +Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{ + Frequency="Daily" + At="15:00" +} ``` - - ### IMPORT-CSV -You can create custom objects from the items in a CSV file. When you use the Import-Csv cmdlet to import the CSV file, the cmdlet creates a custom object (PSCustomObject) for each item in the file. The column names are the object properties. -For example, if you import a CSV file of computer asset data, Import-CSV creates a collection of custom objects from the input. +You can create custom objects from the items in a CSV file. When you use the +`Import-Csv` cmdlet to import the CSV file, the cmdlet creates a custom object +(PSCustomObject) for each item in the file. The column names are the object +properties. +For example, if you import a CSV file of computer asset data, `Import-CSV` +creates a collection of custom objects from the input. ``` -#In Servers.csv -AssetID, Name, OS, Department -003, Server01, Windows Server 2012, IT -103, Server33, Windows 7, Marketing +#In Servers.csv +AssetID, Name, OS, Department +003, Server01, Windows Server 2012, IT +103, Server33, Windows 7, Marketing 212, Server35, Windows 8, Finance ``` +```powershell +PS C:\> $a = Import-Csv Servers.csv +PS C:\> $a - -``` -PS C:\> $a = Import-Csv Servers.csv -PS C:\> $a - -AssetID Name OS Department -------- ---- -- ---------- -003 Server01 Windows Server 2012 IT -103 Server33 Windows 7 Marketing +AssetID Name OS Department +------- ---- -- ---------- +003 Server01 Windows Server 2012 IT +103 Server33 Windows 7 Marketing 212 Server35 Windows 8 Finance ``` - Use the Get-Member cmdlet to confirm the object type. - -``` +```powershell PS C:\> $a | Get-Member ``` +```Output +TypeName: System.Management.Automation.PSCustomObject - -``` -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() -AssetID NoteProperty System.String AssetID=003 -Department NoteProperty System.String Department=IT -Name NoteProperty System.String Name=Server01 +Name MemberType Definition +---- ---------- ---------- +Equals Method bool Equals(System.Object obj) +GetHashCode Method int GetHashCode() +GetType Method type GetType() +ToString Method string ToString() +AssetID NoteProperty System.String AssetID=003 +Department NoteProperty System.String Department=IT +Name NoteProperty System.String Name=Server01 OS NoteProperty System.String OS=Windows Server 2012 ``` - You can use the custom objects just as you would standard objects. - -``` +```powershell PS C:\> $a | where {$_.OS -eq "Windows 8"} ``` - - -``` -AssetID Name OS Department -------- ---- -- ---------- +```output +AssetID Name OS Department +------- ---- -- ---------- 212 Server35 Windows 8 Finance ``` - For more information, see the help topic for the Import-Csv cmdlet. - ## SEE ALSO [about_Objects](about_Objects.md) @@ -243,9 +257,8 @@ For more information, see the help topic for the Import-Csv cmdlet. [about_Pipelines](about_Pipelines.md) -Get-Member - -Import-Csv +[Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) -New-Object +[Import-Csv](../../Microsoft.PowerShell.Utility/Import-Csv.md) +[New-Object](../../Microsoft.PowerShell.Utility/New-Object.md) diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Objects.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Objects.md index 88ab499af532..58308cabd6d7 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Objects.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Objects.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -58,20 +58,13 @@ directory objects are passed down the pipeline to the second command. The second command `where { $_.PsIsContainer -eq $false }` uses the PsIsContainer property of all file system objects to select only -files, which have a value of False ($false) in their PsIsContainer +files, which have a value of False (\$false) in their PsIsContainer property. Folders, which are containers and, thus, have a value of -True ($true) in their PsIsContainer property, are not selected. +True (\$true) in their PsIsContainer property, are not selected. The second command passes only the file objects to the third command `Format-List`, which displays the file objects in a list. -## For More Information - -Now that you understand a bit about objects, see the [about_Methods](about_Methods.md) -help topic to learn how to find and use object methods, the -[about_Properties](about_Properties.md) topic to learn how to find and use object properties, -and the [Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) topic, to learn how to find an object type. - ## See Also [about_Methods](about_Methods.md) diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md index 6e83191b889c..01d129ccc4bb 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -10,84 +10,85 @@ title: about_Operator_Precedence ## SHORT DESCRIPTION -Lists the Windows PowerShell operators in precedence order. +Lists the PowerShell operators in precedence order. -[This topic was contributed by Kirk Munro, a Windows PowerShell MVP +[This topic was contributed by Kirk Munro, a PowerShell MVP from Ottawa, Ontario] ## LONG DESCRIPTION -Windows PowerShell operators let you construct simple, but powerful -expressions. This topic lists the operators in precedence order. -Precedence order is the order in which Windows PowerShell evaluates -the operators when multiple operators appear in the same expression. - -When operators have equal precedence, Windows PowerShell evaluates -them from left to right. The exceptions are the assignment operators, -the cast operators, and the negation operators (!, -not, -bnot), -which are evaluated from right to left. - -You can use enclosures, such as parentheses, to override the -standard precedence order and force Windows PowerShell to evaluate -the enclosed part of an expression before an unenclosed part. - -In the following list, operators are listed in the order that they -are evaluated. Operators on the same line, or in the same group, have -equal precedence. - -The Operator column lists the operators. The Reference column lists -the Windows PowerShell Help topic in which the operator is described. -To display the topic, type `get-help `. - -|OPERATOR|REFERENCE| -|--------|---------| -|`$() @()`|[about_Operators](#index-operator)| -|`.` (dereference) `::` (static)|[about_Operators](about_Operators.md)| -|`[0]` (index operator)|[about_Operators](about_Operators.md)| +PowerShell operators let you construct simple, but powerful +expressions. This topic lists the operators in precedence order. Precedence +order is the order in which PowerShell evaluates the operators when +multiple operators appear in the same expression. + +When operators have equal precedence, PowerShell evaluates them from +left to right. The exceptions are the assignment operators, the cast +operators, and the negation operators (!, -not, -bnot), which are evaluated +from right to left. + +You can use enclosures, such as parentheses, to override the standard +precedence order and force PowerShell to evaluate the enclosed part of +an expression before an unenclosed part. + +In the following list, operators are listed in the order that they are +evaluated. Operators on the same line, or in the same group, have equal +precedence. + +The Operator column lists the operators. The Reference column lists the +PowerShell Help topic in which the operator is described. To display +the topic, type `get-help `. + +|OPERATOR |REFERENCE| +|------------------------|---------| +|`$() @()` |[about_Operators](#index-operator)| +|`.` (dereference) |[about_Operators](about_Operators.md)| +|`::` (static) |[about_Operators](about_Operators.md)| +|`[0]` (index operator) |[about_Operators](about_Operators.md)| |`[int]` (cast operators)|[about_Operators](about_Operators.md)| -|`-split` (unary)
`-join` (unary)|[about_Split](about_Split.md)
[about_Join](about_Join.md)| -|`,` (comma operator)|[about_Operators](about_Operators.md)| -|`++ --`|[about_Assignment_Operators](about_Assignment_Operators.md)| -|`-not`
`! -bNot`|[about_Logical_Operators](about_logical_operators.md)
[about_Comparison_Operators](about_Comparison_Operators.md)| -|`..` (range operator)|[about_Operators](about_Operators.md)| -|`-f` (format operator)|[about_Operators](about_Operators.md)| -|`* / %`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`+ -`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| - - -The following group of operators have equal precedence. Their -case-sensitive and explicitly case-insensitive variants have -the same precedence. - -|OPERATOR|REFERENCE| -|--------|---------| -|`-split` (unary)|[about_Split](about_Split.md)| -|`-join` (unary)|[about_Join](about_Join.md)| -|`-is -isnot -as`|[about_Type_Operators](about_Type_Operators.md)| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`,` (comma operator) |[about_Operators](about_Operators.md)| +|`++ --` |[about_Assignment_Operators](about_Assignment_Operators.md)| +|`-not` |[about_Logical_Operators](about_logical_operators.md)| +|`! -bNot` |[about_Comparison_Operators](about_Comparison_Operators.md)| +|`..` (range operator) |[about_Operators](about_Operators.md)| +|`-f` (format operator) |[about_Operators](about_Operators.md)| +|`* / % + -` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| + +The following group of operators have equal precedence. Their case-sensitive +and explicitly case-insensitive variants have the same precedence. + +|OPERATOR |REFERENCE| +|-------------------------|---------| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`-is -isnot -as` |[about_Type_Operators](about_Type_Operators.md)| |`-eq -ne -gt -gt -lt -le`|[about_Comparison_Operators](about_Comparison_Operators.md)| -|`-like -notlike`|[about_comparison_operators](about_comparison_operators.md)| -|`-match -notmatch`|[about_comparison_operators](about_comparison_operators.md)| -|`-in -notIn`|[about_comparison_operators](about_comparison_operators.md)| -|`-contains -notContains`|[about_comparison_operators](about_comparison_operators.md)| -|`-replace`|[about_comparison_operators](about_comparison_operators.md)| +|`-like -notlike` |[about_comparison_operators](about_comparison_operators.md)| +|`-match -notmatch` |[about_comparison_operators](about_comparison_operators.md)| +|`-in -notIn` |[about_comparison_operators](about_comparison_operators.md)| +|`-contains -notContains` |[about_comparison_operators](about_comparison_operators.md)| +|`-replace` |[about_comparison_operators](about_comparison_operators.md)| The list resumes here with the following operators in precedence order: -|OPERATOR|REFERENCE| -|--------|---------| -|`-band -bor -bxor`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`-and -or -xor`|[about_comparison_operators](about_comparison_operators.md)| -|`.` (dot-source)
`&` (call)|[about_Scopes](about_Scopes.md)
[about_Operators](about_Operators.md)| +|OPERATOR |REFERENCE| +|--------------------------|---------| +|`-band -bor -bxor` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| +|`-and -or -xor` |[about_comparison_operators](about_comparison_operators.md)| +|`.` (dot-source) |[about_Scopes](about_Scopes.md)| +|`&` (call) |[about_Operators](about_Operators.md)| || (pipeline operator)|[about_Operators](about_Operators.md)| -|`> >> 2> 2>> 2>&1`|[about_Redirection](about_Redirection.md)| -|`= += -= *= /= %=`|[about_Assignment_Operators](about_Assignment_Operators.md)| +|`> >> 2> 2>> 2>&1` |[about_Redirection](about_Redirection.md)| +|`= += -= *= /= %=` |[about_Assignment_Operators](about_Assignment_Operators.md)| # EXAMPLES -The following two commands show the arithmetic operators and -the effect of using parentheses to force Windows PowerShell to -evaluate the enclosed part of the expression first. +The following two commands show the arithmetic operators and the effect of +using parentheses to force PowerShell to evaluate the enclosed part of +the expression first. ```powershell C:\PS> 2 + 3 * 4 @@ -97,8 +98,8 @@ C:\PS> (2 + 3) * 4 20 ``` -The following example gets the read-only text files from the local -directory and saves them in the `$read_only` variable. +The following example gets the read-only text files from the local directory +and saves them in the `$read_only` variable. ```powershell $read_only = get-childitem *.txt | where-object {$_.isReadOnly} @@ -109,37 +110,37 @@ It is equivalent to the following example. $read_only = ( get-childitem *.txt | where-object {$_.isReadOnly} ) ``` -Because the pipeline operator (|) has a higher precedence than the -assignment operator (=), the files that the Get-ChildItem cmdlet -gets are sent to the Where-Object cmdlet for filtering before they -are assigned to the $read_only variable. +Because the pipeline operator (|) has a higher precedence than the assignment +operator (=), the files that the Get-ChildItem cmdlet gets are sent to the +Where-Object cmdlet for filtering before they are assigned to the $read_only +variable. -The following example demonstrates that the index operator takes -precedence over the cast operator. +The following example demonstrates that the index operator takes precedence +over the cast operator. -The first expression creates an array of three strings. Then, it -uses the index operator with a value of 0 to select the first object -in the array, which is the first string. Finally, it casts the -selected object as a string. In this case, the cast has no effect. +The first expression creates an array of three strings. Then, it uses the +index operator with a value of 0 to select the first object in the array, +which is the first string. Finally, it casts the selected object as a string. +In this case, the cast has no effect. ```powershell C:\PS> [string]@('Windows','PowerShell','2.0')[0] Windows ``` -The second expression uses parentheses to force the cast operation -to occur before the index selection. As a result, the entire array -is cast as a (single) string. Then, the index operator selects -the first item in the string array, which is the first character. +The second expression uses parentheses to force the cast operation to occur +before the index selection. As a result, the entire array is cast as a +(single) string. Then, the index operator selects the first item in the string +array, which is the first character. ```powershell C:\PS> ([string]@('Windows','PowerShell','2.0'))[0] W ``` -In the following example, because the -gt (greater-than) operator -has a higher precedence than the -and (logical AND) operator, the -result of the expression is FALSE. +In the following example, because the -gt (greater-than) operator has a higher +precedence than the -and (logical AND) operator, the result of the expression +is FALSE. ```powershell C:\PS> 2 -gt 4 -and 1 @@ -160,11 +161,11 @@ C:\PS> 2 -gt (4 -and 1) True ``` -However, this example demonstrates an important principle of managing -operator precedence. When an expression is difficult for people to -interpret, use parentheses to force the evaluation order, even when it -forces the default operator precedence. The parentheses make your -intentions clear to people who are reading and maintaining your scripts. +However, this example demonstrates an important principle of managing operator +precedence. When an expression is difficult for people to interpret, use +parentheses to force the evaluation order, even when it forces the default +operator precedence. The parentheses make your intentions clear to people who +are reading and maintaining your scripts. ## SEE ALSO @@ -185,4 +186,3 @@ intentions clear to people who are reading and maintaining your scripts. [about_Split](about_Split.md) [about_Type_Operators](about_Type_Operators.md) - diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_PackageManagement.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_PackageManagement.md index 86512bc2df24..7933f7f0a80e 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_PackageManagement.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_PackageManagement.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,87 +7,81 @@ title: about_PackageManagement --- # About PackageManagement -## about_PackageManagement -# TOPIC -about_PackageManagement - -# SHORT DESCRIPTION +## SHORT DESCRIPTION PackageManagement is an aggregator for software package managers. -# LONG DESCRIPTION +## LONG DESCRIPTION PackageManagement functionality was introduced in Windows PowerShell 5.0. -PackageManagement is a unified interface for software package management systems; you -can run PackageManagement cmdlets to perform software discovery, installation, and -inventory (SDII) tasks. Regardless of the underlying installation technology, -you can run the common cmdlets in the PackageManagement module to search for, -install, or uninstall packages; add, remove, and query package repositories; and -run queries on a computer to determine which software packages are installed. - -PackageManagement supports a flexible plug-in model that enables support for other -software package management systems. - -The PackageManagement module is included with Windows PowerShell 5.0 and later releases -of Windows PowerShell, and works on three levels of package management -structure: package providers, package sources, and the packages themselves. - -Term Description ----------- ------------------------------ -Package manager Software package management system. In -PackageManagement terms, this is a package provider. -Package provider PackageManagement term for a package manager. Examples -can include Windows Installer, Chocolatey, -and others. -Package source A URL, local folder, or network shared folder that -you configure package providers to use as a -repository. -Package A piece of software that a package provider manages, -and that is stored in a specific package source. - -The PackageManagement module includes the following cmdlets. You can find the -Help for these cmdlets on TechNet starting on the following page: -http://technet.microsoft.com/library/dn890951(v=wps.640).aspx. - -Cmdlet Description ----------- ------------------------------ -Get-PackageProvider Returns a list of package providers that are -connected to PackageManagement. -Get-PackageSource Gets a list of package sources that are -registered for a package provider. -Register-PackageSource Adds a package source for a specified -package provider. -Set-PackageSource Sets properties on an existing package -source. -Unregister-PackageSource Removes a registered package source. -Get-Package Returns a list of installed software -packages. -Find-Package Finds software packages in available -package sources. -Install-Package Installs one or more software packages. -Save-Package Saves packages to the local computer -without installing them. -Uninstall-Package Uninstalls one or more software packages. - -PackageManagement Package Provider Bootstrapping and Dynamic Cmdlet Parameters - -By default, PackageManagement ships with a core bootstrap provider. You can install -additional package providers as you need them by bootstrapping the providers; -that is, responding to a prompt to install the provider automatically, from a -web service. You can specify a package provider with any PackageManagement cmdlet; -if the specified provider is not available, PackageManagement prompts you to bootstrap ---or automatically install--the provider. In the following examples, if the -Chocolatey provider is not already installed, PackageManagement bootstrapping installs -the provider. - +PackageManagement is a unified interface for software package management +systems; you can run PackageManagement cmdlets to perform software discovery, +installation, and inventory (SDII) tasks. Regardless of the underlying +installation technology, you can run the common cmdlets in the +PackageManagement module to search for, install, or uninstall packages; add, +remove, and query package repositories; and run queries on a computer to +determine which software packages are installed. + +PackageManagement supports a flexible plug-in model that enables support for +other software package management systems. + +The PackageManagement module is included with Windows PowerShell 5.0 and later +releases of Windows PowerShell, and works on three levels of package +management structure: package providers, package sources, and the packages +themselves. Let us define some terms: + +- Package manager: Software package management system. In PackageManagement + terms, this is a package provider. +- Package provider: PackageManagement term for a package manager. Examples can + include Windows Installer, Chocolatey, and others. +- Package source: A URL, local folder, or network shared folder that you + configure package providers to use as a repository. +- Package: A piece of software that a package provider manages, and that is + stored in a specific package source. + +The PackageManagement module includes the following cmdlets. For more +information, see the +[PackageManagement](/powershell/gallery/psget/oneget/packagemanagement_cmdlets) +help. + +- `Get-PackageProvider`: Returns a list of package providers that are + connected to PackageManagement. +- `Get-PackageSource`: Gets a list of package sources that are registered for + a package provider. +- `Register-PackageSource`: Adds a package source for a specified package + provider. +- `Set-PackageSource`: Sets properties on an existing package source. +- `Unregister-PackageSource`: Removes a registered package source. +- `Get-Package`: Returns a list of installed software packages. +- `Find-Package`: Finds software packages in available package sources. +- `Install-Package`: Installs one or more software packages. +- `Save-Package`: Saves packages to the local computer without installing + them. +- `Uninstall-Package`: Uninstalls one or more software packages. + +### Package Provider Bootstrapping and Dynamic Cmdlet Parameters + +By default, PackageManagement ships with a core bootstrap provider. You can +install additional package providers as you need them by bootstrapping the +providers; that is, responding to a prompt to install the provider +automatically, from a web service. You can specify a package provider with any +PackageManagement cmdlet; if the specified provider is not available, +PackageManagement prompts you to bootstrap (or automatically install) the +provider. In the following examples, if the Chocolatey provider is not already +installed, PackageManagement bootstrapping installs the provider. + +```powershell Find-Package -Provider Chocolatey +``` If the Chocolatey provider is not already installed, when you run the preceding command, you are prompted to install it. +```powershell Install-Package -ForceBootstrap +``` If the Chocolatey provider is not already installed, when you run the preceding command, the provider is installed; but because the ForceBootstrap @@ -99,10 +93,10 @@ provider installed, and you do not add the ForceBootstrap parameter to your command, PackageManagement prompts you to install the provider. Specifying a package provider in your PackageManagement command can make -dynamic parameters available that are specific to that package provider. -When you run Get-Help for a specific PackageManagement cmdlet, a list of -parameter sets are returned, grouping dynamic parameters for available -package providers in separate parameter sets. +dynamic parameters available that are specific to that package provider. When +you run Get-Help for a specific PackageManagement cmdlet, a list of parameter +sets are returned, grouping dynamic parameters for available package providers +in separate parameter sets. More Information About the PackageManagement Project @@ -131,4 +125,3 @@ Install-Package Save-Package Uninstall-Package - diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md index 871bcb0dd4f2..e9c4ebaefa98 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,449 +7,409 @@ title: about_Parameters_Default_Values --- # About Parameters Default Values -## about_Parameters_Default_Values - ## SHORT DESCRIPTION -Describes how to set custom default values for the parameters of cmdlets and advanced functions. +Describes how to set custom default values for the parameters of cmdlets and +advanced functions. ## LONG DESCRIPTION -The $PSDefaultParameterValues preference variable lets you specify custom default values for any cmdlet or advanced function. Cmdlets and functions use the custom default value unless you specify another value in the command. -The authors of cmdlets and advanced functions set standard default values for their parameters. Typically, the standard default values are useful, but they might not be appropriate for all environments. +The \$PSDefaultParameterValues preference variable lets you specify custom +default values for any cmdlet or advanced function. Cmdlets and functions use +the custom default value unless you specify another value in the command. + +The authors of cmdlets and advanced functions set standard default values for +their parameters. Typically, the standard default values are useful, but they +might not be appropriate for all environments. -This feature is especially useful when you must specify the same alternate parameter value nearly every time you use the command or when a particular parameter value is difficult to remember, such as an e-mail server name or project GUID. +This feature is especially useful when you must specify the same alternate +parameter value nearly every time you use the command or when a particular +parameter value is difficult to remember, such as an e-mail server name or +project GUID. -If the desired default value varies predictably, you can specify a script block that provides different default values for a parameter under different conditions. +If the desired default value varies predictably, you can specify a script +block that provides different default values for a parameter under different +conditions. -$PSDefaultParameterValues was introduced in Windows PowerShell 3.0. +\$PSDefaultParameterValues was introduced in PowerShell 3.0. +## SYNTAX -### SYNTAX The syntax of the $PSDefaultParameterValues preference variable is as follows: +```powershell +$PSDefaultParameterValues=@{":"=""} + +$PSDefaultParameterValues=@{":"={}} -``` -$PSDefaultParameterValues=@{":"=""} - -$PSDefaultParameterValues=@{":"={}} - $PSDefaultParameterValues["Disabled"]=$true | $false ``` - Wildcard characters are permitted in the CmdletName and ParameterName values. -The value of $PSDefaultParameterValues is a System.Management.Automation.DefaultParameterDictionary, a type of hash table that validates the format of keys. Enter a hash table where the key consists of the cmdlet name and parameter name separated by a colon (:) and the value is the custom default value. - -To set, change, add, or remove entries from $PSDefaultParameterValues, use the methods that you would use to edit a standard hash table. +The value of \$PSDefaultParameterValues is a +System.Management.Automation.DefaultParameterDictionary, a type of hash table +that validates the format of keys. Enter a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (:) and the value +is the custom default value. -The must be the name of a cmdlet or the name of an advanced function that uses the CmdletBinding attribute. You cannot use $PSDefaultParameterValues to specify default values for scripts or simple functions. +To set, change, add, or remove entries from \$PSDefaultParameterValues, use the +methods that you would use to edit a standard hash table. -The default value can be an object or a script block. If the value is a script block, Windows PowerShell evaluates the script block and uses the result as the parameter value. When the specified parameter takes a script block value, enclose the script block value in a second set of braces, such as: +The \ must be the name of a cmdlet or the name of an advanced +function that uses the CmdletBinding attribute. You cannot use +$PSDefaultParameterValues to specify default values for scripts or simple +functions. +The default value can be an object or a script block. If the value is a script +block, PowerShell evaluates the script block and uses the result as the +parameter value. When the specified parameter takes a script block value, +enclose the script block value in a second set of braces, such as: -``` +```powershell $PSDefaultParameterValues=@{ "Invoke-Command:ScriptBlock"={{Get-Process}} } ``` +For information about hash tables, see +[about_Hash_Tables](about_Hash_Tables.md). For information about script +blocks, see [about_Script_Blocks](about_Script_Blocks.md). For information +about preference variables, see +[about_Preference_Variables](about_Preference_Variables.md). -For information about hash tables, see about_Hash_Tables. For information about script blocks, see about_Script_Blocks. For information about preference variables, see about_Preference_Variables. - +## EXAMPLES -### EXAMPLES -The following command sets a custom default value for the SmtpServer parameter of the Send-MailMessage cmdlet. +The following command sets a custom default value for the SmtpServer parameter +of the Send-MailMessage cmdlet. - -``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"} +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" +} ``` +To set default values for multiple parameters, use a semi-colon (;) to +separate each Name\=Value pair. The following command adds a custom default +value for the LogName parameter of the `Get-WinEvent` cmdlet. -To set default values for multiple parameters, use a semi-colon (;) to separate each Name\=Value pair. The following command adds a custom default value for the LogName parameter of the Get-WinEvent cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5"; + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" +} ``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"} -``` - -You can use wildcard characters in the name of the cmdlet and parameter. The following command sets the Verbose common parameter to $true in all commands. Use $true and $false to set values for switch parameters, such as Verbose. +You can use wildcard characters in the name of the cmdlet and parameter. The +following command sets the Verbose common parameter to \$true in all commands. +Use \$true and \$false to set values for switch parameters, such as +**Verbose**. - -``` +```powershell $PSDefaultParameterValues = @{"*:Verbose"=$true} ``` +If a parameter takes multiple values (an array), you can set multiple values +as the default value. The following command sets the default value of the +**ComputerName** parameter of the Invoke-Command cmdlet to "Server01" and +"Server02". -If a parameter takes multiple values (an array), you can set multiple values as the default value. The following command sets the default value of the ComputerName parameter of the Invoke-Command cmdlet to "Server01" and "Server02". - - -``` -$PSDefaultParameterValues = @{"Invoke-Command:ComputerName"="Server01","Server02"} -``` - - -You can use a script block to specify different default values for a parameter under different conditions. Windows PowerShell evaluates the script block and uses the result as the default parameter value. - -The following command sets the default value of the Autosize parameter of the Format-Table cmdlet to $true when the host program is the Windows PowerShell console. - - -``` -$PSDefaultParameterValues=@{"Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}}} -``` - - -If a parameter takes a script block value, enclose the script block in an extra set of braces. When Windows PowerShell evaluates the outer script block, the result is the inner script block, which is set as the default parameter value. - -The following command sets the default value of the ScriptBlock parameter of Invoke-Command. Because the script block is enclosed in a second set of braces, the enclosed script block is passed to the Invoke-Command cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Invoke-Command:ComputerName"="Server01","Server02" +} ``` -$PSDefaultParameterValues=@{"Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}}} -``` - - - -### HOW TO SET $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. - -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues +You can use a script block to specify different default values for a parameter +under different conditions. PowerShell evaluates the script block and uses the +result as the default parameter value. -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. +The following command sets the default value of the Autosize parameter of the +Format-Table cmdlet to \$true when the host program is the PowerShell console. - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +$PSDefaultParameterValues=@{ + "Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}} +} ``` +If a parameter takes a script block value, enclose the script block in an +extra set of braces. When PowerShell evaluates the outer script block, the +result is the inner script block, which is set as the default parameter value. +The following command sets the default value of the ScriptBlock parameter of +`Invoke-Command`. Because the script block is enclosed in a second set of +braces, the enclosed script block is passed to the `Invoke-Command` cmdlet. -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational -Get*:Verbose True +```powershell +$PSDefaultParameterValues=@{ + "Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}} +} ``` +### HOW TO SET \$PSDefaultParameterValues -To get the value of a key, use the following command syntax: +\$PSDefaultParameterValues is a preference variable, so it exists only in the +session in which it is set. It has no default value. +To set \$PSDefaultParameterValues, type the variable name and one or more +key-value pairs at the command line. -``` -$PSDefaultParameterValues[""] -``` +If you type another \$PSDefaultParameterValues command, its value replaces the +original value. The original is not retained. +To save \$PSDefaultParameterValues for future sessions, add a +\$PSDefaultParameterValues command to your PowerShell profile. For more +information, see [about_Profiles](about_Profiles.md). -For example: +### HOW TO GET \$PSDefaultParameterValues +To get the value of \$PSDefaultParameterValues, at the command prompt, type: +```powershell +$PSDefaultParameterValues ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] -Server01AB234x5 -``` - - - -### HOW TO ADD VALUES TO $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. +For example, the first command sets the value of \$PSDefaultParameterValues. +The second command gets the value of \$PSDefaultParameterValues. -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues - -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. - - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +PS C:\> $PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" + "Get-*:Verbose"=$true +} ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To get the value of a \ key, use the following +command syntax: -To get the value of a key, use the following command syntax: - - -``` +```powershell $PSDefaultParameterValues[""] ``` - For example: - -``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] +```powershell +PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] Server01AB234x5 ``` +### HOW TO ADD VALUES TO PSDefaultParameterValues +To add or remove values from \$PSDefaultParameterValues, use the methods that +you would use for a standard hash table. -### HOW TO ADD VALUES TO $PSDefaultParameterValues -To add or remove values from $PSDefaultParameterValues, use the methods that you would use for a standard hash table. - -For example, to add a value to $PSDefaultParameterValues without affecting the existing values, use the Add method of hash tables. +For example, to add a value to \$PSDefaultParameterValues without affecting the +existing values, use the Add method of hash tables. The syntax of the Add method is as follows: - ``` .Add(Key, Value) ``` +where the Key is ":" and the value is the parameter +value. -where the Key is ":" and the value is the parameter value. - -Use the following command format to call the Add method on $PSDefaultParameterValues. Be sure to use a comma (,) to separate the key from the value, instead of the equal sign (\=). - +Use the following command format to call the Add method on +\$PSDefaultParameterValues. Be sure to use a comma (,) to separate the key +from the value, instead of the equal sign (\=). +```powershell +$PSDefaultParameterValues.Add( + ":", "" +) ``` -$PSDefaultParameterValues.Add(":", "") -``` - -For example, the following command adds "PowerShell" as the default value of the Name parameter of the Get-Process cmdlet. +For example, the following command adds "PowerShell" as the default value of +the Name parameter of the Get-Process cmdlet. - -``` +```powershell $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO REMOVE VALUES FROM \$PSDefaultParameterValues - -### HOW TO REMOVE VALUES FROM $PSDefaultParameterValues -To remove a value from $PSDefaultParameterValues, use the Remove method of hash tables. +To remove a value from \$PSDefaultParameterValues, use the Remove method of +hash tables. The syntax of the Remove method is as follows: - -``` +```powershell .Remove(Key) ``` +Use the following command format to call the Remove method on +\$PSDefaultParameterValues. -Use the following command format to call the Remove method on $PSDefaultParameterValues. - - -``` +```powershell $PSDefaultParameterValues.Remove(":") ``` +For example, the following command removes the Name parameter of the +`Get-Process` cmdlet and its values. -For example, the following command removes the Name parameter of the Get-Process cmdlet and its values. - - -``` +```powershell $PSDefaultParameterValues.Remove("Get-Process:Name") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Remove("Get-Process:Name") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO CHANGE VALUES IN \$PSDefaultParameterValues +To change a value in $PSDefaultParameterValues, use the following command +format. -### HOW TO CHANGE VALUES IN $PSDefaultParameterValues -To change a value in $PSDefaultParameterValues, use the following command format. - - -``` +```powershell $PSDefaultParameterValues["CmdletName:ParameterName"]="" ``` - The following example shows the effect of this command. +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - +```powershell +$PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" -``` - +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO DISABLE AND RE-ENABLE \$PSDefaultParameterValues +You can temporarily disable and then re-enable \$PSDefaultParameterValues. This +is very useful if you're running scripts that might assume different default +parameter values. -### HOW TO DISABLE AND RE-ENABLE $PSDefaultParameterValues -You can temporarily disable and then re-enable $PSDefaultParameterValues. This is very useful if you're running scripts that might assume different default parameter values. - -To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of $True. +To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of +\$True. For example, - -``` +```powershell $PSDefaultParameterValues.Add("Disabled", $true) ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$true ``` +The other values in \$PSDefaultParameterValues are preserved, but not +effective. -The other values in $PSDefaultParameterValues are preserved, but not effective. - +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Disabled True -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Disabled True +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To re-enable \$PSDefaultParameterValues, remove the Disabled key or change the +value of the Disabled key to \$False. -To re-enable $PSDefaultParameterValues, remove the Disabled key or change the value of the Disabled key to $False. - - -``` +```powershell $PSDefaultParameterValues.Remove("Disabled") ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$false ``` - -The previous value of $PSDefaultParameterValues is effective again. - +The previous value of \$PSDefaultParameterValues is effective again. ## KEYWORDS + about_PSDefaultParameterValues about_Parameters_DefaultValues about_DefaultValues - ## SEE ALSO [about_Hash_Tables](about_Hash_Tables.md) @@ -459,4 +419,3 @@ about_DefaultValues [about_Profiles](about_Profiles.md) [about_Script_Blocks](about_Script_Blocks.md) - diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Profiles.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Profiles.md index b7eabd81d0ce..eea0dd9f0d50 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Profiles.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Profiles.md @@ -1,104 +1,99 @@ --- -ms.date: 2017-06-25 +ms.date: 2017-11-30 schema: 2.0.0 keywords: powershell,cmdlet title: about_Profiles --- # About Profiles -## about_Profiles +## SHORT DESCRIPTION -# SHORT DESCRIPTION +Describes how to create and use a PowerShell profile. -Describes how to create and use a Windows PowerShell profile. +## LONG DESCRIPTION -# LONG DESCRIPTION +You can create a PowerShell profile to customize your environment and to add +session-specific elements to every PowerShell session that you start. -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 PowerShell profile is a script that runs when 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 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. -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. +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. -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 PowerShell console +(PowerShell.exe) to start PowerShell without any profiles. And, it explains +the effect of the PowerShell execution policy on profiles. -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 -# THE PROFILE FILES +PowerShell supports several profile files. Also, PowerShell host programs can +support their own host-specific profiles. - -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 +For example, the 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\Profile.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 | +|Description | Path | +|--------------------------|------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Profile.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 +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\Microsoft.PowerShellISE_profile.ps1 | -| All users, Current Host | $PsHome\Microsoft.PowerShellISE_profile.ps1 | +In addition, other programs that host PowerShell can support their own +profiles. For example, PowerShell Integrated Scripting Environment (ISE) +supports the following host-specific profiles. -In Windows PowerShell Help, the "CurrentUser, Current Host" profile is the profile most -often referred to as "your Windows PowerShell profile". +|Description | Path | +|--------------------------|-------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Microsoft.PowerShellISE_profile.ps1 | +|All users, Current Host |$PsHome\Microsoft.PowerShellISE_profile.ps1| -# THE $PROFILE VARIABLE +In PowerShell Help, the "CurrentUser, Current Host" profile is the profile +most often referred to as "your PowerShell profile". +## THE $PROFILE VARIABLE -The `$Profile` automatic variable stores the paths to the Windows PowerShell -profiles that are available in the current session. +The `$Profile` automatic variable stores the paths to the 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. +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 | +|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. +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 PowerShell host application that you use. To see the current values of the `$Profile` variable, type: @@ -107,24 +102,22 @@ $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: +following command opens the "Current User, Current Host" profile in Notepad: ```powershell notepad $profile ``` -The following command determines whether an "All Users, All Hosts" profile -has been created on the local computer: +The following command determines whether an "All Users, All Hosts" profile has +been created on the local computer: ```powershell Test-Path -Path $profile.AllUsersAllHosts ``` -# HOW TO CREATE A PROFILE +## HOW TO CREATE A PROFILE - -To create a Windows PowerShell profile, use the following command format: +To create a PowerShell profile, use the following command format: ```powershell if (!(Test-Path -Path )) @@ -132,7 +125,7 @@ if (!(Test-Path -Path )) ``` For example, to create a profile for the current user in the current -Windows PowerShell host application, use the following command: +PowerShell host application, use the following command: ```powershell if (!(Test-Path -Path $profile)) @@ -140,21 +133,18 @@ if (!(Test-Path -Path $profile)) ``` In this command, the If statement prevents you from overwriting an existing -profile. Replace the value of the placeholder with the path +profile. Replace the value of the \ 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 +> Note: To create "All Users" profiles in Windows Vista and later versions of +> Windows, start 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. +You can open any 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: +To open the profile of the current user in the current PowerShell host +application in Notepad, type: ```powershell notepad $profile @@ -167,106 +157,99 @@ 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. +To apply the changes, save the profile file, and then restart PowerShell. -# HOW TO CHOOSE A PROFILE +## 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 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: +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 - + `$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 +implementation of 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. +Many of the items that you create in 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](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), -and Windows PowerShell snap-ins that you add to the session. +variables, aliases, functions, commands (except for +[Set-ExecutionPolicy](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), +and PowerShell modules 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. +To save these items and make them available in all future sessions, add them +to a 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. +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 +## 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. +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: +### 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: ```powershell function Pro {notepad $profile.CurrentUserAllHosts} ``` -- Add a function that opens Windows PowerShell Help in a compiled HTML -Help file (.chm) +### Add a function that opens PowerShell Help in a compiled HTML + Help file (.chm) ```powershell -function Get-CHM -{ -Invoke-Item -Path "$env:windir\help\mui\0409\WindowsPowerShellHelp.chm" +function Get-CHM { + Invoke-Item -Path "$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. +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 +### Add a function that lists the aliases for any cmdlet ```powershell -function Get-CmdletAlias ($cmdletname) -{ -Get-Alias | Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | Format-Table -Property Definition, Name -AutoSize +function Get-CmdletAlias ($cmdletname) { + Get-Alias | + Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | + Format-Table -Property Definition, Name -AutoSize } ``` -- Customize your console +### Customize your console ```powershell -function Color-Console -{ -$Host.ui.rawui.backgroundcolor = "white" -$Host.ui.rawui.foregroundcolor = "black" -$hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime -$hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" -$Host.UI.RawUI.WindowTitle = "Windows PowerShell $hostversion ($hosttime)" -Clear-Host +function Color-Console { + $Host.ui.rawui.backgroundcolor = "white" + $Host.ui.rawui.foregroundcolor = "black" + $hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime + $hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" + $Host.UI.RawUI.WindowTitle = "PowerShell $hostversion ($hosttime)" + Clear-Host } Color-Console ``` -- Add a customized Windows PowerShell prompt that includes the computer -name and the current path +### Add a customized PowerShell prompt ```powershell function Prompt @@ -275,18 +258,16 @@ $env:COMPUTERNAME + "\" + (Get-Location) + "> " } ``` -For more information about the Windows PowerShell prompt, see +For more information about the PowerShell prompt, see [about_Prompts](about_Prompts.md). -# THE NOPROFILE PARAMETER +## THE NOPROFILE PARAMETER +To start PowerShell without profiles, use the **NoProfile** parameter of +PowerShell.exe, the program that starts PowerShell. -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. +To begin, open a program that can start PowerShell, such as Cmd.exe or +PowerShell itself. You can also use the Run dialog box in Windows. Type: @@ -294,56 +275,58 @@ Type: PowerShell -NoProfile ``` -For a complete list of the parameters of PowerShell.exe, -type: +For a complete list of the parameters of PowerShell.exe, type: ``` PowerShell -? ``` -# PROFILES AND EXECUTION POLICY - +## 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. +The 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. +one of the few commands that applies in all 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 +## PROFILES AND REMOTE SESSIONS +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 +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 sessions. +To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) +cmdlet. -To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) cmdlet. - -For example, the following command runs the "Current user, Current Host" profile from -the local computer in the session in $s. +For example, the following command runs the "Current user, Current Host" +profile from the local computer in the session in $s. ```powershell Invoke-Command -Session $s -FilePath $profile ``` -The following command runs the "Current user, Current Host" 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. +The following command runs the "Current user, Current Host" 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. ```powershell -Invoke-Command -SessionName $s -ScriptBlock {Invoke-Command -FilePath "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"} +Invoke-Command -SessionName $s -ScriptBlock { +$path = "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1" +Invoke-Command -FilePath $path +} ``` After running this command, the commands that the profile adds to the session are available in $s. -# SEE ALSO +## SEE ALSO [about_Automatic_Variables](about_Automatic_Variables.md) diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Prompts.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Prompts.md index bc2e78b01d08..6f1820bea646 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Prompts.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Prompts.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,308 +7,284 @@ title: about_Prompts --- # About Prompts -## about_Prompts - ## SHORT DESCRIPTION -Describes the Prompt function and demonstrates how to create a custom Prompt function. +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: +The PowerShell command prompt indicates that PowerShell is ready to run a +command: ``` PS C:\> ``` +The PowerShell prompt is determined by the built-in Prompt function. You can +customize the prompt by creating your own Prompt function and saving it in +your PowerShell profile. -The Windows PowerShell prompt is determined by the built-in Prompt function. You can customize the prompt by creating your own Prompt function and saving it in your Windows PowerShell profile. - +## ABOUT THE PROMPT FUNCTION -### ABOUT 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 determines the appearance of the PowerShell prompt. +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: - -``` +```powershell function Prompt { } ``` +The Prompt function must return an object. As a best practice, return a string +or an object that is formatted as a string. The maximum recommended length is +80 characters. -The Prompt function must return an object. As a best practice, return a string or an object that is formatted as a string. The maximum recommended length is 80 characters. - -For example, the following prompt function returns a "Hello, World" string followed by a caret (>). +For example, the following prompt function returns a "Hello, World" string +followed by a caret (>). - -``` -PS C:\> function prompt {"Hello, World > "} +```powershell +PS C:\> function prompt {"Hello, World > "} Hello, World > ``` - - ### GETTING THE PROMPT FUNCTION -To get the Prompt function, use the Get-Command cmdlet or use the Get-Item cmdlet in the Function drive. -Functions are commands. So, you can use the Get-Command cmdlet to get functions, including the Prompt function. +To get the Prompt function, use the `Get-Command` cmdlet or use the `Get-Item` +cmdlet in the Function drive. For example: +```powershell +PS C:\> Get-Command Prompt -``` -PS C:\> Get-Command Prompt - -CommandType Name ModuleName ------------ ---- ---------- +CommandType Name ModuleName +----------- ---- ---------- Function prompt ``` - -To get the script that sets the value of the prompt, use the dot method to get the ScriptBlock property of the Prompt function. +To get the script that sets the value of the prompt, use the dot method to get +the ScriptBlock property of the Prompt function. For example: +```powershell +PS C:\> (Get-Command Prompt).ScriptBlock -``` -PS C:\> (Get-Command Prompt).ScriptBlock - -"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -# .Link -# http://go.microsoft.com/fwlink/?LinkID=225750 +"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPr +omptLevel + 1)) " +# .Link +# http://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml ``` +Like all functions, the Prompt function is stored in the Function: drive. To +display the script that creates the current Prompt function, type: -Like all functions, the Prompt function is stored in the Function: drive. To display the script that creates the current Prompt function, type: - - -``` +```powershell (Get-Item function:prompt).ScriptBlock ``` - ### THE DEFAULT PROMPT -The default prompt appears only when the Prompt function generates an error or does not return an object. -The default Windows PowerShell prompt is: +The default prompt appears only when the Prompt function generates an error or +does not return an object. +The default PowerShell prompt is: ``` PS> ``` +For example, the following command sets the Prompt function to $null, which is +invalid. As a result, the default prompt appears. -For example, the following command sets the Prompt function to $null, which is invalid. As a result, the default prompt appears. - - -``` -PS C:\> function prompt {$null} +```powershell +PS C:\> function prompt {$null} PS> ``` - -Because Windows PowerShell comes with a built-in prompt, you usually do not see the default prompt. - +Because PowerShell comes with a built-in prompt, you usually do not see the +default prompt. ### BUILT-IN PROMPT -Windows PowerShell includes a built-in prompt function. - -In Windows PowerShell 3.0, the built-in prompt function is: - - -``` -function prompt -{ - "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -} -``` - -This simplified prompt starts with "PS" followed by the current location, and one ">" for each nested prompt level. +PowerShell includes a built-in prompt function. -In Windows PowerShell 2.0, the built-in prompt function is: - - -``` -function prompt -{ - $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } - else { '' }) + 'PS ' + $(Get-Location) ` - + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' +```powershell +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: -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: - - -``` +```Output [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 (>). -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: -``` -For example: - PS C:\ps-test> +```Output +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.) -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: -For example, when you are debugging in a nested prompt, the prompt resembles the following prompt: - - -``` +```Output [DBG] PS C:\ps-test>>> ``` - - ### CHANGES TO THE PROMPT -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: +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 +```Output +PS Hello, World> Enter-PSSession Server01 [Server01]: PS Hello, World> ``` +Other PowerShell host applications and alternate shells might have their own +custom command prompts. -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. - +For more information about the \$PSDebugContext and $NestedPromptLevel +automatic variables, see [about_Automatic_Variables](about_Automatic_Variables.md). ### HOW TO CUSTOMIZE 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: +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: -``` +```powershell function prompt { } ``` - -Then, between the braces, enter the commands or the string that creates your prompt. +Then, between the braces, enter the commands or the string that creates your +prompt. For example, the following prompt includes your computer name: - -``` +```powershell function prompt {"PS [$env:COMPUTERNAME]> "} ``` - On the Server01 computer, the prompt resembles the following prompt: - -``` +```Output PS [Server01] > ``` - The following prompt function includes the current date and time: - -``` +```powershell function prompt {"$(get-date)> "} ``` - The prompt resembles the following prompt: - -``` +```Output 03/15/2012 17:49:47> ``` - You can also change the default Prompt function: -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) { '>>' }) + '> ' +For example, the following modified Prompt function adds "[ADMIN]:" to the +built-in PowerShell prompt when PowerShell is opened by using the "Run as +administrator" option: + +```powershell +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 PowerShell by using the "Run as administrator" option, a prompt +that resembles the following prompt appears: -When you start Windows PowerShell by using the "Run as administrator" option, a prompt that resembles the following prompt appears: - - -``` +```Output [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. -The following Prompt function displays the history ID of the next command. To view the command history, use the Get-History cmdlet. - +```powershell +function prompt { + # The at sign creates an array in case only one history item exists. + $history = @(get-history) + if($history.Count -gt 0) + { + $lastItem = $history[$history.Count - 1] + $lastId = $lastItem.Id + } -``` -function prompt -{ - # The at sign creates an array in case only one history item exists. - $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 >" + $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, PowerShell uses the default prompt, "PS>". -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 -ForegroundColor $Color - return " " +```powershell +function prompt { + $color = Get-Random -Min 1 -Max 16 + Write-Host ("PS " + $(Get-Location) +">") -NoNewLine ` + -ForegroundColor $Color + return " " } ``` - - ### SAVING THE PROMPT FUNCTION -Like any function, the Prompt function exists 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. +Like any function, the Prompt function exists only in the current session. To +save the Prompt function for future sessions, add it to your PowerShell +profiles. For more information about profiles, see about_Profiles. ## SEE ALSO -Get-Location +[Get-Location](../../Microsoft.PowerShell.Management/Get-Location.md) -Enter-PSSession +[Enter-PSSession](../Enter-PSSession.md) -Get-History +[Get-History](../Get-History.md) -Get-Random +[Get-Random](../../Microsoft.PowerShell.Utility/Get-Random.md) -Write-Host +[Write-Host](../../Microsoft.PowerShell.Utility/Write-Host.md) [about_Profiles](about_Profiles.md) diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_pipelines.md index ec7b65c085af..97cd9535c505 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,41 +7,39 @@ title: about_pipelines --- # About Pipelines -## about_Pipelines - - ### Short Description -Combining commands into pipelines in the Windows PowerShell +Combining commands into pipelines in the 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. +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 powerful -command chain or "pipeline" that is comprised of a series of simple commands. +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 powerful command +chain or "pipeline" that is comprised of a series of simple commands. For example, + ```powershell 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` processes -the objects and send them down the pipeline. Because there are no more commands in -the pipeline, the results are displayed at the console. +`Command-2` processes the objects and sends them to `Command-3`. `Command-3` +processes the objects and send them down the pipeline. Because there are no +more commands 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. +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. +Here is a simple example. The following command gets the Notepad process and +then stops it. For example, ```powershell @@ -49,77 +47,69 @@ 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 object -to the `Stop-Process` cmdlet, which stops the Notepad process. Notice that the -`Stop-Process` command does not have a Name or ID parameter to specify the process, -because the specified process is submitted through the pipeline. +the Notepad process. It uses a pipeline operator (`|`) to send the process +object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice +that the `Stop-Process` command does not have a Name or ID parameter to +specify the process, because the specified process is submitted through the +pipeline. Here is a practical example. This command pipeline gets the text files in the -current directory, selects only the files that are more than 10,000 bytes long, -sorts them by length, and displays the name and length of each file in a table. +current directory, selects only the files that are more than 10,000 bytes +long, sorts them by length, and displays the name and length of each file in a +table. ```powershell 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 command -is written horizontally, but we will show the process vertically in the following -graphic. +This pipeline is comprised of four commands in the specified order. The +command is written horizontally, but we will show the process vertically in +the following graphic. `Get-ChildItem` `-Path` *.txt - **|** - -| (FileInfo objects ) -| ( .txt ) - - **|** - - **V** +``` +| +| (FileInfo objects for *.txt) +| +V +``` `Where-Object` {$_.length `-gt` 10000} - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| +V +``` `Sort-Object` `-Property` Length - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) -| ( Sorted by length ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.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** - ``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| ( Sorted by length ) +| ( Formatted in a table ) +| +V +``` + +```output Name Length ---- ------ tmp1.txt 82920 @@ -129,13 +119,13 @@ tmp3.txt 114000 ### Using Pipelines +The PowerShell cmdlets were designed to be used in pipelines. For example, 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. -The Windows PowerShell cmdlets were designed to be used in pipelines. For example, -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 `Start-Service` -or `Stop-Service` cmdlets (although disabled services cannot be restarted in this way). +For example, you can pipe any service from the `Get-Service` cmdlet to the +`Start-Service` or `Stop-Service` cmdlets (although disabled services cannot +be restarted in this way). This command pipeline starts the WMI service on the computer: @@ -144,90 +134,98 @@ For example, Get-Service wmi | Start-Service ``` -The cmdlets that get and set objects of the Windows PowerShell providers, such as the +The cmdlets that get and set objects of the PowerShell providers, such 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` command in the -Windows PowerShell registry provider to the `New-ItemProperty` cmdlet. This command adds -a new registry entry, NoOfEmployees, with a value of 8124, to the MyCompany registry key. +For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` +command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. +This command adds a new registry entry, NoOfEmployees, with a value of 8124, +to the MyCompany registry key. For example, ```powershell -Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 +Get-Item -Path HKLM:\Software\MyCompany | + New-ItemProperty -Name NoOfEmployees -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 any objects to -these cmdlets. +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 any 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. +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. For example, + ```powershell Get-Process | Sort-Object -Property handles ``` -Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and -`Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out -cmdlets, such as `Out-Printer`. +Also, you can pipe any objects to the formatting cmdlets, such as +`Format-List` 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. +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. For example, + ```powershell Get-Process winlogon | Format-List -Property * ``` -With a bit of practice, you'll find that combining simple commands into pipelines -saves time and typing, and makes your scripting more efficient. +With a bit of practice, you'll find that combining simple commands into +pipelines 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 command +to another command, PowerShell tries to associate the piped objects with one +of the parameters of the receiving cmdlet. -When you "pipe" objects, that is send the objects in the output of one command 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 associates input objects -with cmdlet parameters, tries to find a parameter that meets the following criteria: +To do so, the PowerShell "parameter binding" component, which associates 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 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 `-InputObject` 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`. +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 `-InputObject` 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 PowerShell prompts you -for the missing parameter values. +If the parameter binding component of PowerShell cannot associate the piped +objects with a parameter of the receiving cmdlet, the command fails and +PowerShell prompts you for the missing parameter values. -You cannot force the parameter binding component to associate the piped objects with a particular -parameter -- you cannot even suggest a parameter. Instead, the logic of the component manages -the piping as efficiently as possible. +You cannot force the parameter binding component to associate the piped +objects with a particular parameter. You cannot even suggest a parameter. +Instead, the logic of the 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. -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: +For example, piping objects representing the services on the computer to a +`Format-Table` command, such as: ```powershell Get-Service | Format-Table -Property name, dependentservices ``` -is much like saving the service objects in a variable and using the InputObject parameter -of `Format-Table` to submit the service object. +is much like saving the service objects in a variable and using the +InputObject parameter of `Format-Table` to submit the service object. For example, + ```powershell $services = Get-Service Format-Table -InputObject $services -Property name, dependentservices @@ -236,51 +234,58 @@ Format-Table -InputObject $services -Property name, dependentservices or imbedding the command in the parameter value For example, + ```powershell -Format-Table -InputObject (Get-Service wmi) -Property name, dependentservices +Format-Table -InputObject (Get-Service wmi) -Property name,dependentservices ``` -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 you use a -command parameter, the objects are sent as a single array object. +However, there is an important difference. When you pipe multiple objects to a +command, PowerShell sends the objects to the command one at a time. When you +use a command parameter, the objects are sent as a single array object. + +This seemingly technical difference can have interesting, and sometimes +useful, consequences. -This seemingly technical difference can have interesting, and sometimes useful, consequences. +For example, if you pipe multiple process objects from the `Get-Process` +cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one +at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the +process objects, and their properties and methods. -For example, if you pipe multiple process objects from the `Get-Process` cmdlet 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 their properties and methods. -(`Get-Member` eliminates duplicates, so if the objects are all of the same type, it displays only -one object type.) +NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the +same type, it displays only one object type. -In this case, `Get-Member` displays the properties and methods of each process object, that is, a -System.Diagnostics.Process object. +In this case, `Get-Member` displays the properties and methods of each process +object, that is, a System.Diagnostics.Process object. For example, + ```powershell Get-Process | Get-Member ``` -``` +```Output TypeName: System.Diagnostics.Process -Name MemberType Definition ----- ---------- ---------- -Handles AliasProperty Handles = Handlecount -Name AliasProperty Name = ProcessName -NPM AliasProperty NPM = NonpagedSystemMemorySize +Name MemberType Definition +---- ---------- ---------- +Handles AliasProperty Handles = Handlecount +Name AliasProperty Name = ProcessName +NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then `Get-Member` receives an -array of System.Diagnostics.Process objects as a single unit, and it displays the properties -of an array of objects. (Note the array symbol ([]) after the System.Object type name.) +However, if you use the InputObject parameter of `Get-Member`, then +`Get-Member` receives an array of System.Diagnostics.Process objects as a +single unit, and it displays the properties of an array of objects. (Note the +array symbol ([]) after the System.Object type name.) For example, + ```powershell Get-Member -InputObject (Get-Process) ``` -``` +```Output TypeName: System.Object[] Name MemberType Definition @@ -291,30 +296,32 @@ Clone Method System.Object Clone() ... ``` -This result might not be what you intended, but after you understand it, you 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. +This result might not be what you intended, but after you understand it, you +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. For example, + ```powershell (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. +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** or **Parameter** -parameters to determine which, if any, of a cmdlet's parameters 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** or **Parameter** parameters to determine which, if any, of a +cmdlet's parameters accepts pipeline input. -In the `Get-Help` default display, the "Accept 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. +In the `Get-Help` default display, the "Accept 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` cmdlet accepts -pipeline input, type: +For example, to determine which of the parameters of the `Start-Service` +cmdlet accepts pipeline input, type: ```powershell Get-Help Start-Service -Full @@ -326,108 +333,115 @@ or Get-Help Start-Service -Parameter * ``` -For example, the help for the `Start-Service` cmdlet shows that the **InputObject** and **Name** -parameters accept pipeline input ("true"). All other parameters have a value of "false" -in the "Accept pipeline input?" row. +For example, the help for the `Start-Service` cmdlet shows that the +**InputObject** and **Name** parameters accept pipeline input ("true"). All +other parameters have a value of "false" in the "Accept pipeline input?" row. ``` -InputObject - 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. +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? true - Position? 0 - Default value None - Accept pipeline input? True (ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByValue) +Accept wildcard characters? false -Name - Specifies the service names for the service to be started. +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. +The parameter name is optional. You can use Name or its alias, ServiceName, +or you can omit the parameter name. - Required? true - Position? 0 - Default value None - Accept pipeline input? True (ByPropertyName, ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByPropertyName, ByValue) +Accept wildcard characters? false ``` This means that you can send objects (PsObjects) through the pipeline to the -`Where-Object` cmdlet and Windows PowerShell will associate the object with the +`Where-Object` cmdlet and PowerShell will associate the object with the **InputObject** and **Name** parameters. ### 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 objects -that have the same .NET type as their parameter value or objects that can 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. + that have the same .NET type as their parameter value or objects that can be + converted to that type. -- ByPropertyName: Parameters that accept input "by property name" can accept piped -objects only when a property of the object has the same name as the parameter. + 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. -For example, the Name parameter of `Start-Service` can accept objects that have -a Name property. +- ByPropertyName: Parameters that accept input "by property name" can accept + piped objects only when a property of the object has the same name as the + parameter. -(To list the properties of an object, pipe it to `Get-Member`.) + For example, the Name parameter of `Start-Service` can accept objects that + 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 parameters are -designed to take input from the pipeline easily. +Some parameters can accept objects by value or by property name. These +parameters 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 failure and -rewrite the command. +If a command fails because of a pipeline error, you can investigate the +failure 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 destination path and -then piping the path to the `Move-ItemProperty` cmdlet. +registry key to another by using the `Get-Item` cmdlet to get the destination +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. The `Move-ItemProperty` -command specifies the current path and name of the registry entry to be moved. +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. The `Move-ItemProperty` command specifies the +current path and name of the registry entry to be moved. For example, + ```powershell 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 +The command fails and 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 pipeline input. +```output +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 +pipeline input. At line:1 char:23 -+ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name product ++ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name p ``` -To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of -Windows PowerShell. The following command traces the Parameter Binding component 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 reference. +To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding +component of PowerShell. The following command traces the Parameter Binding +component 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 reference. For example, + ```powershell -Trace-Command -Name parameterbinding -Expression {Get-Item -Path HKLM:\software\mycompany\sales | -Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} -PSHost -FilePath debug.txt +Trace-Command -Name parameterbinding -Expression { + Get-Item -Path HKLM:\software\mycompany\sales | + Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} ` + -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. +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`] @@ -442,31 +456,35 @@ 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 parameter -of `Move-ItemProperty` failed. +Finally, it shows that the attempt to bind the path to the **Destination** +parameter 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 ValueFromPipelineByPropertyName NO COERCION -Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION +Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyName NO CO +ERCION +Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COE +RCION ... +``` - -To investigate the failure, use the `Get-Help` cmdlet to view the attributes of the -**Destination** parameter. The following command gets detailed information about the -**Destination** parameter. +To investigate the failure, use the `Get-Help` cmdlet to view the attributes +of the **Destination** parameter. The following command gets detailed +information about the **Destination** parameter. ```powershell Get-Help Move-ItemProperty -Parameter Destination ``` -The results show that **Destination** takes pipeline input only "by property name". -That is, the piped object must have a property named Destination. +The results show that **Destination** takes pipeline input only "by property +name". That is, the piped object must have a property named Destination. ``` -Destination @@ -479,11 +497,12 @@ That is, the piped object must have a property named Destination. Accept wildcard characters? false ``` -To see the properties of the object being piped to the `Move-ItemProperty` cmdlet, -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. +To see the properties of the object being piped to the `Move-ItemProperty` +cmdlet, 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. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` @@ -491,11 +510,13 @@ 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-ItemProperty` cmdlet. We can -use a `Get-ItemProperty` command to get the path, but the name and destination must be specified -in the `Move-ItemProperty` part of the command. +To fix the command, we must specify the destination in the `Move-ItemProperty` +cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name +and destination must be specified in the `Move-ItemProperty` part of the +command. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\design | Move-ItemProperty -Dest HKLM:\software\mycompany\design -Name product @@ -510,9 +531,11 @@ Get-Itemproperty HKLM:\software\mycompany\sales The results show that the Product registry entry was moved to the Sales key. -``` -PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany\sales -PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany +```Output +PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany\sales +PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany PSChildName : sales PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Object_Creation.md b/reference/6/Microsoft.PowerShell.Core/About/about_Object_Creation.md index 65a910c9ccab..0f745ac3aa94 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Object_Creation.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Object_Creation.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,232 +7,246 @@ title: about_Object_Creation --- # About Object Creation -## about_Object_Creation - ## SHORT DESCRIPTION -Explains how to create objects in Windows PowerShell. +Explains how to create objects in PowerShell. ## LONG DESCRIPTION -You can create objects in Windows PowerShell and use the objects that you create in commands and scripts. - -There are several ways to create objects: - -New-Object: -The New-Object cmdlet creates an instance of a .NET Framework object or COM object. +You can create objects in PowerShell and use the objects that you create in +commands and scripts. -Hash tables: +There are several ways to create objects: -Beginning in Windows PowerShell 3.0, you can create objects from hash tables of property names and property values. +- `New-Object`: This cmdlet creates an instance of a .NET Framework object or + COM object. -Import-Csv: +- Hash tables: Beginning in PowerShell 3.0, you can create objects + from hash tables of property names and property values. -The Import-Csv cmdlet creates custom objects (PSCustomObject) from the items in a CSV file. Each row is an object instance and each column is an object property. +- `Import-Csv`: This cmdlet creates custom objects (PSCustomObject) from the + items in a CSV file. Each row is an object instance and each column is an + object property. This topic will demonstrate and discuss each of these methods. - ## NEW-OBJECT -The New-Object cmdlet provides a robust and consistent way to create new objects. The cmdlet works with almost all types and in all supported versions of Windows PowerShell. -To create a new object, specify either the type of a .NET Framework class or a ProgID of a COM object. +The `New-Object` cmdlet provides a robust and consistent way to create new +objects. The cmdlet works with almost all types and in all supported versions +of PowerShell. -For example, the following command creates a Version object. +To create a new object, specify either the type of a .NET Framework class or a +ProgID of a COM object. +For example, the following command creates a Version object. -``` -PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 +```powershell +PS C:\> $v = New-Object -TypeName System.Version -ArgumentList 2.0.0.1 PS C:\> $v ``` - - -``` -Major Minor Build Revision ------ ----- ----- -------- +```Output +Major Minor Build Revision +----- ----- ----- -------- 2 0 0 1 ``` +```powershell +PS C:\> $v | Get-Member - -``` -PS C:\> $v | Get-Member - TypeName: System.Version ``` - For more information, see the help topic for the New-Object cmdlet. - ### CREATE OBJECTS FROM HASH TABLES -Beginning in Windows PowerShell 3.0, you can create an object from a hash table of properties and property values. -The syntax is as follows: +Beginning in PowerShell 3.0, you can create an object from a hash table of +properties and property values. +The syntax is as follows: ``` -[]@{=;=} +[]@{ + = + = +} ``` - -This method works only for classes that have a null constructor, that is, a constructor that has no parameters. The object properties must be public and settable. - +This method works only for classes that have a null constructor, that is, a +constructor that has no parameters. The object properties must be public and +settable. ### CREATE CUSTOM OBJECTS FROM HASH TABLES -Custom objects are very useful and they are very easy to create by using the hash table method. To create a custom object, use the PSCustomObject class, a class designed specifically for this purpose. - -Custom objects are an excellent way to return customized output from a function or script; far more useful than returning formatted output that cannot be reformatted or piped to other commands. - -The commands in the Test-Object function set some variable values and then use those values to create a custom object. (You can see this object in use in the example section of the Update-Help cmdlet help topic.) - -``` -function Test-Object -{ $ModuleName = "PSScheduledJob" - $HelpCulture = "en-us" - $HelpVersion = "3.1.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} - - $ModuleName = "PSWorkflow" - $HelpCulture = "en-us" - $HelpVersion = "3.0.0.0" - [PSCustomObject]@{"ModuleName"=$ModuleName; "UICulture"=$HelpCulture; "Version"=$HelpVersion} +Custom objects are very useful and they are very easy to create by using the +hash table method. To create a custom object, use the PSCustomObject class, a +class designed specifically for this purpose. + +Custom objects are an excellent way to return customized output from a +function or script; far more useful than returning formatted output that +cannot be reformatted or piped to other commands. + +The commands in the `Test-Object function` set some variable values and then +use those values to create a custom object. You can see this object in use in +the example section of the `Update-Help` cmdlet help topic. + +```powershell +function Test-Object { + $ModuleName = "PSScheduledJob" + $HelpCulture = "en-us" + $HelpVersion = "3.1.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } + $ModuleName = "PSWorkflow" + $HelpCulture = "en-us" + $HelpVersion = "3.0.0.0" + [PSCustomObject]@{ + "ModuleName"=$ModuleName + "UICulture"=$HelpCulture + "Version"=$HelpVersion + } } ``` +The output of this function is a collection of custom objects formatted as a +table by default. -The output of this function is a collection of custom objects formatted as a table by default. - +```powershell +PS C:\> Test-Object -``` -PS C:\> Test-Object - -ModuleName UICulture Version ---------- --------- ------- -PSScheduledJob en-us 3.1.0.0 +ModuleName UICulture Version +--------- --------- ------- +PSScheduledJob en-us 3.1.0.0 PSWorkflow en-us 3.0.0.0 ``` +Users can manage the properties of the custom objects just as they do with +standard objects. -Users can manage the properties of the custom objects just as they do with standard objects. - - -``` -PS C:\> (Test-Object).ModuleName - PSScheduledJob +```powershell +PS C:\> (Test-Object).ModuleName + PSScheduledJob PSWorkflow ``` - - #### CREATE NON-CUSTOM OBJECTS FROM HASH TABLES -You can also use hash tables to create objects for non-custom classes. When you create an object for a non-custom class, the full namespace name is required unless class is in the System namespace. Use only the properties of the class. -For example, the following command creates a session option object. +You can also use hash tables to create objects for non-custom classes. When +you create an object for a non-custom class, the full namespace name is +required unless class is in the System namespace. Use only the properties of +the class. +For example, the following command creates a session option object. +```powershell +[System.Management.Automation.Remoting.PSSessionOption]@{ + IdleTimeout=43200000 + SkipCnCheck=$True +} ``` -[System.Management.Automation.Remoting.PSSessionOption]@{IdleTimeout=43200000; SkipCnCheck=$True} -``` - -The requirements of the hash table feature, especially the null constructor requirement, eliminate many existing classes. However, most Windows PowerShell option classes are designed to work with this feature, as well as other very useful classes, such as the ScheduledJobTrigger class. +The requirements of the hash table feature, especially the null constructor +requirement, eliminate many existing classes. However, most PowerShell option +classes are designed to work with this feature, as well as other very useful +classes, such as the ScheduledJobTrigger class. +```powershell +[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{ + Frequency="Daily" + At="15:00" +} -``` -[Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger]@{Frequency="Daily";At="15:00"} - -Id Frequency Time DaysOfWeek Enabled --- --------- ---- ---------- ------- -0 Daily 6/6/2012 3:00:00 PM True +Id Frequency Time DaysOfWeek Enabled +-- --------- ---- ---------- ------- +0 Daily 6/6/2012 3:00:00 PM True ``` +You can also use the hash table feature when setting parameter values. For +example, the value of the **SessionOption** parameter of the New-PSSession +cmdlet and the value of the JobTrigger parameter of `Register-ScheduledJob` +can be a hash table. -You can also use the hash table feature when setting parameter values. For example, the value of the SessionOption parameter of the New-PSSession cmdlet and the value of the JobTrigger parameter of Register-ScheduledJob can be a hash table. - - -``` -New-PSSession -ComputerName Server01 -SessionOption @{IdleTimeout=43200000; SkipCnCheck=$True} -Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{Frequency="Daily";At="15:00"} +```powershell +New-PSSession -ComputerName Server01 -SessionOption @{ + IdleTimeout=43200000 + SkipCnCheck=$True +} +Register-ScheduledJob Name Test -FilePath .\Get-Inventory.ps1 -Trigger @{ + Frequency="Daily" + At="15:00" +} ``` - - ### IMPORT-CSV -You can create custom objects from the items in a CSV file. When you use the Import-Csv cmdlet to import the CSV file, the cmdlet creates a custom object (PSCustomObject) for each item in the file. The column names are the object properties. -For example, if you import a CSV file of computer asset data, Import-CSV creates a collection of custom objects from the input. +You can create custom objects from the items in a CSV file. When you use the +`Import-Csv` cmdlet to import the CSV file, the cmdlet creates a custom object +(PSCustomObject) for each item in the file. The column names are the object +properties. +For example, if you import a CSV file of computer asset data, `Import-CSV` +creates a collection of custom objects from the input. ``` -#In Servers.csv -AssetID, Name, OS, Department -003, Server01, Windows Server 2012, IT -103, Server33, Windows 7, Marketing +#In Servers.csv +AssetID, Name, OS, Department +003, Server01, Windows Server 2012, IT +103, Server33, Windows 7, Marketing 212, Server35, Windows 8, Finance ``` +```powershell +PS C:\> $a = Import-Csv Servers.csv +PS C:\> $a - -``` -PS C:\> $a = Import-Csv Servers.csv -PS C:\> $a - -AssetID Name OS Department -------- ---- -- ---------- -003 Server01 Windows Server 2012 IT -103 Server33 Windows 7 Marketing +AssetID Name OS Department +------- ---- -- ---------- +003 Server01 Windows Server 2012 IT +103 Server33 Windows 7 Marketing 212 Server35 Windows 8 Finance ``` - Use the Get-Member cmdlet to confirm the object type. - -``` +```powershell PS C:\> $a | Get-Member ``` +```Output +TypeName: System.Management.Automation.PSCustomObject - -``` -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() -AssetID NoteProperty System.String AssetID=003 -Department NoteProperty System.String Department=IT -Name NoteProperty System.String Name=Server01 +Name MemberType Definition +---- ---------- ---------- +Equals Method bool Equals(System.Object obj) +GetHashCode Method int GetHashCode() +GetType Method type GetType() +ToString Method string ToString() +AssetID NoteProperty System.String AssetID=003 +Department NoteProperty System.String Department=IT +Name NoteProperty System.String Name=Server01 OS NoteProperty System.String OS=Windows Server 2012 ``` - You can use the custom objects just as you would standard objects. - -``` +```powershell PS C:\> $a | where {$_.OS -eq "Windows 8"} ``` - - -``` -AssetID Name OS Department -------- ---- -- ---------- +```output +AssetID Name OS Department +------- ---- -- ---------- 212 Server35 Windows 8 Finance ``` - For more information, see the help topic for the Import-Csv cmdlet. - ## SEE ALSO [about_Objects](about_Objects.md) @@ -243,9 +257,8 @@ For more information, see the help topic for the Import-Csv cmdlet. [about_Pipelines](about_Pipelines.md) -Get-Member - -Import-Csv +[Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) -New-Object +[Import-Csv](../../Microsoft.PowerShell.Utility/Import-Csv.md) +[New-Object](../../Microsoft.PowerShell.Utility/New-Object.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Objects.md b/reference/6/Microsoft.PowerShell.Core/About/about_Objects.md index 88ab499af532..58308cabd6d7 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Objects.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Objects.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -58,20 +58,13 @@ directory objects are passed down the pipeline to the second command. The second command `where { $_.PsIsContainer -eq $false }` uses the PsIsContainer property of all file system objects to select only -files, which have a value of False ($false) in their PsIsContainer +files, which have a value of False (\$false) in their PsIsContainer property. Folders, which are containers and, thus, have a value of -True ($true) in their PsIsContainer property, are not selected. +True (\$true) in their PsIsContainer property, are not selected. The second command passes only the file objects to the third command `Format-List`, which displays the file objects in a list. -## For More Information - -Now that you understand a bit about objects, see the [about_Methods](about_Methods.md) -help topic to learn how to find and use object methods, the -[about_Properties](about_Properties.md) topic to learn how to find and use object properties, -and the [Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) topic, to learn how to find an object type. - ## See Also [about_Methods](about_Methods.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md b/reference/6/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md index 6e83191b889c..01d129ccc4bb 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Operator_Precedence.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -10,84 +10,85 @@ title: about_Operator_Precedence ## SHORT DESCRIPTION -Lists the Windows PowerShell operators in precedence order. +Lists the PowerShell operators in precedence order. -[This topic was contributed by Kirk Munro, a Windows PowerShell MVP +[This topic was contributed by Kirk Munro, a PowerShell MVP from Ottawa, Ontario] ## LONG DESCRIPTION -Windows PowerShell operators let you construct simple, but powerful -expressions. This topic lists the operators in precedence order. -Precedence order is the order in which Windows PowerShell evaluates -the operators when multiple operators appear in the same expression. - -When operators have equal precedence, Windows PowerShell evaluates -them from left to right. The exceptions are the assignment operators, -the cast operators, and the negation operators (!, -not, -bnot), -which are evaluated from right to left. - -You can use enclosures, such as parentheses, to override the -standard precedence order and force Windows PowerShell to evaluate -the enclosed part of an expression before an unenclosed part. - -In the following list, operators are listed in the order that they -are evaluated. Operators on the same line, or in the same group, have -equal precedence. - -The Operator column lists the operators. The Reference column lists -the Windows PowerShell Help topic in which the operator is described. -To display the topic, type `get-help `. - -|OPERATOR|REFERENCE| -|--------|---------| -|`$() @()`|[about_Operators](#index-operator)| -|`.` (dereference) `::` (static)|[about_Operators](about_Operators.md)| -|`[0]` (index operator)|[about_Operators](about_Operators.md)| +PowerShell operators let you construct simple, but powerful +expressions. This topic lists the operators in precedence order. Precedence +order is the order in which PowerShell evaluates the operators when +multiple operators appear in the same expression. + +When operators have equal precedence, PowerShell evaluates them from +left to right. The exceptions are the assignment operators, the cast +operators, and the negation operators (!, -not, -bnot), which are evaluated +from right to left. + +You can use enclosures, such as parentheses, to override the standard +precedence order and force PowerShell to evaluate the enclosed part of +an expression before an unenclosed part. + +In the following list, operators are listed in the order that they are +evaluated. Operators on the same line, or in the same group, have equal +precedence. + +The Operator column lists the operators. The Reference column lists the +PowerShell Help topic in which the operator is described. To display +the topic, type `get-help `. + +|OPERATOR |REFERENCE| +|------------------------|---------| +|`$() @()` |[about_Operators](#index-operator)| +|`.` (dereference) |[about_Operators](about_Operators.md)| +|`::` (static) |[about_Operators](about_Operators.md)| +|`[0]` (index operator) |[about_Operators](about_Operators.md)| |`[int]` (cast operators)|[about_Operators](about_Operators.md)| -|`-split` (unary)
`-join` (unary)|[about_Split](about_Split.md)
[about_Join](about_Join.md)| -|`,` (comma operator)|[about_Operators](about_Operators.md)| -|`++ --`|[about_Assignment_Operators](about_Assignment_Operators.md)| -|`-not`
`! -bNot`|[about_Logical_Operators](about_logical_operators.md)
[about_Comparison_Operators](about_Comparison_Operators.md)| -|`..` (range operator)|[about_Operators](about_Operators.md)| -|`-f` (format operator)|[about_Operators](about_Operators.md)| -|`* / %`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`+ -`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| - - -The following group of operators have equal precedence. Their -case-sensitive and explicitly case-insensitive variants have -the same precedence. - -|OPERATOR|REFERENCE| -|--------|---------| -|`-split` (unary)|[about_Split](about_Split.md)| -|`-join` (unary)|[about_Join](about_Join.md)| -|`-is -isnot -as`|[about_Type_Operators](about_Type_Operators.md)| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`,` (comma operator) |[about_Operators](about_Operators.md)| +|`++ --` |[about_Assignment_Operators](about_Assignment_Operators.md)| +|`-not` |[about_Logical_Operators](about_logical_operators.md)| +|`! -bNot` |[about_Comparison_Operators](about_Comparison_Operators.md)| +|`..` (range operator) |[about_Operators](about_Operators.md)| +|`-f` (format operator) |[about_Operators](about_Operators.md)| +|`* / % + -` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| + +The following group of operators have equal precedence. Their case-sensitive +and explicitly case-insensitive variants have the same precedence. + +|OPERATOR |REFERENCE| +|-------------------------|---------| +|`-split` (unary) |[about_Split](about_Split.md)| +|`-join` (unary) |[about_Join](about_Join.md)| +|`-is -isnot -as` |[about_Type_Operators](about_Type_Operators.md)| |`-eq -ne -gt -gt -lt -le`|[about_Comparison_Operators](about_Comparison_Operators.md)| -|`-like -notlike`|[about_comparison_operators](about_comparison_operators.md)| -|`-match -notmatch`|[about_comparison_operators](about_comparison_operators.md)| -|`-in -notIn`|[about_comparison_operators](about_comparison_operators.md)| -|`-contains -notContains`|[about_comparison_operators](about_comparison_operators.md)| -|`-replace`|[about_comparison_operators](about_comparison_operators.md)| +|`-like -notlike` |[about_comparison_operators](about_comparison_operators.md)| +|`-match -notmatch` |[about_comparison_operators](about_comparison_operators.md)| +|`-in -notIn` |[about_comparison_operators](about_comparison_operators.md)| +|`-contains -notContains` |[about_comparison_operators](about_comparison_operators.md)| +|`-replace` |[about_comparison_operators](about_comparison_operators.md)| The list resumes here with the following operators in precedence order: -|OPERATOR|REFERENCE| -|--------|---------| -|`-band -bor -bxor`|[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| -|`-and -or -xor`|[about_comparison_operators](about_comparison_operators.md)| -|`.` (dot-source)
`&` (call)|[about_Scopes](about_Scopes.md)
[about_Operators](about_Operators.md)| +|OPERATOR |REFERENCE| +|--------------------------|---------| +|`-band -bor -bxor` |[about_Arithmetic_Operators](about_Arithmetic_Operators.md)| +|`-and -or -xor` |[about_comparison_operators](about_comparison_operators.md)| +|`.` (dot-source) |[about_Scopes](about_Scopes.md)| +|`&` (call) |[about_Operators](about_Operators.md)| || (pipeline operator)|[about_Operators](about_Operators.md)| -|`> >> 2> 2>> 2>&1`|[about_Redirection](about_Redirection.md)| -|`= += -= *= /= %=`|[about_Assignment_Operators](about_Assignment_Operators.md)| +|`> >> 2> 2>> 2>&1` |[about_Redirection](about_Redirection.md)| +|`= += -= *= /= %=` |[about_Assignment_Operators](about_Assignment_Operators.md)| # EXAMPLES -The following two commands show the arithmetic operators and -the effect of using parentheses to force Windows PowerShell to -evaluate the enclosed part of the expression first. +The following two commands show the arithmetic operators and the effect of +using parentheses to force PowerShell to evaluate the enclosed part of +the expression first. ```powershell C:\PS> 2 + 3 * 4 @@ -97,8 +98,8 @@ C:\PS> (2 + 3) * 4 20 ``` -The following example gets the read-only text files from the local -directory and saves them in the `$read_only` variable. +The following example gets the read-only text files from the local directory +and saves them in the `$read_only` variable. ```powershell $read_only = get-childitem *.txt | where-object {$_.isReadOnly} @@ -109,37 +110,37 @@ It is equivalent to the following example. $read_only = ( get-childitem *.txt | where-object {$_.isReadOnly} ) ``` -Because the pipeline operator (|) has a higher precedence than the -assignment operator (=), the files that the Get-ChildItem cmdlet -gets are sent to the Where-Object cmdlet for filtering before they -are assigned to the $read_only variable. +Because the pipeline operator (|) has a higher precedence than the assignment +operator (=), the files that the Get-ChildItem cmdlet gets are sent to the +Where-Object cmdlet for filtering before they are assigned to the $read_only +variable. -The following example demonstrates that the index operator takes -precedence over the cast operator. +The following example demonstrates that the index operator takes precedence +over the cast operator. -The first expression creates an array of three strings. Then, it -uses the index operator with a value of 0 to select the first object -in the array, which is the first string. Finally, it casts the -selected object as a string. In this case, the cast has no effect. +The first expression creates an array of three strings. Then, it uses the +index operator with a value of 0 to select the first object in the array, +which is the first string. Finally, it casts the selected object as a string. +In this case, the cast has no effect. ```powershell C:\PS> [string]@('Windows','PowerShell','2.0')[0] Windows ``` -The second expression uses parentheses to force the cast operation -to occur before the index selection. As a result, the entire array -is cast as a (single) string. Then, the index operator selects -the first item in the string array, which is the first character. +The second expression uses parentheses to force the cast operation to occur +before the index selection. As a result, the entire array is cast as a +(single) string. Then, the index operator selects the first item in the string +array, which is the first character. ```powershell C:\PS> ([string]@('Windows','PowerShell','2.0'))[0] W ``` -In the following example, because the -gt (greater-than) operator -has a higher precedence than the -and (logical AND) operator, the -result of the expression is FALSE. +In the following example, because the -gt (greater-than) operator has a higher +precedence than the -and (logical AND) operator, the result of the expression +is FALSE. ```powershell C:\PS> 2 -gt 4 -and 1 @@ -160,11 +161,11 @@ C:\PS> 2 -gt (4 -and 1) True ``` -However, this example demonstrates an important principle of managing -operator precedence. When an expression is difficult for people to -interpret, use parentheses to force the evaluation order, even when it -forces the default operator precedence. The parentheses make your -intentions clear to people who are reading and maintaining your scripts. +However, this example demonstrates an important principle of managing operator +precedence. When an expression is difficult for people to interpret, use +parentheses to force the evaluation order, even when it forces the default +operator precedence. The parentheses make your intentions clear to people who +are reading and maintaining your scripts. ## SEE ALSO @@ -185,4 +186,3 @@ intentions clear to people who are reading and maintaining your scripts. [about_Split](about_Split.md) [about_Type_Operators](about_Type_Operators.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_PackageManagement.md b/reference/6/Microsoft.PowerShell.Core/About/about_PackageManagement.md index 86512bc2df24..7933f7f0a80e 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_PackageManagement.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_PackageManagement.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,87 +7,81 @@ title: about_PackageManagement --- # About PackageManagement -## about_PackageManagement -# TOPIC -about_PackageManagement - -# SHORT DESCRIPTION +## SHORT DESCRIPTION PackageManagement is an aggregator for software package managers. -# LONG DESCRIPTION +## LONG DESCRIPTION PackageManagement functionality was introduced in Windows PowerShell 5.0. -PackageManagement is a unified interface for software package management systems; you -can run PackageManagement cmdlets to perform software discovery, installation, and -inventory (SDII) tasks. Regardless of the underlying installation technology, -you can run the common cmdlets in the PackageManagement module to search for, -install, or uninstall packages; add, remove, and query package repositories; and -run queries on a computer to determine which software packages are installed. - -PackageManagement supports a flexible plug-in model that enables support for other -software package management systems. - -The PackageManagement module is included with Windows PowerShell 5.0 and later releases -of Windows PowerShell, and works on three levels of package management -structure: package providers, package sources, and the packages themselves. - -Term Description ----------- ------------------------------ -Package manager Software package management system. In -PackageManagement terms, this is a package provider. -Package provider PackageManagement term for a package manager. Examples -can include Windows Installer, Chocolatey, -and others. -Package source A URL, local folder, or network shared folder that -you configure package providers to use as a -repository. -Package A piece of software that a package provider manages, -and that is stored in a specific package source. - -The PackageManagement module includes the following cmdlets. You can find the -Help for these cmdlets on TechNet starting on the following page: -http://technet.microsoft.com/library/dn890951(v=wps.640).aspx. - -Cmdlet Description ----------- ------------------------------ -Get-PackageProvider Returns a list of package providers that are -connected to PackageManagement. -Get-PackageSource Gets a list of package sources that are -registered for a package provider. -Register-PackageSource Adds a package source for a specified -package provider. -Set-PackageSource Sets properties on an existing package -source. -Unregister-PackageSource Removes a registered package source. -Get-Package Returns a list of installed software -packages. -Find-Package Finds software packages in available -package sources. -Install-Package Installs one or more software packages. -Save-Package Saves packages to the local computer -without installing them. -Uninstall-Package Uninstalls one or more software packages. - -PackageManagement Package Provider Bootstrapping and Dynamic Cmdlet Parameters - -By default, PackageManagement ships with a core bootstrap provider. You can install -additional package providers as you need them by bootstrapping the providers; -that is, responding to a prompt to install the provider automatically, from a -web service. You can specify a package provider with any PackageManagement cmdlet; -if the specified provider is not available, PackageManagement prompts you to bootstrap ---or automatically install--the provider. In the following examples, if the -Chocolatey provider is not already installed, PackageManagement bootstrapping installs -the provider. - +PackageManagement is a unified interface for software package management +systems; you can run PackageManagement cmdlets to perform software discovery, +installation, and inventory (SDII) tasks. Regardless of the underlying +installation technology, you can run the common cmdlets in the +PackageManagement module to search for, install, or uninstall packages; add, +remove, and query package repositories; and run queries on a computer to +determine which software packages are installed. + +PackageManagement supports a flexible plug-in model that enables support for +other software package management systems. + +The PackageManagement module is included with Windows PowerShell 5.0 and later +releases of Windows PowerShell, and works on three levels of package +management structure: package providers, package sources, and the packages +themselves. Let us define some terms: + +- Package manager: Software package management system. In PackageManagement + terms, this is a package provider. +- Package provider: PackageManagement term for a package manager. Examples can + include Windows Installer, Chocolatey, and others. +- Package source: A URL, local folder, or network shared folder that you + configure package providers to use as a repository. +- Package: A piece of software that a package provider manages, and that is + stored in a specific package source. + +The PackageManagement module includes the following cmdlets. For more +information, see the +[PackageManagement](/powershell/gallery/psget/oneget/packagemanagement_cmdlets) +help. + +- `Get-PackageProvider`: Returns a list of package providers that are + connected to PackageManagement. +- `Get-PackageSource`: Gets a list of package sources that are registered for + a package provider. +- `Register-PackageSource`: Adds a package source for a specified package + provider. +- `Set-PackageSource`: Sets properties on an existing package source. +- `Unregister-PackageSource`: Removes a registered package source. +- `Get-Package`: Returns a list of installed software packages. +- `Find-Package`: Finds software packages in available package sources. +- `Install-Package`: Installs one or more software packages. +- `Save-Package`: Saves packages to the local computer without installing + them. +- `Uninstall-Package`: Uninstalls one or more software packages. + +### Package Provider Bootstrapping and Dynamic Cmdlet Parameters + +By default, PackageManagement ships with a core bootstrap provider. You can +install additional package providers as you need them by bootstrapping the +providers; that is, responding to a prompt to install the provider +automatically, from a web service. You can specify a package provider with any +PackageManagement cmdlet; if the specified provider is not available, +PackageManagement prompts you to bootstrap (or automatically install) the +provider. In the following examples, if the Chocolatey provider is not already +installed, PackageManagement bootstrapping installs the provider. + +```powershell Find-Package -Provider Chocolatey +``` If the Chocolatey provider is not already installed, when you run the preceding command, you are prompted to install it. +```powershell Install-Package -ForceBootstrap +``` If the Chocolatey provider is not already installed, when you run the preceding command, the provider is installed; but because the ForceBootstrap @@ -99,10 +93,10 @@ provider installed, and you do not add the ForceBootstrap parameter to your command, PackageManagement prompts you to install the provider. Specifying a package provider in your PackageManagement command can make -dynamic parameters available that are specific to that package provider. -When you run Get-Help for a specific PackageManagement cmdlet, a list of -parameter sets are returned, grouping dynamic parameters for available -package providers in separate parameter sets. +dynamic parameters available that are specific to that package provider. When +you run Get-Help for a specific PackageManagement cmdlet, a list of parameter +sets are returned, grouping dynamic parameters for available package providers +in separate parameter sets. More Information About the PackageManagement Project @@ -131,4 +125,3 @@ Install-Package Save-Package Uninstall-Package - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md b/reference/6/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md index 871bcb0dd4f2..e9c4ebaefa98 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,449 +7,409 @@ title: about_Parameters_Default_Values --- # About Parameters Default Values -## about_Parameters_Default_Values - ## SHORT DESCRIPTION -Describes how to set custom default values for the parameters of cmdlets and advanced functions. +Describes how to set custom default values for the parameters of cmdlets and +advanced functions. ## LONG DESCRIPTION -The $PSDefaultParameterValues preference variable lets you specify custom default values for any cmdlet or advanced function. Cmdlets and functions use the custom default value unless you specify another value in the command. -The authors of cmdlets and advanced functions set standard default values for their parameters. Typically, the standard default values are useful, but they might not be appropriate for all environments. +The \$PSDefaultParameterValues preference variable lets you specify custom +default values for any cmdlet or advanced function. Cmdlets and functions use +the custom default value unless you specify another value in the command. + +The authors of cmdlets and advanced functions set standard default values for +their parameters. Typically, the standard default values are useful, but they +might not be appropriate for all environments. -This feature is especially useful when you must specify the same alternate parameter value nearly every time you use the command or when a particular parameter value is difficult to remember, such as an e-mail server name or project GUID. +This feature is especially useful when you must specify the same alternate +parameter value nearly every time you use the command or when a particular +parameter value is difficult to remember, such as an e-mail server name or +project GUID. -If the desired default value varies predictably, you can specify a script block that provides different default values for a parameter under different conditions. +If the desired default value varies predictably, you can specify a script +block that provides different default values for a parameter under different +conditions. -$PSDefaultParameterValues was introduced in Windows PowerShell 3.0. +\$PSDefaultParameterValues was introduced in PowerShell 3.0. +## SYNTAX -### SYNTAX The syntax of the $PSDefaultParameterValues preference variable is as follows: +```powershell +$PSDefaultParameterValues=@{":"=""} + +$PSDefaultParameterValues=@{":"={}} -``` -$PSDefaultParameterValues=@{":"=""} - -$PSDefaultParameterValues=@{":"={}} - $PSDefaultParameterValues["Disabled"]=$true | $false ``` - Wildcard characters are permitted in the CmdletName and ParameterName values. -The value of $PSDefaultParameterValues is a System.Management.Automation.DefaultParameterDictionary, a type of hash table that validates the format of keys. Enter a hash table where the key consists of the cmdlet name and parameter name separated by a colon (:) and the value is the custom default value. - -To set, change, add, or remove entries from $PSDefaultParameterValues, use the methods that you would use to edit a standard hash table. +The value of \$PSDefaultParameterValues is a +System.Management.Automation.DefaultParameterDictionary, a type of hash table +that validates the format of keys. Enter a hash table where the key consists +of the cmdlet name and parameter name separated by a colon (:) and the value +is the custom default value. -The must be the name of a cmdlet or the name of an advanced function that uses the CmdletBinding attribute. You cannot use $PSDefaultParameterValues to specify default values for scripts or simple functions. +To set, change, add, or remove entries from \$PSDefaultParameterValues, use the +methods that you would use to edit a standard hash table. -The default value can be an object or a script block. If the value is a script block, Windows PowerShell evaluates the script block and uses the result as the parameter value. When the specified parameter takes a script block value, enclose the script block value in a second set of braces, such as: +The \ must be the name of a cmdlet or the name of an advanced +function that uses the CmdletBinding attribute. You cannot use +$PSDefaultParameterValues to specify default values for scripts or simple +functions. +The default value can be an object or a script block. If the value is a script +block, PowerShell evaluates the script block and uses the result as the +parameter value. When the specified parameter takes a script block value, +enclose the script block value in a second set of braces, such as: -``` +```powershell $PSDefaultParameterValues=@{ "Invoke-Command:ScriptBlock"={{Get-Process}} } ``` +For information about hash tables, see +[about_Hash_Tables](about_Hash_Tables.md). For information about script +blocks, see [about_Script_Blocks](about_Script_Blocks.md). For information +about preference variables, see +[about_Preference_Variables](about_Preference_Variables.md). -For information about hash tables, see about_Hash_Tables. For information about script blocks, see about_Script_Blocks. For information about preference variables, see about_Preference_Variables. - +## EXAMPLES -### EXAMPLES -The following command sets a custom default value for the SmtpServer parameter of the Send-MailMessage cmdlet. +The following command sets a custom default value for the SmtpServer parameter +of the Send-MailMessage cmdlet. - -``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"} +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" +} ``` +To set default values for multiple parameters, use a semi-colon (;) to +separate each Name\=Value pair. The following command adds a custom default +value for the LogName parameter of the `Get-WinEvent` cmdlet. -To set default values for multiple parameters, use a semi-colon (;) to separate each Name\=Value pair. The following command adds a custom default value for the LogName parameter of the Get-WinEvent cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5"; + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" +} ``` -$PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"} -``` - -You can use wildcard characters in the name of the cmdlet and parameter. The following command sets the Verbose common parameter to $true in all commands. Use $true and $false to set values for switch parameters, such as Verbose. +You can use wildcard characters in the name of the cmdlet and parameter. The +following command sets the Verbose common parameter to \$true in all commands. +Use \$true and \$false to set values for switch parameters, such as +**Verbose**. - -``` +```powershell $PSDefaultParameterValues = @{"*:Verbose"=$true} ``` +If a parameter takes multiple values (an array), you can set multiple values +as the default value. The following command sets the default value of the +**ComputerName** parameter of the Invoke-Command cmdlet to "Server01" and +"Server02". -If a parameter takes multiple values (an array), you can set multiple values as the default value. The following command sets the default value of the ComputerName parameter of the Invoke-Command cmdlet to "Server01" and "Server02". - - -``` -$PSDefaultParameterValues = @{"Invoke-Command:ComputerName"="Server01","Server02"} -``` - - -You can use a script block to specify different default values for a parameter under different conditions. Windows PowerShell evaluates the script block and uses the result as the default parameter value. - -The following command sets the default value of the Autosize parameter of the Format-Table cmdlet to $true when the host program is the Windows PowerShell console. - - -``` -$PSDefaultParameterValues=@{"Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}}} -``` - - -If a parameter takes a script block value, enclose the script block in an extra set of braces. When Windows PowerShell evaluates the outer script block, the result is the inner script block, which is set as the default parameter value. - -The following command sets the default value of the ScriptBlock parameter of Invoke-Command. Because the script block is enclosed in a second set of braces, the enclosed script block is passed to the Invoke-Command cmdlet. - - +```powershell +$PSDefaultParameterValues = @{ + "Invoke-Command:ComputerName"="Server01","Server02" +} ``` -$PSDefaultParameterValues=@{"Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}}} -``` - - - -### HOW TO SET $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. - -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues +You can use a script block to specify different default values for a parameter +under different conditions. PowerShell evaluates the script block and uses the +result as the default parameter value. -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. +The following command sets the default value of the Autosize parameter of the +Format-Table cmdlet to \$true when the host program is the PowerShell console. - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +$PSDefaultParameterValues=@{ + "Format-Table:AutoSize"={if ($host.Name -eq "ConsoleHost"){$true}} +} ``` +If a parameter takes a script block value, enclose the script block in an +extra set of braces. When PowerShell evaluates the outer script block, the +result is the inner script block, which is set as the default parameter value. +The following command sets the default value of the ScriptBlock parameter of +`Invoke-Command`. Because the script block is enclosed in a second set of +braces, the enclosed script block is passed to the `Invoke-Command` cmdlet. -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational -Get*:Verbose True +```powershell +$PSDefaultParameterValues=@{ + "Invoke-Command:ScriptBlock"={{Get-EventLog -Log System}} +} ``` +### HOW TO SET \$PSDefaultParameterValues -To get the value of a key, use the following command syntax: +\$PSDefaultParameterValues is a preference variable, so it exists only in the +session in which it is set. It has no default value. +To set \$PSDefaultParameterValues, type the variable name and one or more +key-value pairs at the command line. -``` -$PSDefaultParameterValues[""] -``` +If you type another \$PSDefaultParameterValues command, its value replaces the +original value. The original is not retained. +To save \$PSDefaultParameterValues for future sessions, add a +\$PSDefaultParameterValues command to your PowerShell profile. For more +information, see [about_Profiles](about_Profiles.md). -For example: +### HOW TO GET \$PSDefaultParameterValues +To get the value of \$PSDefaultParameterValues, at the command prompt, type: +```powershell +$PSDefaultParameterValues ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] -Server01AB234x5 -``` - - - -### HOW TO ADD VALUES TO $PSDefaultParameterValues -$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value. - -To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line. - -If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained. - -To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles. +For example, the first command sets the value of \$PSDefaultParameterValues. +The second command gets the value of \$PSDefaultParameterValues. -### HOW TO GET $PSDefaultParameterValues -To get the value of $PSDefaultParameterValues, at the command prompt, type: $PSDefaultParameterValues - -For example, the first command sets the value of $PSDefaultParameterValues. The second command gets the value of $PSDefaultParameterValues. - - -``` -PS C:\> $PSDefaultParameterValues = @{"Send-MailMessage:SmtpServer"="Server01AB234x5"; - "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational"; - "Get-*:Verbose"=$true} +```powershell +PS C:\> $PSDefaultParameterValues = @{ + "Send-MailMessage:SmtpServer"="Server01AB234x5" + "Get-WinEvent:LogName"="Microsoft-Windows-PrintService/Operational" + "Get-*:Verbose"=$true +} ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To get the value of a \ key, use the following +command syntax: -To get the value of a key, use the following command syntax: - - -``` +```powershell $PSDefaultParameterValues[""] ``` - For example: - -``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] +```powershell +PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"] Server01AB234x5 ``` +### HOW TO ADD VALUES TO PSDefaultParameterValues +To add or remove values from \$PSDefaultParameterValues, use the methods that +you would use for a standard hash table. -### HOW TO ADD VALUES TO $PSDefaultParameterValues -To add or remove values from $PSDefaultParameterValues, use the methods that you would use for a standard hash table. - -For example, to add a value to $PSDefaultParameterValues without affecting the existing values, use the Add method of hash tables. +For example, to add a value to \$PSDefaultParameterValues without affecting the +existing values, use the Add method of hash tables. The syntax of the Add method is as follows: - ``` .Add(Key, Value) ``` +where the Key is ":" and the value is the parameter +value. -where the Key is ":" and the value is the parameter value. - -Use the following command format to call the Add method on $PSDefaultParameterValues. Be sure to use a comma (,) to separate the key from the value, instead of the equal sign (\=). - +Use the following command format to call the Add method on +\$PSDefaultParameterValues. Be sure to use a comma (,) to separate the key +from the value, instead of the equal sign (\=). +```powershell +$PSDefaultParameterValues.Add( + ":", "" +) ``` -$PSDefaultParameterValues.Add(":", "") -``` - -For example, the following command adds "PowerShell" as the default value of the Name parameter of the Get-Process cmdlet. +For example, the following command adds "PowerShell" as the default value of +the Name parameter of the Get-Process cmdlet. - -``` +```powershell $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Add("Get-Process:Name", "PowerShell") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO REMOVE VALUES FROM \$PSDefaultParameterValues - -### HOW TO REMOVE VALUES FROM $PSDefaultParameterValues -To remove a value from $PSDefaultParameterValues, use the Remove method of hash tables. +To remove a value from \$PSDefaultParameterValues, use the Remove method of +hash tables. The syntax of the Remove method is as follows: - -``` +```powershell .Remove(Key) ``` +Use the following command format to call the Remove method on +\$PSDefaultParameterValues. -Use the following command format to call the Remove method on $PSDefaultParameterValues. - - -``` +```powershell $PSDefaultParameterValues.Remove(":") ``` +For example, the following command removes the Name parameter of the +`Get-Process` cmdlet and its values. -For example, the following command removes the Name parameter of the Get-Process cmdlet and its values. - - -``` +```powershell $PSDefaultParameterValues.Remove("Get-Process:Name") ``` - The following example shows the effect of this command. +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Get-Process:Name PowerShell -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Get-Process:Name PowerShell +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - -``` +```powershell PS C:\> $PSDefaultParameterValues.Remove("Get-Process:Name") ``` +```powershell +PS C:\> $PSDefaultParameterValues - -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO CHANGE VALUES IN \$PSDefaultParameterValues +To change a value in $PSDefaultParameterValues, use the following command +format. -### HOW TO CHANGE VALUES IN $PSDefaultParameterValues -To change a value in $PSDefaultParameterValues, use the following command format. - - -``` +```powershell $PSDefaultParameterValues["CmdletName:ParameterName"]="" ``` - The following example shows the effect of this command. +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server01AB234x5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server01AB234x5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` - - +```powershell +$PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" ``` -PS C:\> $PSDefaultParameterValues["Send-MailMessage:SmtpServer"]="Server0000cabx5" -``` - +```powershell +$PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +### HOW TO DISABLE AND RE-ENABLE \$PSDefaultParameterValues +You can temporarily disable and then re-enable \$PSDefaultParameterValues. This +is very useful if you're running scripts that might assume different default +parameter values. -### HOW TO DISABLE AND RE-ENABLE $PSDefaultParameterValues -You can temporarily disable and then re-enable $PSDefaultParameterValues. This is very useful if you're running scripts that might assume different default parameter values. - -To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of $True. +To disable $PSDefaultParameterValues, add a key of "Disabled" with a value of +\$True. For example, - -``` +```powershell $PSDefaultParameterValues.Add("Disabled", $true) ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$true ``` +The other values in \$PSDefaultParameterValues are preserved, but not +effective. -The other values in $PSDefaultParameterValues are preserved, but not effective. - +```powershell +PS C:\> $PSDefaultParameterValues -``` -PS C:\> $PSDefaultParameterValues - -Name Value ----- ----- -Disabled True -Send-MailMessage:SmtpServer Server0000cabx5 -Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational +Name Value +---- ----- +Disabled True +Send-MailMessage:SmtpServer Server0000cabx5 +Get-WinEvent:LogName Microsoft-Windows-PrintService/Operational Get*:Verbose True ``` +To re-enable \$PSDefaultParameterValues, remove the Disabled key or change the +value of the Disabled key to \$False. -To re-enable $PSDefaultParameterValues, remove the Disabled key or change the value of the Disabled key to $False. - - -``` +```powershell $PSDefaultParameterValues.Remove("Disabled") ``` - - or - - -``` +```powershell $PSDefaultParameterValues[Disabled]=$false ``` - -The previous value of $PSDefaultParameterValues is effective again. - +The previous value of \$PSDefaultParameterValues is effective again. ## KEYWORDS + about_PSDefaultParameterValues about_Parameters_DefaultValues about_DefaultValues - ## SEE ALSO [about_Hash_Tables](about_Hash_Tables.md) @@ -459,4 +419,3 @@ about_DefaultValues [about_Profiles](about_Profiles.md) [about_Script_Blocks](about_Script_Blocks.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Profiles.md b/reference/6/Microsoft.PowerShell.Core/About/about_Profiles.md index b7eabd81d0ce..eea0dd9f0d50 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Profiles.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Profiles.md @@ -1,104 +1,99 @@ --- -ms.date: 2017-06-25 +ms.date: 2017-11-30 schema: 2.0.0 keywords: powershell,cmdlet title: about_Profiles --- # About Profiles -## about_Profiles +## SHORT DESCRIPTION -# SHORT DESCRIPTION +Describes how to create and use a PowerShell profile. -Describes how to create and use a Windows PowerShell profile. +## LONG DESCRIPTION -# LONG DESCRIPTION +You can create a PowerShell profile to customize your environment and to add +session-specific elements to every PowerShell session that you start. -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 PowerShell profile is a script that runs when 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 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. -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. +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. -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 PowerShell console +(PowerShell.exe) to start PowerShell without any profiles. And, it explains +the effect of the PowerShell execution policy on profiles. -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 -# THE PROFILE FILES +PowerShell supports several profile files. Also, PowerShell host programs can +support their own host-specific profiles. - -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 +For example, the 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\Profile.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 | +|Description | Path | +|--------------------------|------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Profile.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 +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\Microsoft.PowerShellISE_profile.ps1 | -| All users, Current Host | $PsHome\Microsoft.PowerShellISE_profile.ps1 | +In addition, other programs that host PowerShell can support their own +profiles. For example, PowerShell Integrated Scripting Environment (ISE) +supports the following host-specific profiles. -In Windows PowerShell Help, the "CurrentUser, Current Host" profile is the profile most -often referred to as "your Windows PowerShell profile". +|Description | Path | +|--------------------------|-------------------------------------------| +|Current user, Current Host|$Home\\[My ]Documents\\WindowsPowerShell | +| | \\Microsoft.PowerShellISE_profile.ps1 | +|All users, Current Host |$PsHome\Microsoft.PowerShellISE_profile.ps1| -# THE $PROFILE VARIABLE +In PowerShell Help, the "CurrentUser, Current Host" profile is the profile +most often referred to as "your PowerShell profile". +## THE $PROFILE VARIABLE -The `$Profile` automatic variable stores the paths to the Windows PowerShell -profiles that are available in the current session. +The `$Profile` automatic variable stores the paths to the 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. +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 | +|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. +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 PowerShell host application that you use. To see the current values of the `$Profile` variable, type: @@ -107,24 +102,22 @@ $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: +following command opens the "Current User, Current Host" profile in Notepad: ```powershell notepad $profile ``` -The following command determines whether an "All Users, All Hosts" profile -has been created on the local computer: +The following command determines whether an "All Users, All Hosts" profile has +been created on the local computer: ```powershell Test-Path -Path $profile.AllUsersAllHosts ``` -# HOW TO CREATE A PROFILE +## HOW TO CREATE A PROFILE - -To create a Windows PowerShell profile, use the following command format: +To create a PowerShell profile, use the following command format: ```powershell if (!(Test-Path -Path )) @@ -132,7 +125,7 @@ if (!(Test-Path -Path )) ``` For example, to create a profile for the current user in the current -Windows PowerShell host application, use the following command: +PowerShell host application, use the following command: ```powershell if (!(Test-Path -Path $profile)) @@ -140,21 +133,18 @@ if (!(Test-Path -Path $profile)) ``` In this command, the If statement prevents you from overwriting an existing -profile. Replace the value of the placeholder with the path +profile. Replace the value of the \ 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 +> Note: To create "All Users" profiles in Windows Vista and later versions of +> Windows, start 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. +You can open any 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: +To open the profile of the current user in the current PowerShell host +application in Notepad, type: ```powershell notepad $profile @@ -167,106 +157,99 @@ 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. +To apply the changes, save the profile file, and then restart PowerShell. -# HOW TO CHOOSE A PROFILE +## 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 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: +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 - + `$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 +implementation of 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. +Many of the items that you create in 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](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), -and Windows PowerShell snap-ins that you add to the session. +variables, aliases, functions, commands (except for +[Set-ExecutionPolicy](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md)), +and PowerShell modules 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. +To save these items and make them available in all future sessions, add them +to a 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. +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 +## 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. +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: +### 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: ```powershell function Pro {notepad $profile.CurrentUserAllHosts} ``` -- Add a function that opens Windows PowerShell Help in a compiled HTML -Help file (.chm) +### Add a function that opens PowerShell Help in a compiled HTML + Help file (.chm) ```powershell -function Get-CHM -{ -Invoke-Item -Path "$env:windir\help\mui\0409\WindowsPowerShellHelp.chm" +function Get-CHM { + Invoke-Item -Path "$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. +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 +### Add a function that lists the aliases for any cmdlet ```powershell -function Get-CmdletAlias ($cmdletname) -{ -Get-Alias | Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | Format-Table -Property Definition, Name -AutoSize +function Get-CmdletAlias ($cmdletname) { + Get-Alias | + Where-Object -FilterScript {$_.Definition -like "$cmdletname"} | + Format-Table -Property Definition, Name -AutoSize } ``` -- Customize your console +### Customize your console ```powershell -function Color-Console -{ -$Host.ui.rawui.backgroundcolor = "white" -$Host.ui.rawui.foregroundcolor = "black" -$hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime -$hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" -$Host.UI.RawUI.WindowTitle = "Windows PowerShell $hostversion ($hosttime)" -Clear-Host +function Color-Console { + $Host.ui.rawui.backgroundcolor = "white" + $Host.ui.rawui.foregroundcolor = "black" + $hosttime = (Get-ChildItem -Path $pshome\PowerShell.exe).CreationTime + $hostversion="$($Host.Version.Major)`.$($Host.Version.Minor)" + $Host.UI.RawUI.WindowTitle = "PowerShell $hostversion ($hosttime)" + Clear-Host } Color-Console ``` -- Add a customized Windows PowerShell prompt that includes the computer -name and the current path +### Add a customized PowerShell prompt ```powershell function Prompt @@ -275,18 +258,16 @@ $env:COMPUTERNAME + "\" + (Get-Location) + "> " } ``` -For more information about the Windows PowerShell prompt, see +For more information about the PowerShell prompt, see [about_Prompts](about_Prompts.md). -# THE NOPROFILE PARAMETER +## THE NOPROFILE PARAMETER +To start PowerShell without profiles, use the **NoProfile** parameter of +PowerShell.exe, the program that starts PowerShell. -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. +To begin, open a program that can start PowerShell, such as Cmd.exe or +PowerShell itself. You can also use the Run dialog box in Windows. Type: @@ -294,56 +275,58 @@ Type: PowerShell -NoProfile ``` -For a complete list of the parameters of PowerShell.exe, -type: +For a complete list of the parameters of PowerShell.exe, type: ``` PowerShell -? ``` -# PROFILES AND EXECUTION POLICY - +## 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. +The 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. +one of the few commands that applies in all 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 +## PROFILES AND REMOTE SESSIONS +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 +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 sessions. +To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) +cmdlet. -To run a profile in a session, use the [Invoke-Command](../Invoke-Command.md) cmdlet. - -For example, the following command runs the "Current user, Current Host" profile from -the local computer in the session in $s. +For example, the following command runs the "Current user, Current Host" +profile from the local computer in the session in $s. ```powershell Invoke-Command -Session $s -FilePath $profile ``` -The following command runs the "Current user, Current Host" 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. +The following command runs the "Current user, Current Host" 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. ```powershell -Invoke-Command -SessionName $s -ScriptBlock {Invoke-Command -FilePath "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"} +Invoke-Command -SessionName $s -ScriptBlock { +$path = "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1" +Invoke-Command -FilePath $path +} ``` After running this command, the commands that the profile adds to the session are available in $s. -# SEE ALSO +## SEE ALSO [about_Automatic_Variables](about_Automatic_Variables.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Prompts.md b/reference/6/Microsoft.PowerShell.Core/About/about_Prompts.md index bc2e78b01d08..6f1820bea646 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Prompts.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Prompts.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,308 +7,284 @@ title: about_Prompts --- # About Prompts -## about_Prompts - ## SHORT DESCRIPTION -Describes the Prompt function and demonstrates how to create a custom Prompt function. +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: +The PowerShell command prompt indicates that PowerShell is ready to run a +command: ``` PS C:\> ``` +The PowerShell prompt is determined by the built-in Prompt function. You can +customize the prompt by creating your own Prompt function and saving it in +your PowerShell profile. -The Windows PowerShell prompt is determined by the built-in Prompt function. You can customize the prompt by creating your own Prompt function and saving it in your Windows PowerShell profile. - +## ABOUT THE PROMPT FUNCTION -### ABOUT 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 determines the appearance of the PowerShell prompt. +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: - -``` +```powershell function Prompt { } ``` +The Prompt function must return an object. As a best practice, return a string +or an object that is formatted as a string. The maximum recommended length is +80 characters. -The Prompt function must return an object. As a best practice, return a string or an object that is formatted as a string. The maximum recommended length is 80 characters. - -For example, the following prompt function returns a "Hello, World" string followed by a caret (>). +For example, the following prompt function returns a "Hello, World" string +followed by a caret (>). - -``` -PS C:\> function prompt {"Hello, World > "} +```powershell +PS C:\> function prompt {"Hello, World > "} Hello, World > ``` - - ### GETTING THE PROMPT FUNCTION -To get the Prompt function, use the Get-Command cmdlet or use the Get-Item cmdlet in the Function drive. -Functions are commands. So, you can use the Get-Command cmdlet to get functions, including the Prompt function. +To get the Prompt function, use the `Get-Command` cmdlet or use the `Get-Item` +cmdlet in the Function drive. For example: +```powershell +PS C:\> Get-Command Prompt -``` -PS C:\> Get-Command Prompt - -CommandType Name ModuleName ------------ ---- ---------- +CommandType Name ModuleName +----------- ---- ---------- Function prompt ``` - -To get the script that sets the value of the prompt, use the dot method to get the ScriptBlock property of the Prompt function. +To get the script that sets the value of the prompt, use the dot method to get +the ScriptBlock property of the Prompt function. For example: +```powershell +PS C:\> (Get-Command Prompt).ScriptBlock -``` -PS C:\> (Get-Command Prompt).ScriptBlock - -"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -# .Link -# http://go.microsoft.com/fwlink/?LinkID=225750 +"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPr +omptLevel + 1)) " +# .Link +# http://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml ``` +Like all functions, the Prompt function is stored in the Function: drive. To +display the script that creates the current Prompt function, type: -Like all functions, the Prompt function is stored in the Function: drive. To display the script that creates the current Prompt function, type: - - -``` +```powershell (Get-Item function:prompt).ScriptBlock ``` - ### THE DEFAULT PROMPT -The default prompt appears only when the Prompt function generates an error or does not return an object. -The default Windows PowerShell prompt is: +The default prompt appears only when the Prompt function generates an error or +does not return an object. +The default PowerShell prompt is: ``` PS> ``` +For example, the following command sets the Prompt function to $null, which is +invalid. As a result, the default prompt appears. -For example, the following command sets the Prompt function to $null, which is invalid. As a result, the default prompt appears. - - -``` -PS C:\> function prompt {$null} +```powershell +PS C:\> function prompt {$null} PS> ``` - -Because Windows PowerShell comes with a built-in prompt, you usually do not see the default prompt. - +Because PowerShell comes with a built-in prompt, you usually do not see the +default prompt. ### BUILT-IN PROMPT -Windows PowerShell includes a built-in prompt function. - -In Windows PowerShell 3.0, the built-in prompt function is: - - -``` -function prompt -{ - "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) " -} -``` - -This simplified prompt starts with "PS" followed by the current location, and one ">" for each nested prompt level. +PowerShell includes a built-in prompt function. -In Windows PowerShell 2.0, the built-in prompt function is: - - -``` -function prompt -{ - $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } - else { '' }) + 'PS ' + $(Get-Location) ` - + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' +```powershell +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: -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: - - -``` +```Output [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 (>). -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: -``` -For example: - PS C:\ps-test> +```Output +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.) -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: -For example, when you are debugging in a nested prompt, the prompt resembles the following prompt: - - -``` +```Output [DBG] PS C:\ps-test>>> ``` - - ### CHANGES TO THE PROMPT -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: +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 +```Output +PS Hello, World> Enter-PSSession Server01 [Server01]: PS Hello, World> ``` +Other PowerShell host applications and alternate shells might have their own +custom command prompts. -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. - +For more information about the \$PSDebugContext and $NestedPromptLevel +automatic variables, see [about_Automatic_Variables](about_Automatic_Variables.md). ### HOW TO CUSTOMIZE 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: +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: -``` +```powershell function prompt { } ``` - -Then, between the braces, enter the commands or the string that creates your prompt. +Then, between the braces, enter the commands or the string that creates your +prompt. For example, the following prompt includes your computer name: - -``` +```powershell function prompt {"PS [$env:COMPUTERNAME]> "} ``` - On the Server01 computer, the prompt resembles the following prompt: - -``` +```Output PS [Server01] > ``` - The following prompt function includes the current date and time: - -``` +```powershell function prompt {"$(get-date)> "} ``` - The prompt resembles the following prompt: - -``` +```Output 03/15/2012 17:49:47> ``` - You can also change the default Prompt function: -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) { '>>' }) + '> ' +For example, the following modified Prompt function adds "[ADMIN]:" to the +built-in PowerShell prompt when PowerShell is opened by using the "Run as +administrator" option: + +```powershell +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 PowerShell by using the "Run as administrator" option, a prompt +that resembles the following prompt appears: -When you start Windows PowerShell by using the "Run as administrator" option, a prompt that resembles the following prompt appears: - - -``` +```Output [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. -The following Prompt function displays the history ID of the next command. To view the command history, use the Get-History cmdlet. - +```powershell +function prompt { + # The at sign creates an array in case only one history item exists. + $history = @(get-history) + if($history.Count -gt 0) + { + $lastItem = $history[$history.Count - 1] + $lastId = $lastItem.Id + } -``` -function prompt -{ - # The at sign creates an array in case only one history item exists. - $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 >" + $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, PowerShell uses the default prompt, "PS>". -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 -ForegroundColor $Color - return " " +```powershell +function prompt { + $color = Get-Random -Min 1 -Max 16 + Write-Host ("PS " + $(Get-Location) +">") -NoNewLine ` + -ForegroundColor $Color + return " " } ``` - - ### SAVING THE PROMPT FUNCTION -Like any function, the Prompt function exists 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. +Like any function, the Prompt function exists only in the current session. To +save the Prompt function for future sessions, add it to your PowerShell +profiles. For more information about profiles, see about_Profiles. ## SEE ALSO -Get-Location +[Get-Location](../../Microsoft.PowerShell.Management/Get-Location.md) -Enter-PSSession +[Enter-PSSession](../Enter-PSSession.md) -Get-History +[Get-History](../Get-History.md) -Get-Random +[Get-Random](../../Microsoft.PowerShell.Utility/Get-Random.md) -Write-Host +[Write-Host](../../Microsoft.PowerShell.Utility/Write-Host.md) [about_Profiles](about_Profiles.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/6/Microsoft.PowerShell.Core/About/about_pipelines.md index ec7b65c085af..97cd9535c505 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2017-11-30 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,41 +7,39 @@ title: about_pipelines --- # About Pipelines -## about_Pipelines - - ### Short Description -Combining commands into pipelines in the Windows PowerShell +Combining commands into pipelines in the 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. +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 powerful -command chain or "pipeline" that is comprised of a series of simple commands. +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 powerful command +chain or "pipeline" that is comprised of a series of simple commands. For example, + ```powershell 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` processes -the objects and send them down the pipeline. Because there are no more commands in -the pipeline, the results are displayed at the console. +`Command-2` processes the objects and sends them to `Command-3`. `Command-3` +processes the objects and send them down the pipeline. Because there are no +more commands 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. +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. +Here is a simple example. The following command gets the Notepad process and +then stops it. For example, ```powershell @@ -49,77 +47,69 @@ 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 object -to the `Stop-Process` cmdlet, which stops the Notepad process. Notice that the -`Stop-Process` command does not have a Name or ID parameter to specify the process, -because the specified process is submitted through the pipeline. +the Notepad process. It uses a pipeline operator (`|`) to send the process +object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice +that the `Stop-Process` command does not have a Name or ID parameter to +specify the process, because the specified process is submitted through the +pipeline. Here is a practical example. This command pipeline gets the text files in the -current directory, selects only the files that are more than 10,000 bytes long, -sorts them by length, and displays the name and length of each file in a table. +current directory, selects only the files that are more than 10,000 bytes +long, sorts them by length, and displays the name and length of each file in a +table. ```powershell 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 command -is written horizontally, but we will show the process vertically in the following -graphic. +This pipeline is comprised of four commands in the specified order. The +command is written horizontally, but we will show the process vertically in +the following graphic. `Get-ChildItem` `-Path` *.txt - **|** - -| (FileInfo objects ) -| ( .txt ) - - **|** - - **V** +``` +| +| (FileInfo objects for *.txt) +| +V +``` `Where-Object` {$_.length `-gt` 10000} - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| +V +``` `Sort-Object` `-Property` Length - **|** - -| (FileInfo objects ) -| ( .txt ) -| ( Length > 10000 ) -| ( Sorted by length ) - - **|** - - **V** - +``` +| +| (FileInfo objects for *.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** - ``` +| +| (FileInfo objects for *.txt) +| ( Length > 10000 ) +| ( Sorted by length ) +| ( Formatted in a table ) +| +V +``` + +```output Name Length ---- ------ tmp1.txt 82920 @@ -129,13 +119,13 @@ tmp3.txt 114000 ### Using Pipelines +The PowerShell cmdlets were designed to be used in pipelines. For example, 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. -The Windows PowerShell cmdlets were designed to be used in pipelines. For example, -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 `Start-Service` -or `Stop-Service` cmdlets (although disabled services cannot be restarted in this way). +For example, you can pipe any service from the `Get-Service` cmdlet to the +`Start-Service` or `Stop-Service` cmdlets (although disabled services cannot +be restarted in this way). This command pipeline starts the WMI service on the computer: @@ -144,90 +134,98 @@ For example, Get-Service wmi | Start-Service ``` -The cmdlets that get and set objects of the Windows PowerShell providers, such as the +The cmdlets that get and set objects of the PowerShell providers, such 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` command in the -Windows PowerShell registry provider to the `New-ItemProperty` cmdlet. This command adds -a new registry entry, NoOfEmployees, with a value of 8124, to the MyCompany registry key. +For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` +command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. +This command adds a new registry entry, NoOfEmployees, with a value of 8124, +to the MyCompany registry key. For example, ```powershell -Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 +Get-Item -Path HKLM:\Software\MyCompany | + New-ItemProperty -Name NoOfEmployees -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 any objects to -these cmdlets. +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 any 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. +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. For example, + ```powershell Get-Process | Sort-Object -Property handles ``` -Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and -`Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out -cmdlets, such as `Out-Printer`. +Also, you can pipe any objects to the formatting cmdlets, such as +`Format-List` 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. +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. For example, + ```powershell Get-Process winlogon | Format-List -Property * ``` -With a bit of practice, you'll find that combining simple commands into pipelines -saves time and typing, and makes your scripting more efficient. +With a bit of practice, you'll find that combining simple commands into +pipelines 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 command +to another command, PowerShell tries to associate the piped objects with one +of the parameters of the receiving cmdlet. -When you "pipe" objects, that is send the objects in the output of one command 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 associates input objects -with cmdlet parameters, tries to find a parameter that meets the following criteria: +To do so, the PowerShell "parameter binding" component, which associates 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 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 `-InputObject` 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`. +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 `-InputObject` 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 PowerShell prompts you -for the missing parameter values. +If the parameter binding component of PowerShell cannot associate the piped +objects with a parameter of the receiving cmdlet, the command fails and +PowerShell prompts you for the missing parameter values. -You cannot force the parameter binding component to associate the piped objects with a particular -parameter -- you cannot even suggest a parameter. Instead, the logic of the component manages -the piping as efficiently as possible. +You cannot force the parameter binding component to associate the piped +objects with a particular parameter. You cannot even suggest a parameter. +Instead, the logic of the 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. -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: +For example, piping objects representing the services on the computer to a +`Format-Table` command, such as: ```powershell Get-Service | Format-Table -Property name, dependentservices ``` -is much like saving the service objects in a variable and using the InputObject parameter -of `Format-Table` to submit the service object. +is much like saving the service objects in a variable and using the +InputObject parameter of `Format-Table` to submit the service object. For example, + ```powershell $services = Get-Service Format-Table -InputObject $services -Property name, dependentservices @@ -236,51 +234,58 @@ Format-Table -InputObject $services -Property name, dependentservices or imbedding the command in the parameter value For example, + ```powershell -Format-Table -InputObject (Get-Service wmi) -Property name, dependentservices +Format-Table -InputObject (Get-Service wmi) -Property name,dependentservices ``` -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 you use a -command parameter, the objects are sent as a single array object. +However, there is an important difference. When you pipe multiple objects to a +command, PowerShell sends the objects to the command one at a time. When you +use a command parameter, the objects are sent as a single array object. + +This seemingly technical difference can have interesting, and sometimes +useful, consequences. -This seemingly technical difference can have interesting, and sometimes useful, consequences. +For example, if you pipe multiple process objects from the `Get-Process` +cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one +at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the +process objects, and their properties and methods. -For example, if you pipe multiple process objects from the `Get-Process` cmdlet 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 their properties and methods. -(`Get-Member` eliminates duplicates, so if the objects are all of the same type, it displays only -one object type.) +NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the +same type, it displays only one object type. -In this case, `Get-Member` displays the properties and methods of each process object, that is, a -System.Diagnostics.Process object. +In this case, `Get-Member` displays the properties and methods of each process +object, that is, a System.Diagnostics.Process object. For example, + ```powershell Get-Process | Get-Member ``` -``` +```Output TypeName: System.Diagnostics.Process -Name MemberType Definition ----- ---------- ---------- -Handles AliasProperty Handles = Handlecount -Name AliasProperty Name = ProcessName -NPM AliasProperty NPM = NonpagedSystemMemorySize +Name MemberType Definition +---- ---------- ---------- +Handles AliasProperty Handles = Handlecount +Name AliasProperty Name = ProcessName +NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then `Get-Member` receives an -array of System.Diagnostics.Process objects as a single unit, and it displays the properties -of an array of objects. (Note the array symbol ([]) after the System.Object type name.) +However, if you use the InputObject parameter of `Get-Member`, then +`Get-Member` receives an array of System.Diagnostics.Process objects as a +single unit, and it displays the properties of an array of objects. (Note the +array symbol ([]) after the System.Object type name.) For example, + ```powershell Get-Member -InputObject (Get-Process) ``` -``` +```Output TypeName: System.Object[] Name MemberType Definition @@ -291,30 +296,32 @@ Clone Method System.Object Clone() ... ``` -This result might not be what you intended, but after you understand it, you 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. +This result might not be what you intended, but after you understand it, you +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. For example, + ```powershell (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. +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** or **Parameter** -parameters to determine which, if any, of a cmdlet's parameters 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** or **Parameter** parameters to determine which, if any, of a +cmdlet's parameters accepts pipeline input. -In the `Get-Help` default display, the "Accept 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. +In the `Get-Help` default display, the "Accept 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` cmdlet accepts -pipeline input, type: +For example, to determine which of the parameters of the `Start-Service` +cmdlet accepts pipeline input, type: ```powershell Get-Help Start-Service -Full @@ -326,108 +333,115 @@ or Get-Help Start-Service -Parameter * ``` -For example, the help for the `Start-Service` cmdlet shows that the **InputObject** and **Name** -parameters accept pipeline input ("true"). All other parameters have a value of "false" -in the "Accept pipeline input?" row. +For example, the help for the `Start-Service` cmdlet shows that the +**InputObject** and **Name** parameters accept pipeline input ("true"). All +other parameters have a value of "false" in the "Accept pipeline input?" row. ``` -InputObject - 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. +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? true - Position? 0 - Default value None - Accept pipeline input? True (ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByValue) +Accept wildcard characters? false -Name - Specifies the service names for the service to be started. +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. +The parameter name is optional. You can use Name or its alias, ServiceName, +or you can omit the parameter name. - Required? true - Position? 0 - Default value None - Accept pipeline input? True (ByPropertyName, ByValue) - Accept wildcard characters? false +Required? true +Position? 0 +Default value None +Accept pipeline input? True (ByPropertyName, ByValue) +Accept wildcard characters? false ``` This means that you can send objects (PsObjects) through the pipeline to the -`Where-Object` cmdlet and Windows PowerShell will associate the object with the +`Where-Object` cmdlet and PowerShell will associate the object with the **InputObject** and **Name** parameters. ### 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 objects -that have the same .NET type as their parameter value or objects that can 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. + that have the same .NET type as their parameter value or objects that can be + converted to that type. -- ByPropertyName: Parameters that accept input "by property name" can accept piped -objects only when a property of the object has the same name as the parameter. + 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. -For example, the Name parameter of `Start-Service` can accept objects that have -a Name property. +- ByPropertyName: Parameters that accept input "by property name" can accept + piped objects only when a property of the object has the same name as the + parameter. -(To list the properties of an object, pipe it to `Get-Member`.) + For example, the Name parameter of `Start-Service` can accept objects that + 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 parameters are -designed to take input from the pipeline easily. +Some parameters can accept objects by value or by property name. These +parameters 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 failure and -rewrite the command. +If a command fails because of a pipeline error, you can investigate the +failure 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 destination path and -then piping the path to the `Move-ItemProperty` cmdlet. +registry key to another by using the `Get-Item` cmdlet to get the destination +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. The `Move-ItemProperty` -command specifies the current path and name of the registry entry to be moved. +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. The `Move-ItemProperty` command specifies the +current path and name of the registry entry to be moved. For example, + ```powershell 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 +The command fails and 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 pipeline input. +```output +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 +pipeline input. At line:1 char:23 -+ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name product ++ $a | Move-ItemProperty <<<< -Path HKLM:\software\mycompany\design -Name p ``` -To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of -Windows PowerShell. The following command traces the Parameter Binding component 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 reference. +To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding +component of PowerShell. The following command traces the Parameter Binding +component 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 reference. For example, + ```powershell -Trace-Command -Name parameterbinding -Expression {Get-Item -Path HKLM:\software\mycompany\sales | -Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} -PSHost -FilePath debug.txt +Trace-Command -Name parameterbinding -Expression { + Get-Item -Path HKLM:\software\mycompany\sales | + Move-ItemProperty -Path HKLM:\software\mycompany\design -Name product} ` + -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. +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`] @@ -442,31 +456,35 @@ 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 parameter -of `Move-ItemProperty` failed. +Finally, it shows that the attempt to bind the path to the **Destination** +parameter 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 ValueFromPipelineByPropertyName NO COERCION -Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION +Parameter [Destination] PIPELINE INPUT ValueFromPipelineByPropertyName NO CO +ERCION +Parameter [Credential] PIPELINE INPUT ValueFromPipelineByPropertyName NO COE +RCION ... +``` - -To investigate the failure, use the `Get-Help` cmdlet to view the attributes of the -**Destination** parameter. The following command gets detailed information about the -**Destination** parameter. +To investigate the failure, use the `Get-Help` cmdlet to view the attributes +of the **Destination** parameter. The following command gets detailed +information about the **Destination** parameter. ```powershell Get-Help Move-ItemProperty -Parameter Destination ``` -The results show that **Destination** takes pipeline input only "by property name". -That is, the piped object must have a property named Destination. +The results show that **Destination** takes pipeline input only "by property +name". That is, the piped object must have a property named Destination. ``` -Destination @@ -479,11 +497,12 @@ That is, the piped object must have a property named Destination. Accept wildcard characters? false ``` -To see the properties of the object being piped to the `Move-ItemProperty` cmdlet, -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. +To see the properties of the object being piped to the `Move-ItemProperty` +cmdlet, 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. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` @@ -491,11 +510,13 @@ 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-ItemProperty` cmdlet. We can -use a `Get-ItemProperty` command to get the path, but the name and destination must be specified -in the `Move-ItemProperty` part of the command. +To fix the command, we must specify the destination in the `Move-ItemProperty` +cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name +and destination must be specified in the `Move-ItemProperty` part of the +command. For example, + ```powershell Get-Item -Path HKLM:\software\mycompany\design | Move-ItemProperty -Dest HKLM:\software\mycompany\design -Name product @@ -510,9 +531,11 @@ Get-Itemproperty HKLM:\software\mycompany\sales The results show that the Product registry entry was moved to the Sales key. -``` -PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany\sales -PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany +```Output +PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany\sales +PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa +re\mycompany PSChildName : sales PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry