diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Environment_Variables.md b/reference/6/Microsoft.PowerShell.Core/About/about_Environment_Variables.md index 900e10daf0c5..700cb3bc71ca 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Environment_Variables.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Environment_Variables.md @@ -305,5 +305,5 @@ For more information, see [about_Modules](about_Modules.md). ## SEE ALSO -- [Environment (provider)](../../Microsoft.PowerShell.Core/Providers/Environment-Provider.md) +- [Environment (provider)](../Providers/Environment-Provider.md) - [about_Modules](about_Modules.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_For.md b/reference/6/Microsoft.PowerShell.Core/About/about_For.md index c8343e7483e3..5c8f723bb156 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_For.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_For.md @@ -25,7 +25,7 @@ all the values in an array, consider using a Foreach statement. The following shows the For statement syntax. ```powershell -for (>init>; ; ) +for (; ; ) {} ``` diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Functions_Advanced_Methods.md b/reference/6/Microsoft.PowerShell.Core/About/about_Functions_Advanced_Methods.md index 3e4a5424b207..9dd552a11e64 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Functions_Advanced_Methods.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Functions_Advanced_Methods.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,77 +7,71 @@ title: about_Functions_Advanced_Methods --- # About Functions Advanced Methods -## about_Functions_Advanced_Methods +## SHORT DESCRIPTION -# SHORT DESCRIPTION - -Describes how functions that specify the `CmdletBinding` attribute can use -the methods and properties that are available to compiled cmdlets. +Describes how functions that specify the `CmdletBinding` attribute can use the +methods and properties that are available to compiled cmdlets. # LONG DESCRIPTION Functions that specify the `CmdletBinding` attribute can access a number of -methods and properties through the `$pscmdlet` variable. These methods -include the following methods: +methods and properties through the `$pscmdlet` variable. These methods include +the following methods: - Input-processing methods that compiled cmdlets use to do their work. - - The `ShouldProcess` and `ShouldContinue` methods that are used to get -user feedback before an action is performed. - + user feedback before an action is performed. - The `ThrowTerminatingError` method for generating error records. - - Several Write methods that return different types of output. All the methods and properties of the `PSCmdlet` class are available to -advanced functions. For more information about these methods and -properties, see `System.Management.Automation.PSCmdlet` in the MSDN -(Microsoft Developer Network) library at -http://go.microsoft.com/fwlink/?LinkId=142139. - -# Input Processing Methods - -The methods described in this section are referred to as the input -processing methods. For functions, these three methods are represented -by the `Begin`, `Process`, and `End` blocks of the function. Each function -must include one or more of these blocks. The Windows PowerShell runtime -uses the code within these blocks when it is running a function. (These -blocks are also available to functions that do not use the `CmdletBinding` -attribute.) - -## Begin +advanced functions. For more information about these methods and properties, +see [`System.Management.Automation.PSCmdlet`](http://go.microsoft.com/fwlink/?LinkId=142139) in the MSDN library. + +### Input Processing Methods + +The methods described in this section are referred to as the input processing +methods. For functions, these three methods are represented by the `Begin`, +`Process`, and `End` blocks of the function. Each function must include one or +more of these blocks. The Windows PowerShell runtime uses the code within +these blocks when it is running a function. (These blocks are also available +to functions that do not use the `CmdletBinding` attribute.) + +#### Begin + This block is used to provide optional one-time preprocessing for the -function. The Windows PowerShell runtime uses the code in this block one -time for each instance of the function in the pipeline. - -## Process -This block is used to provide record-by-record processing for the -function. This block might be used any number of times, or not at all, -depending on the input to the function. For example, if the function is -the first command in the pipeline, the `Process` block will be used one -time. If the function is not the first command in the pipeline, the -`Process` block is used one time for every input that the function -receives from the pipeline. If there is no pipeline input, the `Process` -block is not used. - -This block must be defined if a function parameter is set to accept -pipeline input. If this block is not defined and the parameter accepts -input from the pipeline, the function will miss the values that are -passed to the function through the pipeline. +function. The Windows PowerShell runtime uses the code in this block one time +for each instance of the function in the pipeline. + +#### Process + +This block is used to provide record-by-record processing for the function. +This block might be used any number of times, or not at all, depending on the +input to the function. For example, if the function is the first command in +the pipeline, the `Process` block will be used one time. If the function is +not the first command in the pipeline, the `Process` block is used one time +for every input that the function receives from the pipeline. If there is no +pipeline input, the `Process` block is not used. + +This block must be defined if a function parameter is set to accept pipeline +input. If this block is not defined and the parameter accepts input from the +pipeline, the function will miss the values that are passed to the function +through the pipeline. Also, when the function supports confirmation requests (when the `SupportsShouldProcess` parameter of the Parameter attribute is set to -`$True`), the call to the `ShouldProcess` method must be made from within -the Process block. +`$True`), the call to the `ShouldProcess` method must be made from within the +Process block. + +#### End -## End -This block is used to provide optional one-time post-processing for -the function. +This block is used to provide optional one-time post-processing for the +function. -The following example shows the outline of a function that contains a -`Begin` block for one-time preprocessing, a `Process` block for multiple -record processing, and an `End` block for one-time post-processing. +The following example shows the outline of a function that contains a `Begin` +block for one-time preprocessing, a `Process` block for multiple record +processing, and an `End` block for one-time post-processing. ```powershell Function Test-ScriptCmdlet @@ -90,119 +84,125 @@ Function Test-ScriptCmdlet } ``` -# Confirmation Methods +### Confirmation Methods + +#### ShouldProcess -## ShouldProcess This method is called to request confirmation from the user before the -function performs an action that would change the system. The function -can continue based on the Boolean value returned by the method. This -method can be called only from within the `Process{}` block of the -function. And, the `CmdletBinding` attribute must declare that the -function supports `ShouldProcess` (as shown in the previous example). +function performs an action that would change the system. The function can +continue based on the Boolean value returned by the method. This method can be +called only from within the `Process{}` block of the function. And, the +`CmdletBinding` attribute must declare that the function supports +`ShouldProcess` (as shown in the previous example). For more information about this method, see -`System.Management.Automation.Cmdlet.ShouldProcess` in the MSDN library at -http://go.microsoft.com/fwlink/?LinkId=142142. +[`System.Management.Automation.Cmdlet.ShouldProcess`](http://go.microsoft.com/fwlink/?LinkId=142142) +in the MSDN library. For more information about how to request confirmation, see -"Requesting Confirmation" in the MSDN library at -http://go.microsoft.com/fwlink/?LinkID=136658. +[Requesting Confirmation](http://go.microsoft.com/fwlink/?LinkID=136658) +in the MSDN library. + +#### ShouldContinue -## ShouldContinue -This method is called to request a second confirmation message. It -should be called when the `ShouldProcess` method returns `$true`. For more -information about this method, see -`System.Management.Automation.Cmdlet.ShouldContinue` in the MSDN library -at http://go.microsoft.com/fwlink/?LinkId=142143. +This method is called to request a second confirmation message. It should be +called when the `ShouldProcess` method returns `$true`. For more information +about this method, see `System.Management.Automation.Cmdlet.ShouldContinue` in +the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142143. -# Error Methods +### Error Methods Functions can call two different methods when errors occur. When a -nonterminating error occurs, the function should call the `WriteError` -method, which is described in the "Write Methods" section. When a -terminating error occurs and the function cannot continue, it should call -the `ThrowTerminatingError` method. You can also use the `Throw` statement for +nonterminating error occurs, the function should call the `WriteError` method, +which is described in the "Write Methods" section. When a terminating error +occurs and the function cannot continue, it should call the +`ThrowTerminatingError` method. You can also use the `Throw` statement for terminating errors and the `Write-Error` cmdlet for nonterminating errors. -For more information, see `System.Management.Automation.Cmdlet.ThrowTerminatingError` -in the MSDN libray at -http://go.microsoft.com/fwlink/?LinkId=142144. +For more information, see +[`System.Management.Automation.Cmdlet.ThrowTerminatingError`](http://go.microsoft.com/fwlink/?LinkId=142144) +in the MSDN libray. -# Write Methods +### Write Methods -A function can call the following methods to return different types of -output. Notice that not all the output goes to the next command in the -pipeline. You can also use the various Write cmdlets, such as -Write-Error. +A function can call the following methods to return different types of output. +Notice that not all the output goes to the next command in the pipeline. You +can also use the various Write cmdlets, such as Write-Error. + +#### WriteCommandDetail -## WriteCommandDetail For information about the `WriteCommandDetails` method, see -`System.Management.Automation.Cmdlet.WriteCommandDetail` in the MSDN -library at http://go.microsoft.com/fwlink/?LinkId=142155. - -## WriteDebug -To provide information that can be used to troubleshoot a function, -make the function call the `WriteDebug` method. This displays debug -messages to the user. For more information, see -`System.Management.Automation.Cmdlet.WriteDebug` in the MSDN library -at http://go.microsoft.com/fwlink/?LinkId=142156. - -## WriteError -Functions should call this method when nonterminating errors occur and -the function is designed to continue processing records. For more -information, see `System.Management.Automation.Cmdlet.WriteError` in the -MSDN library at http://go.microsoft.com/fwlink/?LinkId=142157. +[`System.Management.Automation.Cmdlet.WriteCommandDetail`](http://go.microsoft.com/fwlink/?LinkId=142155) +in the MSDN library. + +#### WriteDebug + +To provide information that can be used to troubleshoot a function, make the +function call the `WriteDebug` method. This displays debug messages to the +user. For more information, see +[`System.Management.Automation.Cmdlet.WriteDebug`](http://go.microsoft.com/fwlink/?LinkId=142156) +in the MSDN library. + +#### WriteError + +Functions should call this method when nonterminating errors occur and the +function is designed to continue processing records. For more information, see +[`System.Management.Automation.Cmdlet.WriteError`](http://go.microsoft.com/fwlink/?LinkId=142157) +in the MSDN library. Note: If a terminating error occurs, the function should call the `ThrowTerminatingError` method. -## WriteObject -This method allows the function to send an object to the next command in -the pipeline. In most cases, this is the method to use when the function -returns data. For more information, see -`System.Management.Automation.PSCmdlet.WriteObject` in the MSDN library at -http://go.microsoft.com/fwlink/?LinkId=142158. - -## WriteProgress -For functions whose actions take a long time to complete, this method -allows the function to call the `WriteProgress` method so that progress -information is displayed. For example, you can display the percent -completed. For more information, see -`System.Management.Automation.PSCmdlet.WriteProgress` in the MSDN library -at http://go.microsoft.com/fwlink/?LinkId=142160. - -## WriteVerbose -To provide detailed information about what the function is doing, make -the function call the `WriteVerbose` method to display verbose messages to -the user. By default, verbose messages are not displayed. For more -information, see `System.Management.Automation.PSCmdlet.WriteVerbose` -in the MSDN library at http://go.microsoft.com/fwlink/?LinkId=142162. - -## WriteWarning -To provide information about conditions that may cause unexpected -results, make the function call the WriteWarning method to display -warning messages to the user. By default, warning messages are displayed. -For more information, see -`System.Management.Automation.PSCmdlet.WriteWarning` in the MSDN library -at http://go.microsoft.com/fwlink/?LinkId=142164. +#### WriteObject + +This method allows the function to send an object to the next command in the +pipeline. In most cases, this is the method to use when the function returns +data. For more information, see +[`System.Management.Automation.PSCmdlet.WriteObject`](http://go.microsoft.com/fwlink/?LinkId=142158) +in the MSDN library. + +#### WriteProgress + +For functions whose actions take a long time to complete, this method allows +the function to call the `WriteProgress` method so that progress information +is displayed. For example, you can display the percent completed. For more +information, see [`System.Management.Automation.PSCmdlet.WriteProgress`](http://go.microsoft.com/fwlink/?LinkId=142160) +in the MSDN library. + +#### WriteVerbose + +To provide detailed information about what the function is doing, make the +function call the `WriteVerbose` method to display verbose messages to the +user. By default, verbose messages are not displayed. For more information, +see +[`System.Management.Automation.PSCmdlet.WriteVerbose`](http://go.microsoft.com/fwlink/?LinkId=142162) +in the MSDN library. + +#### WriteWarning + +To provide information about conditions that may cause unexpected results, +make the function call the WriteWarning method to display warning messages to +the user. By default, warning messages are displayed. For more information, +see [`System.Management.Automation.PSCmdlet.WriteWarning`](http://go.microsoft.com/fwlink/?LinkId=142164) +in the MSDN library. Note: You can also display warning messages by configuring the `WarningPreference` variable or by using the `Verbose` and `Debug` command-line options. -# Other Methods and Properties +### Other Methods and Properties For information about the other methods and properties that can be accessed through the `$PSCmdlet` variable, see -`System.Management.Automation.PSCmdlet` in the MSDN library at -http://go.microsoft.com/fwlink/?LinkId=142139. +[`System.Management.Automation.PSCmdlet`](http://go.microsoft.com/fwlink/?LinkId=142139) +in the MSDN library. For example, the `ParameterSetName` property allows you to see the parameter set that is being used. Parameter sets allow you to create a function that -performs different tasks based on the parameters that are specified when -the function is run. +performs different tasks based on the parameters that are specified when the +function is run. -# SEE ALSO +## SEE ALSO [about_Functions](about_Functions.md) @@ -213,4 +213,3 @@ the function is run. [about_Functions_CmdletBindingAttribute](about_Functions_CmdletBindingAttribute.md) [about_Functions_OutputTypeAttribute](about_Functions_OutputTypeAttribute.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Functions_OutputTypeAttribute.md b/reference/6/Microsoft.PowerShell.Core/About/about_Functions_OutputTypeAttribute.md index 546fe9f1e0aa..f5f40dd0d876 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Functions_OutputTypeAttribute.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Functions_OutputTypeAttribute.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,15 +7,13 @@ title: about_Functions_OutputTypeAttribute --- # About Functions OutputTypeAttribute -## about_Functions_OutputTypeAttribute - -# SHORT DESCRIPTION +## SHORT DESCRIPTION Describes an attribute that reports the type of object that the function returns. -# LONG DESCRIPTION +## LONG DESCRIPTION The OutputType attribute lists the .NET types of objects that the functions returns. You can use its optional ParameterSetName parameter to list different @@ -32,25 +30,27 @@ The OutputType attribute value is only a documentation note. It is not derived from the function code or compared to the actual function output. As such, the value might be inaccurate. -# SYNTAX +## SYNTAX The OutputType attribute of functions has the following syntax: -```powershell +``` [OutputType([], ParameterSetName="")] [OutputType("", ParameterSetName="")] ``` + The ParameterSetName parameter is optional. You can list multiple types in the OutputType attribute. -```powershell +``` [OutputType([],[],[])] ``` + You can use the ParameterSetName parameter to indicate that different parameter sets return different types. -```powershell +``` [OutputType([], ParameterSetName="","")] [OutputType([], ParameterSetName="")] ``` @@ -80,9 +80,11 @@ function AdvancedFunction1 [OutputType([])] Param ( [parameter(Mandatory=$true)] - [String[]] $Parameter1 + [String[]] + $Parameter1 ) - + + } @@ -92,16 +94,17 @@ function AdvancedFunction2 [OutputType([])] Param ( [parameter(Mandatory=$true)] - [String[]] $Parameter1 + [String[]] + $Parameter1 ) + } ``` # EXAMPLES - The following function uses the OutputType attribute to indicate that it returns a string value. @@ -111,13 +114,13 @@ function Send-Greeting [OutputType([String])] Param ($Name) - Hello, $Name + "Hello, $Name" } ``` To see the resulting output type property, use the Get-Command cmdlet. -```bash +``` PS C:> (Get-Command Send-Greeting).OutputType Name Type @@ -139,12 +142,15 @@ function Get-User Param ( [parameter(Mandatory=$true, ParameterSetName="ID")] - [Int[]] $UserID, + [Int[]] + $UserID, [parameter(Mandatory=$true, ParameterSetName="Name")] - [String[]] $UserName + [String[]] + $UserName ) + } ``` @@ -160,19 +166,18 @@ that it returns a System.DateTime object. function Get-Time { [OutputType([DateTime])] - Param - ( + Param ( [parameter(Mandatory=$true)] - [Datetime] $DateTime + [Datetime]$DateTime ) - + $DateTime.ToShortTimeString() } ``` The Get-Type method confirms that the function returns a string. -```bash +``` PS C:> (Get-Time -DateTime (Get-Date)).Gettype().FullName System.String ``` @@ -180,7 +185,7 @@ System.String However, the OutputType property, which gets its value from the OutputType attribute, reports that the function returns a DateTime object. -```bash +``` PS C:> (Get-Command Get-Time).OutputType Name Type @@ -188,7 +193,7 @@ Name Type System.DateTime System.DateTime ``` -# NOTES +## NOTES The value of the OutputType property of a FunctionInfo object is an array of System.Management.Automation.PSTypeName objects, each of which have Name and @@ -216,4 +221,3 @@ of an object. [about_Functions_Advanced_Parameters](about_Functions_Advanced_Parameters.md) [about_Functions_CmdletBindingAttribute](about_Functions_CmdletBindingAttribute.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Language_Keywords.md b/reference/6/Microsoft.PowerShell.Core/About/about_Language_Keywords.md index b1dd44a10b43..5c8fc2278634 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Language_Keywords.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Language_Keywords.md @@ -583,7 +583,7 @@ Syntax: do {} while () ``` -# SEE ALSO +## SEE ALSO - [about_Special_Characters](about_Special_Characters.md) - [about_Wildcards](about_Wildcards.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Modules.md b/reference/6/Microsoft.PowerShell.Core/About/about_Modules.md index 6fa833802f55..e5fe0b0de061 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Modules.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Modules.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-11-29 +ms.date: 2018-01-04 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -486,22 +486,20 @@ NOTE: Remote sessions, including sessions that are started by using the commands are packaged in snap-ins. The following modules (or snap-ins) are installed with PowerShell. +* CimCmdlets * Microsoft.PowerShell.Archive * Microsoft.PowerShell.Core * Microsoft.PowerShell.Diagnostics * Microsoft.PowerShell.Host * Microsoft.PowerShell.Management -* Microsoft.PowerShell.ODataUtils * Microsoft.PowerShell.Security * Microsoft.PowerShell.Utility * Microsoft.WSMan.Management -* OneGet +* PackageManagement * PowerShellGet * PSDesiredStateConfiguration -* PSScheduledJob -* PSWorkflow -* PSWorkflowUtility -* ISE +* PSDiagnostics +* PSReadline ## See Also diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_PSSessions.md b/reference/6/Microsoft.PowerShell.Core/About/about_PSSessions.md index 196d7fddf1b9..a96bb8e474f6 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_PSSessions.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_PSSessions.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -10,63 +10,120 @@ title: about_PSSessions ## Short Description -Describes Windows PowerShell sessions (PSSessions) and explains how to establish a persistent connection to a remote computer. +Describes Windows PowerShell sessions (PSSessions) and explains how to +establish a persistent connection to a remote computer. ## Long Description -To run Windows PowerShell commands on a remote computer, you can use the **ComputerName** parameter of a cmdlet, or you can create a Windows PowerShell session (PSSession) and run commands in the PSSession. +To run Windows PowerShell commands on a remote computer, you can use the +**ComputerName** parameter of a cmdlet, or you can create a Windows PowerShell +session (PSSession) and run commands in the PSSession. -When you create a PSSession, Windows PowerShell establishes a persistent connection to the remote computer. Use a PSSession to run a series of related commands on a remote computer. Commands that run in the same PSSession can share data, such as the values of variables, aliases, and functions. +When you create a PSSession, Windows PowerShell establishes a persistent +connection to the remote computer. Use a PSSession to run a series of related +commands on a remote computer. Commands that run in the same PSSession can +share data, such as the values of variables, aliases, and functions. -You can also create a PSSession on the local computer and run commands in it. A local PSSession uses the Windows PowerShell remoting infrastructure to create and maintain the PSSession. +You can also create a PSSession on the local computer and run commands in it. +A local PSSession uses the Windows PowerShell remoting infrastructure to +create and maintain the PSSession. -Beginning in Windows PowerShell 3.0, PSSessions are independent of the sessions in which they are created. Active PSSessions are maintained on the remote computer (or the computer at the remote end or "server-side" of the connection). As a result, you can disconnect from the PSSession and reconnect to it at a later time from the same computer or from a different computer. +Beginning in Windows PowerShell 3.0, PSSessions are independent of the +sessions in which they are created. Active PSSessions are maintained on the +remote computer (or the computer at the remote end or "server-side" of the +connection). As a result, you can disconnect from the PSSession and reconnect +to it at a later time from the same computer or from a different computer. -This topic explains how to create, use, get, and delete PSSessions. For more advanced information, see [about_PSSession_Details](about_PSSession_Details.md). +This topic explains how to create, use, get, and delete PSSessions. For more +advanced information, see +[about_PSSession_Details](about_PSSession_Details.md). -Note: PSSessions use the Windows PowerShell remoting infrastructure. To use PSSessions, the local and remote computers must be configured for remoting. For more information, see [about_Remote_Requirements](about_Remote_Requirements.md). +Note: PSSessions use the Windows PowerShell remoting infrastructure. To use +PSSessions, the local and remote computers must be configured for remoting. +For more information, see +[about_Remote_Requirements](about_Remote_Requirements.md). -In Windows Vista and later versions of Windows, to create a PSSession on a local computer, you must start Windows PowerShell with the "Run as administrator" option. +In Windows Vista and later versions of Windows, to create a PSSession on a +local computer, you must start Windows PowerShell with the "Run as +administrator" option. ## What Is a Session? A session is an environment in which Windows PowerShell runs. -Each time you start Windows PowerShell, a session is created for you, and you can run commands in the session. You can also add items to your session, such as modules and snap-ins, and you can create items, such as variables, functions, and aliases. These items exist only in the session and are deleted when the session ends. - -You can also create user-managed sessions, known as " Windows PowerShell sessions" or "PSSessions," on the local computer or on a remote computer. Like the default session, you can run commands in a PSSession and add and create items. - -However, unlike the session that starts automatically, you can control the PSSessions that you create. You can get, create, configure, and remove them, disconnect and reconnect to them, and run multiple commands in the same PSSession. The PSSession remains available until you delete it or it times out. - -Typically, you create a PSSession to run a series of related commands on a remote computer. When you create a PSSession on a remote computer, Windows PowerShell establishes a persistent connection to the remote computer to support the session. - -If you use the **ComputerName** parameter of the `Invoke-Command` or `Enter-PSSession` cmdlet to run a remote command or to start an interactive session, Windows PowerShell creates a temporary session on the remote computer and closes the session as soon as the command is complete or as soon as the interactive session ends. You cannot control these temporary sessions, and you cannot use them for more than a single command or a single interactive session. - -In Windows PowerShell, the "current session" is the session that you are working in. The "current session" can refer to any session, including a temporary session or a PSSession. +Each time you start Windows PowerShell, a session is created for you, and you +can run commands in the session. You can also add items to your session, such +as modules and snap-ins, and you can create items, such as variables, +functions, and aliases. These items exist only in the session and are deleted +when the session ends. + +You can also create user-managed sessions, known as " Windows PowerShell +sessions" or "PSSessions," on the local computer or on a remote computer. Like +the default session, you can run commands in a PSSession and add and create +items. However, unlike the session that starts automatically, you can control +the PSSessions that you create. You can get, create, configure, and remove +them, disconnect and reconnect to them, and run multiple commands in the same +PSSession. The PSSession remains available until you delete it or it times +out. + +Typically, you create a PSSession to run a series of related commands on a +remote computer. When you create a PSSession on a remote computer, Windows +PowerShell establishes a persistent connection to the remote computer to +support the session. + +If you use the **ComputerName** parameter of the `Invoke-Command` or +`Enter-PSSession` cmdlet to run a remote command or to start an interactive +session, Windows PowerShell creates a temporary session on the remote computer +and closes the session as soon as the command is complete or as soon as the +interactive session ends. You cannot control these temporary sessions, and you +cannot use them for more than a single command or a single interactive +session. + +In Windows PowerShell, the "current session" is the session that you are +working in. The "current session" can refer to any session, including a +temporary session or a PSSession. ## Why Use a PSSession? -Use a PSSession when you need a persistent connection to a remote computer. With a PSSession, you can run a series of commands that share data, such as the value of variables, the contents of a function, or the definition of an alias. +Use a PSSession when you need a persistent connection to a remote computer. +With a PSSession, you can run a series of commands that share data, such as +the value of variables, the contents of a function, or the definition of an +alias. -You can run remote commands without creating a PSSession. Use the **ComputerName** parameter of remote-enabled cmdlets to run a single command or a series of unrelated commands on one or many computers. +You can run remote commands without creating a PSSession. Use the +**ComputerName** parameter of remote-enabled cmdlets to run a single command +or a series of unrelated commands on one or many computers. -When you use the **ComputerName** parameter of `Invoke-Command` or `Enter-PSSession`, Windows PowerShell establishes a temporary connection to the remote computer and then closes the connection as soon as the command is complete. Any data elements that you create are lost when the connection is closed. +When you use the **ComputerName** parameter of `Invoke-Command` or +`Enter-PSSession`, Windows PowerShell establishes a temporary connection to +the remote computer and then closes the connection as soon as the command is +complete. Any data elements that you create are lost when the connection is +closed. -Other cmdlets that have a **ComputerName** parameter, such as `Get-Eventlog` and `Get-WmiObject`, use different remoting technologies to gather data. None create a persistent connection like a PSSession. +Other cmdlets that have a **ComputerName** parameter, such as `Get-Eventlog` +and `Get-WmiObject`, use different remoting technologies to gather data. None +create a persistent connection like a PSSession. ## How to Create a PSSession -To create a PSSession, use the `New-PSSession` cmdlet. To create the PSSession on a remote computer, use the **ComputerName** parameter of the `New-PSSession` cmdlet. +To create a PSSession, use the `New-PSSession` cmdlet. To create the PSSession +on a remote computer, use the **ComputerName** parameter of the +`New-PSSession` cmdlet. -For example, the following command creates a new PSSession on the Server01 computer. +For example, the following command creates a new PSSession on the Server01 +computer. ```powershell New-PSSession -ComputerName Server01 ``` -When you submit the command, `New-PSSession` creates the PSSession and returns an object that represents the PSSession. You can save the object in a variable when you create the PSSession, or you can use a `Get-PSSession` command to get the PSSession at a later time. +When you submit the command, `New-PSSession` creates the PSSession and returns +an object that represents the PSSession. You can save the object in a variable +when you create the PSSession, or you can use a `Get-PSSession` command to get +the PSSession at a later time. -For example, the following command creates a new PSSession on the Server01 computer and saves the resulting object in the $ps variable. +For example, the following command creates a new PSSession on the Server01 +computer and saves the resulting object in the $ps variable. ```powershell $ps = New-PSSession -ComputerName Server01 @@ -74,9 +131,12 @@ $ps = New-PSSession -ComputerName Server01 ## How to Create PSSessions on Multiple Computers -To create PSSessions on multiple computers, use the **ComputerName** parameter of the `New-PSSession` cmdlet. Type the names of the remote computers in a comma-separated list. +To create PSSessions on multiple computers, use the **ComputerName** parameter +of the `New-PSSession` cmdlet. Type the names of the remote computers in a +comma-separated list. -For example, to create PSSessions on the Server01, Server02, and Server03 computers, type: +For example, to create PSSessions on the Server01, Server02, and Server03 +computers, type: ```powershell New-PSSession -ComputerName Server01, Server02, Server03 @@ -86,7 +146,9 @@ New-PSSession -ComputerName Server01, Server02, Server03 ## How to Get PSSessions -To get the PSSessions that were created in your current session, use the `Get-PSSession` cmdlet without the **ComputerName** parameter. `Get-PSSession` returns the same type of object that `New-PSSession` returns. +To get the PSSessions that were created in your current session, use the +`Get-PSSession` cmdlet without the **ComputerName** parameter. `Get-PSSession` +returns the same type of object that `New-PSSession` returns. The following command gets all the PSSessions that were created in the current session. @@ -94,9 +156,10 @@ The following command gets all the PSSessions that were created in the current s Get-PSSession ``` -The default display of the PSSessions shows their ID and a default display name. You can assign an alternate display name when you create the session. +The default display of the PSSessions shows their ID and a default display +name. You can assign an alternate display name when you create the session. -``` +```output Id Name ComputerName State ConfigurationName --- ---- ------------ ----- --------------------- 1 Session1 Server01 Opened Microsoft.PowerShell @@ -104,31 +167,45 @@ Id Name ComputerName State ConfigurationName 3 Session3 Server03 Opened Microsoft.PowerShell ``` -You can also save the PSSessions in a variable. The following command gets the PSSessions and saves them in the $ps123 variable. +You can also save the PSSessions in a variable. The following command gets the +PSSessions and saves them in the \$ps123 variable. ```powershell $ps123 = Get-PSSession ``` -When using the PSSession cmdlets, you can refer to a PSSession by its ID, by its name, or by its instance ID (a GUID). The following command gets a PSSession by its ID and saves it in the $ps01 variable. +When using the PSSession cmdlets, you can refer to a PSSession by its ID, by +its name, or by its instance ID (a GUID). The following command gets a +PSSession by its ID and saves it in the \$ps01 variable. ```powershell $ps01 = Get-PSSession -Id 1 ``` -Beginning in Windows PowerShell 3.0, PSSessions are maintained on the remote computer. To get PSSessions that you created on particular remote computers, use the **ComputerName** parameter of the `Get-PSSession` cmdlet. The following command gets the PSSessions that you created on the Server01 remote computer. This includes PSSessions created in the current session and in other sessions on the local computer or other computers. +Beginning in Windows PowerShell 3.0, PSSessions are maintained on the remote +computer. To get PSSessions that you created on particular remote computers, +use the **ComputerName** parameter of the `Get-PSSession` cmdlet. The +following command gets the PSSessions that you created on the Server01 remote +computer. This includes PSSessions created in the current session and in other +sessions on the local computer or other computers. ```powershell Get-PSSession -ComputerName Server01 ``` -In Windows PowerShell 2.0, `Get-PSSession` gets only the PSSessions that were created in the current session. It does not get PSSessions that were created in other sessions or on other computers, even if the sessions are connected to and are running commands on the local computer. +In Windows PowerShell 2.0, `Get-PSSession` gets only the PSSessions that were +created in the current session. It does not get PSSessions that were created +in other sessions or on other computers, even if the sessions are connected to +and are running commands on the local computer. ## How to Run Commands in a PSSession -To run a command in one or more PSSessions, use the `Invoke-Command` cmdlet. Use the Session parameter to specify the PSSessions and the **ScriptBlock** parameter to specify the command. +To run a command in one or more PSSessions, use the `Invoke-Command` cmdlet. +Use the Session parameter to specify the PSSessions and the **ScriptBlock** +parameter to specify the command. -For example, to run a `Get-ChildItem` ("dir") command in each of the three PSSessions saved in the $ps123 variable, type: +For example, to run a `Get-ChildItem` ("dir") command in each of the three +PSSessions saved in the $ps123 variable, type: ```powershell Invoke-Command -Session $ps123 -ScriptBlock { Get-ChildItem } @@ -136,7 +213,8 @@ Invoke-Command -Session $ps123 -ScriptBlock { Get-ChildItem } ## How to Delete PSSessions -When you are finished with the PSSession, use the `Remove-PSSession` cmdlet to delete the PSSession and to release the resources that it was using. +When you are finished with the PSSession, use the `Remove-PSSession` cmdlet to +delete the PSSession and to release the resources that it was using. ```powershell Remove-PSSession -Session $ps @@ -148,35 +226,38 @@ or Remove-PSSession -Id 1 ``` -To remove a PSSession from a remote computer, use the **ComputerName** parameter of the `Remove-PSSession` cmdlet. +To remove a PSSession from a remote computer, use the **ComputerName** +parameter of the `Remove-PSSession` cmdlet. ```powershell Remove-PSSession -ComputerName Server01 -Id 1 ``` -If you do not delete the PSSession, the PSSession remains available for use until it times out. +If you do not delete the PSSession, the PSSession remains available for use +until it times out. -You can also use the **IdleTimeout** parameter of the `New-PSSessionOption` cmdlet to set an expiration time for an idle PSSession. For more information, see [New-PSSessionOption](../New-PSSessionOption.md). +You can also use the **IdleTimeout** parameter of the `New-PSSessionOption` +cmdlet to set an expiration time for an idle PSSession. For more information, +see [New-PSSessionOption](../New-PSSessionOption.md). ## The PSSession Cmdlets -| Cmdlet | Description | -| -------------------- | --------------------------------------------------------------- | -| Connect-PSSession | Connects a PSSession to the current session | -| Disconnect-PSSession | Disconnects a PSSession from the current session | -| Enter-PSSession | Starts an interactive session | -| Exit-PSSession | Ends an interactive session | -| Get-PSSession | Gets the PSSessions in the current session | -| New-PSSession | Creates a new PSSession on a local or remote computer | -| Receive-PSSession | Gets the results of commands that ran in a disconnected session | -| Remove-PSSession | Deletes the PSSessions in the current session | - For a list of PSSession cmdlets, type: ```powershell Get-Help *-PSSession ``` +- Connect-PSSession: Connects a PSSession to the current session +- Disconnect-PSSession: Disconnects a PSSession from the current session +- Enter-PSSession: Starts an interactive session +- Exit-PSSession: Ends an interactive session +- Get-PSSession: Gets the PSSessions in the current session +- New-PSSession: Creates a new PSSession on a local or remote computer +- Receive-PSSession: Gets the results of commands that ran in a disconnected + session +- Remove-PSSession: Deletes the PSSessions in the current session + ## For More Information For more information about PSSessions, see [about_PSSession_Details](about_PSSession_Details.md). diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_PSSnapins.md b/reference/6/Microsoft.PowerShell.Core/About/about_PSSnapins.md deleted file mode 100644 index bab6da6892d1..000000000000 --- a/reference/6/Microsoft.PowerShell.Core/About/about_PSSnapins.md +++ /dev/null @@ -1,181 +0,0 @@ ---- -ms.date: 2017-06-09 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_PSSnapins ---- - -# About PSSnapins -## about_PSSnapins - - -## SHORT DESCRIPTION -Describes Windows PowerShell snap-ins and shows how to use and manage them. - - -## LONG DESCRIPTION -A Windows PowerShell snap-in is a Microsoft .NET Framework assembly that contains Windows PowerShell providers and\/or cmdlets. Windows PowerShell includes a set of basic snap-ins, but you can extend the power and value of Windows PowerShell by adding snap-ins that contain providers and cmdlets that you create or get from others. - -When you add a snap-in, the cmdlets and providers that it contains are immediately available for use in the current session, but the change affects only the current session. - -To add the snap-in to all future sessions, save it in your Windows PowerShell profile. You can also use the Export-Console cmdlet to save the snap-in names to a console file and then use it in future sessions. You can even save multiple console files, each with a different set of snap-ins. - -NOTE: Windows PowerShell snap-ins (PSSnapins) are available for use in Windows PowerShell 3.0 and Windows PowerShell 2.0. They might be altered or unavailable in subsequent versions. To package Windows PowerShell cmdlets and providers, use modules. For information about creating modules and converting snap-ins to modules, see "Writing a Windows PowerShell Module" in MSDN at http:\/\/go.microsoft.com\/fwlink\/?LinkID\=141556. - - -### FINDING SNAP-INS -To get a list of the Windows PowerShell snap-ins on your computer, type: - - -``` -get-pssnapin -``` - - -To get the snap-in for each Windows PowerShell provider, type: - - -``` -get-psprovider | format-list name, pssnapin -``` - - -To get a list of the cmdlets in a Windows PowerShell snap-in, type: - - -``` -get-command -module -``` - - - -### INSTALLING A SNAP-IN -The built-in snap-ins are registered in the system and added to the default session when you start Windows PowerShell. However, you have to register snap-ins that you create or obtain from others and then add the snap-ins to your session. - - -### REGISTERING A SNAP-IN -A Windows PowerShell snap-in is a program written in a .NET Framework language that is compiled into a .dll file. To use the providers and cmdlets in a snap-in, you must first register the snap-in (add it to the registry). - -Most snap-ins include an installation program (an .exe or .msi file) that registers the .dll file for you. However, if you receive a snap-in as a .dll file, you can register it on your system. For more information, see [How to Register Cmdlets, Providers, and Host Applications](https://go.microsoft.com/fwlink/?LinkID=143619) in the MSDN library. - -To get all the registered snap-ins on your system or to verify that a snap-in is registered, type: - - -``` -get-pssnapin -registered -``` - - - -### ADDING THE SNAP-IN TO THE CURRENT SESSION -To add a registered snap-in to the current session, use the Add-PsSnapin cmdlet. For example, to add the Microsoft SQL Server snap-in to the session, type: - - -``` -add-pssnapin sql -``` - - -After the command is completed, the providers and cmdlets in the snap-in are available in the session. However, they are available only in the current session unless you save them. - - -### SAVING THE SNAP-INS -To use a snap-in in future Windows PowerShell sessions, add the Add-PsSnapin command to your Windows PowerShell profile. Or, export the snap-in names to a console file. - -If you add the Add-PSSnapin command to your profile, it is available in all future Windows PowerShell sessions. If you export the names of the snap-ins in your session, you can use the export file only when you need the snap-ins. - -To add the Add-PsSnapin command to your Windows PowerShell profile, open your profile, paste or type the command, and then save the profile. For more information, see about_Profiles. - -To save the snap-ins from a session in console file (.psc1), use the Export-Console cmdlet. For example, to save the snap-ins in the current session configuration to the NewConsole.psc1 file in the current directory, type: - - -``` -export-console NewConsole -``` - - -For more information, see Export-Console. - - -### OPENING WINDOWS POWERSHELL WITH A CONSOLE FILE -To use a console file that includes the snap-in, start Windows PowerShell (PowerShell.exe) from the command prompt in Cmd.exe or in another Windows PowerShell session. Use the PsConsoleFile parameter to specify the console file that includes the snap-in. For example, the following command starts Windows PowerShell with the NewConsole.psc1 console file: - - -``` -PowerShell.exe -psconsolefile NewConsole.psc1 -``` - - -The providers and cmdlets in the snapin are now available for use in the session. - - -### REMOVING A SNAP-IN -To remove a Windows PowerShell snap-in from the current session, use the Remove-PsSnapin cmdlet. For example, to remove the SQL Server snap-in from the current session, type: - - -``` -remove-pssnapin sql -``` - - -This cmdlet removes the snap-in from the session. The snap-in is still loaded, but the providers and cmdlets that it supports are no longer available. - - -### BUILT-IN COMMANDS -In Windows PowerShell 2.0 and in older-style host programs in Windows PowerShell 3.0 and later, the built-in commands that are installed with Windows PowerShell are packaged in snap-ins that are added automatically to every Windows PowerShell session. - -Beginning in Windows PowerShell 3.0, in newer-style host programs -- those that start sessions by using the InitialSessionState.CreateDefault2 method -- the built-in commands are packaged in modules. The exception is Microsoft.PowerShell.Core, which always appears as a snap-in. The Core snap-in is included in every session by default. The built-in modules are loaded automatically on first-use. - -NOTE: Remote sessions, including sessions that are started by using the New-PSSession cmdlet, are older-style sessions in which the built-in commands are packaged in snap-ins. - -The following snap-ins (or modules) are installed with Windows PowerShell. - -Microsoft.PowerShell.Core - -Contains providers and cmdlets used to manage the basic features of Windows PowerShell. It includes the FileSystem, Registry, Alias, Environment, Function, and Variable providers and basic cmdlets like Get-Help, Get-Command, and Get-History. - -Microsoft.PowerShell.Host - -Contains cmdlets used by the Windows PowerShell host, such as Start-Transcript and Stop-Transcript. - -Microsoft.PowerShell.Management - -Contains cmdlets such as Get-Service and Get-ChildItem that are used to manage Windows-based features. - -Microsoft.PowerShell.Security - -Contains the Certificate provider and cmdlets used to manage Windows PowerShell security, such as Get-Acl, Get-AuthenticodeSignature, and ConvertTo-SecureString. - -Microsoft.PowerShell.Utility - -Contains cmdlets used to manipulate objects and data, such as Get-Member, Write-Host, and Format-List. - -Microsoft.WSMan.Management - -Contains the WSMan provider and cmdlets that manage the Windows Remote Management service, such as Connect-WSMan and Enable-WSManCredSSP. - - -## LOGGING SNAP-IN EVENTS -Beginning in Windows PowerShell 3.0, you can record execution events for the cmdlets in Windows PowerShell modules and snap-ins by setting the LogPipelineExecutionDetails property of modules and snap-ins to TRUE. For more information, see about_EventLogs (http:\/\/go.microsoft.com\/fwlink\/?LinkID\=113224). - - -## SEE ALSO - -Add-PsSnapin - -Get-PsSnapin - -Remove-PsSnapin - -Export-Console - -Get-Command - -[about_Profiles](about_Profiles.md) - -[about_Modules](about_Modules.md) - -## KEYWORDS: -about_Snapins, about_Snap_ins, about_Snap-ins - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_PackageManagement.md b/reference/6/Microsoft.PowerShell.Core/About/about_PackageManagement.md index 7933f7f0a80e..32789dca75ab 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_PackageManagement.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_PackageManagement.md @@ -104,24 +104,24 @@ 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 +## SEE ALSO -Get-PackageProvider +[Get-PackageProvider](../../PackageManagement/Get-PackageProvider.md) -Get-PackageSource +[Get-PackageSource](../../PackageManagement/Get-PackageSource.md) -Register-PackageSource +[Register-PackageSource](../../PackageManagement/Register-PackageSource.md) -Set-PackageSource +[Set-PackageSource](../../PackageManagement/Set-PackageSource.md) -Unregister-PackageSource +[Unregister-PackageSource](../../PackageManagement/Unregister-PackageSource.md) -Get-Package +[Get-Package](../../PackageManagement/Get-Package.md) -Find-Package +[Find-Package](../../PackageManagement/Find-Package.md) -Install-Package +[Install-Package](../../PackageManagement/Install-Package.md) -Save-Package +[Save-Package](../../PackageManagement/Save-Package.md) -Uninstall-Package +[Uninstall-Package](../../PackageManagement/Uninstall-Package.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Parameters.md b/reference/6/Microsoft.PowerShell.Core/About/about_Parameters.md index 37c6f1b3c26e..b74b7e5b0cb0 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Parameters.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Parameters.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,197 +7,227 @@ title: about_Parameters --- # About Parameters -## about_Parameters - ## SHORT DESCRIPTION -Describes how to work with command parameters in Windows PowerShell. +Describes how to work with command parameters in PowerShell. ## LONG DESCRIPTION -Most Windows PowerShell commands, such as cmdlets, functions, and scripts, rely on parameters to allow users to select options or provide input. The parameters follow the command name and have the following form: +Most PowerShell commands, such as cmdlets, functions, and scripts, +rely on parameters to allow users to select options or provide input. The +parameters follow the command name and have the following form: ``` - ``` +The name of the parameter is preceded by a hyphen (-), which signals to +Windows PowerShell that the word following the hyphen is a parameter name. +Some parameters do not require or accept a parameter value. Other parameters +require a value, but do not require the parameter name in the command. -The name of the parameter is preceded by a hyphen (-), which signals to Windows PowerShell that the word following the hyphen is a parameter name. Some parameters do not require or accept a parameter value. Other parameters require a value, but do not require the parameter name in the command. - -The type of parameters and the requirements for those parameters vary. To find information about the parameters of a command, use the Get-Help cmdlet. For example, to find information about the parameters of the Get-ChildItem cmdlet, type: +The type of parameters and the requirements for those parameters vary. To find +information about the parameters of a command, use the Get-Help cmdlet. For +example, to find information about the parameters of the Get-ChildItem cmdlet, +type: -``` +```powershell Get-Help Get-ChildItem ``` +To find information about the parameters of a script, use the full path to the +script file. For example: -To find information about the parameters of a script, use the full path to the script file. For example: - - -``` +```powershell Get-Help $home\Documents\Scripts\Get-Function.ps1 ``` +The Get-Help cmdlet returns various details about the command, including a +description, the command syntax, information about the parameters, and +examples showing how to use the parameters in a command. -The Get-Help cmdlet returns various details about the command, including a description, the command syntax, information about the parameters, and examples showing how to use the parameters in a command. - -You can also use the Parameter parameter of the Get-Help cmdlet to find information about a particular parameter. Or, you can use the Parameter parameter with the wildcard character (\*) value to find information about all parameters of the command. For example, the following command gets information about all parameters of the Get-Member cmdlet: +You can also use the Parameter parameter of the Get-Help cmdlet to find +information about a particular parameter. Or, you can use the Parameter +parameter with the wildcard character (\*) value to find information about all +parameters of the command. For example, the following command gets information +about all parameters of the Get-Member cmdlet: -``` +```powershell Get-Help Get-Member -Parameter * ``` ### DEFAULT PARAMETER VALUES -Optional parameters have a default value, which is the value that is used or assumed when the parameter is not specified in the command. -For example, the default value of the ComputerName parameter of many cmdlets is the name of the local computer. As a result, the local computer name is used in the command unless the ComputerName parameter is specified. +Optional parameters have a default value, which is the value that is used or +assumed when the parameter is not specified in the command. -To find the default parameter value, see help topic for the cmdlet. The parameter description should include the default value. +For example, the default value of the ComputerName parameter of many cmdlets +is the name of the local computer. As a result, the local computer name is +used in the command unless the ComputerName parameter is specified. -You can also set a custom default value for any parameter of a cmdlet or advanced function. For information about setting custom default values, see about_Parameters_Default_Values. +To find the default parameter value, see help topic for the cmdlet. The +parameter description should include the default value. +You can also set a custom default value for any parameter of a cmdlet or +advanced function. For information about setting custom default values, see +[about_Parameters_Default_Values](about_Parameters_Default_Values.md). ### PARAMETER ATTRIBUTE TABLE -When you use the Full, Parameter, or Online parameters of the Get-Help cmdlet, Get-Help displays a parameter attribute table with detailed information about the parameter. -This information includes the details you need to know to use the parameter. For example, the help topic for the Get-ChildItem cmdlet includes the following details about its Path parameter: +When you use the Full, Parameter, or Online parameters of the Get-Help cmdlet, +Get-Help displays a parameter attribute table with detailed information about +the parameter. + +This information includes the details you need to know to use the parameter. +For example, the help topic for the Get-ChildItem cmdlet includes the +following details about its Path parameter: ``` --path - Specifies a path of one or more locations. Wildcard characters are +-path + Specifies a path of one or more locations. Wildcard characters are permitted. The default location is the current directory (.). -``` - - -``` -Required? false -Position? 1 -Default value Current directory -Accept pipeline input? true (ByValue, ByPropertyName) +Required? false +Position? 1 +Default value Current directory +Accept pipeline input? true (ByValue, ByPropertyName) Accept wildcard characters? true ``` +The parameter information includes the parameter syntax, a description of the +parameter, and the parameter attributes. The following sections describe the +parameter attributes. -The parameter information includes the parameter syntax, a description of the parameter, and the parameter attributes. The following sections describe the parameter attributes. +#### Parameter Required? -Parameter Required? +This setting indicates whether the parameter is mandatory, that is, whether +all commands that use this cmdlet must include this parameter. When the value +is "True" and the parameter is missing from the command, Windows PowerShell +prompts you for a value for the parameter. -This setting indicates whether the parameter is mandatory, that is, whether all commands that use this cmdlet must include this parameter. When the value is "True" and the parameter is missing from the command, Windows PowerShell prompts you for a value for the parameter. +#### Parameter Position? -Parameter Position? +This setting indicates whether you can supply a parameter's value without +preceding it with the parameter name. If set to "0" or "named," a parameter +name is required. This type of parameter is referred to as a named parameter. +A named parameter can be listed in any position after the cmdlet name. -This setting indicates whether you can supply a parameter's value without preceding it with the parameter name. If set to "0" or "named," a parameter name is required. This type of parameter is referred to as a named parameter. A named parameter can be listed in any position after the cmdlet name. +If the "Parameter position?" setting is set to an integer other than 0, the +parameter name is not required. This type of parameter is referred to as a +positional parameter, and the number indicates the position in which the +parameter must appear in relation to other positional parameters. If you +include the parameter name for a positional parameter, the parameter can be +listed in any position after the cmdlet name. -If the "Parameter position?" setting is set to an integer other than 0, the parameter name is not required. This type of parameter is referred to as a positional parameter, and the number indicates the position in which the parameter must appear in relation to other positional parameters. If you include the parameter name for a positional parameter, the parameter can be listed in any position after the cmdlet name. +For example, the Get-ChildItem cmdlet has Path and Exclude parameters. The +"Parameter position?" setting for Path is 1, which means that it is a +positional parameter. The "Parameter position?" setting for Exclude is 0, +which means that it is a named parameter. -For example, the Get-ChildItem cmdlet has Path and Exclude parameters. The "Parameter position?" setting for Path is 1, which means that it is a positional parameter. The "Parameter position?" setting for Exclude is 0, which means that it is a named parameter. +This means that Path does not require the parameter name, but its parameter +value must be the first or only unnamed parameter value in the command. +However, because the Exclude parameter is a named parameter, you can place it +in any position in the command. -This means that Path does not require the parameter name, but its parameter value must be the first or only unnamed parameter value in the command. However, because the Exclude parameter is a named parameter, you can place it in any position in the command. +As a result of the "Parameter position?" settings for these two parameters, +you can use any of the following commands: -As a result of the "Parameter position?" settings for these two parameters, you can use any of the following commands: - -``` -Get-ChildItem -path c:\techdocs -exclude *.ppt -Get-ChildItem c:\techdocs -exclude *.ppt -Get-ChildItem -exclude *.ppt -path c:\techdocs +```powershell +Get-ChildItem -path c:\techdocs -exclude *.ppt +Get-ChildItem c:\techdocs -exclude *.ppt +Get-ChildItem -exclude *.ppt -path c:\techdocs Get-ChildItem -exclude *.ppt c:\techdocs ``` +If you were to include another positional parameter without including the +parameter name, that parameter would have to be placed in the order specified +by the "Parameter position?" setting. -If you were to include another positional parameter without including the parameter name, that parameter would have to be placed in the order specified by the "Parameter position?" setting. +#### Parameter Type -Parameter Type +This setting specifies the Microsoft .NET Framework type of the parameter +value. For example, if the type is Int32, the parameter value must be an +integer. If the type is string, the parameter value must be a character +string. If the string contains spaces, the value must be enclosed in quotation +marks, or the spaces must be preceded by the escape character (`). -This setting specifies the Microsoft .NET Framework type of the parameter value. For example, if the type is Int32, the parameter value must be an integer. If the type is string, the parameter value must be a character string. If the string contains spaces, the value must be enclosed in quotation marks, or the spaces must be preceded by the escape character (`). +#### Default Value -Default Value +This setting specifies the value that the parameter will assume if no other +value is provided. For example, the default value of the Path parameter is +often the current directory. Required parameters never have a default value. +For many optional parameters, there is no default because the parameter has no +effect if it is not used. -This setting specifies the value that the parameter will assume if no other value is provided. For example, the default value of the Path parameter is often the current directory. Required parameters never have a default value. For many optional parameters, there is no default because the parameter has no effect if it is not used. +#### Accepts Multiple Values? -Accepts Multiple Values? +This setting indicates whether a parameter accepts multiple parameter values. +When a parameter accepts multiple values, you can type a comma-separated list +as the value of the parameter in the command, or save a comma-separated list +(an array) in a variable, and then specify the variable as the parameter +value. -This setting indicates whether a parameter accepts multiple parameter values. When a parameter accepts multiple values, you can type a comma-separated list as the value of the parameter in the command, or save a comma-separated list (an array) in a variable, and then specify the variable as the parameter value. +For example, the ServiceName parameter of the Get-Service cmdlet accepts +multiple values. The following commands are both valid: -For example, the ServiceName parameter of the Get-Service cmdlet accepts multiple values. The following commands are both valid: - - -``` +```powershell get-service -servicename winrm, netlogon ``` - - -``` -$s = "winrm", "netlogon" +```powershell +$s = "winrm", "netlogon" get-service -servicename $s ``` +#### Accepts Pipeline Input? -Accepts Pipeline Input? - -This setting indicates whether you can use the pipeline operator (|) to send a value to the parameter. - +This setting indicates whether you can use the pipeline operator (|) to +send a value to the parameter. ``` -Value Description ------ ----------- -False Indicates that you cannot pipe a value to the +Value Description +----- ----------- +False Indicates that you cannot pipe a value to the parameter. -``` - - -``` -True (by Value) Indicates that you can pipe any value to the - parameter, just so the value has the .NET - Framework type specified for the parameter or the - value can be converted to the specified .NET +True (by Value) Indicates that you can pipe any value to the + parameter, just so the value has the .NET + Framework type specified for the parameter or the + value can be converted to the specified .NET Framework type. ``` - - -``` -When a parameter is "True (by Value)", Windows -PowerShell tries to associate any piped values -with that parameter before it tries other methods -to interpret the command. -``` - - +When a parameter is "True (by Value)", Windows PowerShell tries to associate +any piped values with that parameter before it tries other methods to +interpret the command. ``` -True (by Property Name) Indicates that you can pipe a value to the - parameter, but the .NET Framework type of the - parameter must include a property with the same +True (by Property Name) Indicates that you can pipe a value to the + parameter, but the .NET Framework type of the + parameter must include a property with the same name as the parameter. ``` +For example, you can pipe a value to a Name parameter only when the value has +a property called "Name". +#### Accepts Wildcard Characters? -``` -For example, you can pipe a value to a Name -parameter only when the value has a property -called "Name". -``` - - -Accepts Wildcard Characters? - -This setting indicates whether the parameter's value can contain wildcard characters so that the parameter value can be matched to more than one existing item in the target container. +This setting indicates whether the parameter's value can contain wildcard +characters so that the parameter value can be matched to more than one +existing item in the target container. -Common Parameters - -Common parameters are parameters that you can use with any cmdlet. For more information about common parameters, see about_CommonParameters +#### Common Parameters +Common parameters are parameters that you can use with any cmdlet. For more +information about common parameters, see [about_CommonParameters](about_CommonParameters.md). ## SEE ALSO @@ -212,4 +242,3 @@ Common parameters are parameters that you can use with any cmdlet. For more info [about_Pipelines](about_Pipelines.md) [about_Wildcards](about_Wildcards.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_PowerShell_Ise_exe.md b/reference/6/Microsoft.PowerShell.Core/About/about_PowerShell_Ise_exe.md deleted file mode 100644 index a14a0cea93c2..000000000000 --- a/reference/6/Microsoft.PowerShell.Core/About/about_PowerShell_Ise_exe.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -ms.date: 2017-06-09 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_PowerShell_Ise_exe ---- - -# About PowerShell Ise.exe -## about_PowerShell_Ise.exe - - -# SHORT DESCRIPTION - -Explains how to use the PowerShell_Ise.exe command-line tool. - -# LONG DESCRIPTION - -PowerShell_Ise.exe starts a Windows PowerShell Integrated -Scripting Environment (ISE) session. You can run it in Cmd.exe -and in Windows PowerShell. - -To run PowerShell_ISE.exe, type PowerShell_ISE.exe, PowerShell_ISE, -or ISE. - -# SYNTAX - -PowerShell_Ise[.exe] -PowerShell_ISE[.exe] -ISE[.exe] -[-File] [-NoProfile] [-MTA] --Help | ? | -? | /? -Displays the syntax and describes the command-line switches. - -# PARAMETERS - --File -Opens the specified files in Windows PowerShell ISE. The -parameter name ("-File") is optional. To list more than one -file, enter one text string enclosed in quotation marks. Use -commas to separate the file names within the string. - -For example: -PowerShell_ISE -File "File1.ps1,File2.ps1,File3.xml". - -Spaces between the file names are permitted in Windows PowerShell, -but might not be interpreted correctly by other programs, such as -Cmd.exe. - -You can use this parameter to open any text file, including Windows -PowerShell script files and XML files. - --Mta -Starts Windows PowerShell ISE using a multi-threaded apartment. This -parameter is introduced in Windows PowerShell 3.0. Single-threaded -apartment (STA) is the default. - --NoProfile -Does not run Windows PowerShell profiles. By default, Windows PowerShell -profiles are run in every session. - -This parameter is recommended when you are writing shared content, such as -functions and scripts that will be run on systems with different profiles. -For more information, see about_Profiles -(http://go.microsoft.com/fwlink/?LinkID=113729). - --Help, -?, /? -Displays help for PowerShell_ISE.exe. - -# EXAMPLES - -These commands start Windows PowerShell ISE. The commands are equivalent -and can be used interchangeably. - -PS C:> PowerShell_ISE.exe -PS C:> PowerShell_ISE -# PS C:>ISE - - -These commands open the Get-Profile.ps1 script in Windows PowerShell ISE. -The commands are equivalent and can be used interchangeably. - -PS C:> PowerShell_ISE.exe -File .\Get-Profile.ps1 -PS C:> ISE -File .\Get-Profile.ps1 -PS C:> ISE .\Get-Profile.ps1 - -This command opens the Get-Backups.ps1 and Get-BackupInstance.ps1 scripts -in Windows PowerShell ISE. To open more than one file, use a comma to -separate the file names and enclose the entire file name value in quotation -marks. - -PS C:> ISE -File ".\Get-Backups.ps1,Get-BackupInstance.ps1" - -This command starts Windows PowerShell ISE with no profiles. - -PS C:> ISE -NoProfile - -This command gets help for PowerShell_ISE.exe. - -PS C:> ISE -help - -# SEE ALSO - -[about_pwsh](about_pwsh.md) - -[about_Windows_PowerShell_ISE](about_Windows_PowerShell_ISE.md) - -Windows PowerShell 3.0 Integrated Scripting Environment (ISE) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Providers.md b/reference/6/Microsoft.PowerShell.Core/About/about_Providers.md index 2a2e72a3ad3a..8080f77944b9 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Providers.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Providers.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,61 +7,58 @@ title: about_Providers --- # About Providers -## about_Providers - -# SHORT DESCRIPTION +## SHORT DESCRIPTION Describes how Windows PowerShell providers provide access to data and -components that would not otherwise be easily accessible at the command -line. The data is presented in a consistent format that resembles a file -system drive. - -# LONG DESCRIPTION - -Windows PowerShell providers are Microsoft .NET Framework-based programs -that make the data in a specialized data store available in Windows -PowerShell so that you can view and manage it. - -The data that a provider exposes appears in a drive, and you access the -data in a path like you would on a hard disk drive. You can use any of the -built-in cmdlets that the provider supports to manage the data in the -provider drive. And, you can use custom cmdlets that are designed -especially for the data. - -The providers can also add dynamic parameters to the built-in cmdlets. -These are parameters that are available only when you use the cmdlet with -the provider data. - -# BUILT-IN PROVIDERS - -Windows PowerShell includes a set of built-in providers that you can use -to access the different types of data stores. - -| Provider | Drive | Data store | -| ----------- | ------------ | ------------------------------------------ | -| Alias | Alias: | Windows PowerShell aliases | -| Certificate | Cert: | x509 certificates for digital signatures | -| Environment | Env: | Windows environment variables | -| FileSystem | (*) | File system drives, directories, and files | -| Function | Function: | Windows PowerShell functions | -| Registry | HKLM:, HKCU: | Windows registry | -| Variable | Variable: | Windows PowerShell variables | -| WSMan | WSMan: | WS-Management configuration information | +components that would not otherwise be easily accessible at the command line. +The data is presented in a consistent format that resembles a file system +drive. + +## LONG DESCRIPTION + +Windows PowerShell providers are Microsoft .NET Framework-based programs that +make the data in a specialized data store available in Windows PowerShell so +that you can view and manage it. + +The data that a provider exposes appears in a drive, and you access the data +in a path like you would on a hard disk drive. You can use any of the built-in +cmdlets that the provider supports to manage the data in the provider drive. +And, you can use custom cmdlets that are designed especially for the data. + +The providers can also add dynamic parameters to the built-in cmdlets. These +are parameters that are available only when you use the cmdlet with the +provider data. + +## BUILT-IN PROVIDERS + +Windows PowerShell includes a set of built-in providers that you can use to +access the different types of data stores. + +|Provider |Drive |Data store | +|------------|-------------|-------------------------------------------| +|Alias |Alias: |Windows PowerShell aliases | +|Certificate |Cert: |x509 certificates for digital signatures | +|Environment |Env: |Windows environment variables | +|FileSystem |(*) |File system drives, directories, and files | +|Function |Function: |Windows PowerShell functions | +|Registry |HKLM:, HKCU: |Windows registry | +|Variable |Variable: |Windows PowerShell variables | +|WSMan |WSMan: |WS-Management configuration information | (*) The FileSystem drives vary on each system. -You can also create your own Windows PowerShell providers, and you can -install providers that others develop. To list the providers that are -available in your session, type: +You can also create your own Windows PowerShell providers, and you can install +providers that others develop. To list the providers that are available in +your session, type: -Get-PSProvider +get-psprovider -# INSTALLING AND REMOVING PROVIDERS +## INSTALLING AND REMOVING PROVIDERS Windows PowerShell providers are delivered to you in Windows PowerShell -snap-ins, which are .NET Framework-based programs that are compiled -into .dll files. The snap-ins can include providers and cmdlets. +snap-ins, which are .NET Framework-based programs that are compiled into .dll +files. The snap-ins can include providers and cmdlets. Before you use the provider features, you have to install the snap-in and then add it to your Windows PowerShell session. For more information, see @@ -69,103 +66,106 @@ about_PSSnapins. You cannot uninstall a provider, although you can remove the Windows PowerShell snap-in for the provider from the current session. If you do, -you remove all the contents of the snap-in, including its cmdlets. +you will remove all the contents of the snap-in, including its cmdlets. To remove a provider from the current session, use the Remove-PSSnapin cmdlet. This cmdlet does not uninstall the provider, but it makes the provider unavailable in the session. You can also use the Remove-PSDrive cmdlet to remove any drive from the -current session. This data on the drive is not affected, but the drive is -no longer available in that session. +current session. This data on the drive is not affected, but the drive is no +longer available in that session. -# VIEWING PROVIDERS +## VIEWING PROVIDERS To view the Windows PowerShell providers on your computer, type: -Get-PSProvider +```powershell +get-psprovider +``` -The output lists the built-in providers and the providers that you added -to the session. +The output lists the built-in providers and the providers that you added to +the session. -# THE PROVIDER CMDLETS +## THE PROVIDER CMDLETS -The following cmdlets are designed to work with the data exposed by -any provider. You can use the same cmdlets in the same way to manage -the different types of data that providers expose. After you -learn to manage the data of one provider, you can use the same -procedures with the data from any provider. +The following cmdlets are designed to work with the data exposed by any +provider. You can use the same cmdlets in the same way to manage the different +types of data that providers expose. After you learn to manage the data of one +provider, you can use the same procedures with the data from any provider. -For example, the New-Item cmdlet creates a new item. In the C: drive that -is supported by the FileSystem provider, you can use New-Item to create a -new file or folder. In the drives that are supported by the Registry -provider, you can use New-Item to create a new registry key. In the Alias: -drive, you can use New-Item to create a new alias. +For example, the New-Item cmdlet creates a new item. In the C: drive that is +supported by the FileSystem provider, you can use New-Item to create a new +file or folder. In the drives that are supported by the Registry provider, you +can use New-Item to create a new registry key. In the Alias: drive, you can +use New-Item to create a new alias. For detailed information about any of the following cmdlets, type: -Get-Help -Detailed +``` +get-help -detailed +``` -# CHILDITEM CMDLETS +### CHILDITEM CMDLETS -Get-ChildItem +- Get-ChildItem -# CONTENT CMDLETS +### CONTENT CMDLETS -Add-Content -Clear-Content -Get-Content -Set-Content +- Add-Content +- Clear-Content +- Get-Content +- Set-Content -# ITEM CMDLETS +### ITEM CMDLETS -Clear-Item -Copy-Item -Get-Item -Invoke-Item -Move-Item -New-Item -Remove-Item -Rename-Item -Set-Item +- Clear-Item +- Copy-Item +- Get-Item +- Invoke-Item +- Move-Item +- New-Item +- Remove-Item +- Rename-Item +- Set-Item -# ITEMPROPERTY CMDLETS +### ITEMPROPERTY CMDLETS -Clear-ItemProperty -Copy-ItemProperty -Get-ItemProperty -Move-ItemProperty -New-ItemProperty -Remove-ItemProperty -Rename-ItemProperty -Set-ItemProperty +- Clear-ItemProperty +- Copy-ItemProperty +- Get-ItemProperty +- Move-ItemProperty +- New-ItemProperty +- Remove-ItemProperty +- Rename-ItemProperty +- Set-ItemProperty -# LOCATION CMDLETS +### LOCATION CMDLETS -Get-Location -Pop-Location -Push-Location -Set-Location +- Get-Location +- Pop-Location +- Push-Location +- Set-Location -# PATH CMDLETS +### PATH CMDLETS -Join-Path -Convert-Path -Split-Path -Resolve-Path -Test-Path +- Join-Path +- Convert-Path +- Split-Path +- Resolve-Path +- Test-Path -# PSDRIVE CMDLETS +### PSDRIVE CMDLETS -Get-PSDrive -New-PSDrive -Remove-PSDrive +- Get-PSDrive +- New-PSDrive +- Remove-PSDrive -# PSPROVIDER CMDLETS +### PSPROVIDER CMDLETS -Get-PSProvider +- Get-PSProvider -# VIEWING PROVIDER DATA +## VIEWING PROVIDER DATA The primary benefit of a provider is that it exposes its data in a familiar and consistent way. The model for data presentation is a file system @@ -181,7 +181,7 @@ but you can get information about the provider drive by using the Get-PSDrive cmdlet. For example, to get all the properties of the Function: drive, type: -Get-PSDrive Function | Format-List * +get-psdrive Function | format-list * You can view and move through the data in a provider drive just as you would on a file system drive. @@ -190,85 +190,108 @@ To view the contents of a provider drive, use the Get-Item or Get-ChildItem cmdlets. Type the drive name followed by a colon (:). For example, to view the contents of the Alias: drive, type: -Get-Item Alias: +```powershell +get-item alias: +``` You can view and manage the data in any drive from another drive by including the drive name in the path. For example, to view the HKLM\Software registry key in the HKLM: drive from another drive, type: -Get-ChildItem HKLM:\SOFTWARE +```powershell +get-childitem hklm:\software +``` To open the drive, use the Set-Location cmdlet. Remember the colon when you specify the drive path. For example, to change your location to the root directory of the Cert: drive, type: -Set-Location Cert: +```powershell +set-location cert: +``` Then, to view the contents of the Cert: drive, type: -Get-ChildItem +```powershell +get-childitem +``` -# MOVING THROUGH HIERARCHICAL DATA +## MOVING THROUGH HIERARCHICAL DATA You can move through a provider drive just as you would a hard disk drive. If the data is arranged in a hierarchy of items within items, use a backslash () to indicate a child item. Use the following format: +``` drive:\location\child-location\... +``` For example, to change your location to the HKLM\Software registry key, type a Set-Location command, such as: -Set-Location HKLM:\SOFTWARE +```powershell +set-location hklm:\software +``` You can also use relative references to locations. A dot (.) represents the current location. For example, if you are in the HKLM:\Software\Microsoft registry key, and you want to list the registry subkeys in the HKLM:\Software\Microsoft\PowerShell key, type the following command: -Get-ChildItem .\PowerShell +```powershell +get-childitem .\PowerShell +``` -# FINDING DYNAMIC PARAMETERS +## FINDING DYNAMIC PARAMETERS -Dynamic parameters are cmdlet parameters that are added to a cmdlet -by a provider. These parameters are available only when the cmdlet is -used with the provider that added them. +Dynamic parameters are cmdlet parameters that are added to a cmdlet by a +provider. These parameters are available only when the cmdlet is used with the +provider that added them. -For example, the Cert: drive adds the CodeSigningCert parameter -to the Get-Item and Get-ChildItem cmdlets. You can use this parameter -only when you use Get-Item or Get-ChildItem in the Cert: drive. +For example, the Cert: drive adds the CodeSigningCert parameter to the +Get-Item and Get-ChildItem cmdlets. You can use this parameter only when you +use Get-Item or Get-ChildItem in the Cert: drive. -For a list of the dynamic parameters that a provider supports, see the -Help file for the provider. Type: +For a list of the dynamic parameters that a provider supports, see the Help +file for the provider. Type: -Get-Help +``` +get-help +``` For example: -Get-Help Certificate +```powershell +get-help certificate +``` -# LEARNING ABOUT PROVIDERS +## LEARNING ABOUT PROVIDERS -Although all provider data appears in drives, and you use the same methods -to move through them, the similarity stops there. The data stores that -the provider exposes can be as varied as Active Directory locations and -Microsoft Exchange Server mailboxes. +Although all provider data appears in drives, and you use the same methods to +move through them, the similarity stops there. The data stores that the +provider exposes can be as varied as Active Directory locations and Microsoft +Exchange Server mailboxes. For information about individual Windows PowerShell providers, type: -Get-Help +``` +get-help +``` For example: -Get-Help Registry +```powershell +get-help registry +``` For a list of Help topics about the providers, type: -Get-Help * -Category provider +```powershell +get-help * -category provider +``` -# SEE ALSO +## SEE ALSO -about_Locations +[about_Locations](about_Locations.md) [about_Path_Syntax](about_Path_Syntax.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Quoting_Rules.md b/reference/6/Microsoft.PowerShell.Core/About/about_Quoting_Rules.md index 8e8248c24f78..8df82dca043b 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Quoting_Rules.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Quoting_Rules.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,290 +7,272 @@ title: about_Quoting_Rules --- # About Quoting Rules -## about_Quoting_Rules - ## SHORT DESCRIPTION -Describes rules for using single and double quotation marks in Windows PowerShell. +Describes rules for using single and double quotation marks in PowerShell. ## LONG DESCRIPTION -Quotation marks are used to specify a literal string. You can enclose a string in single quotation marks (') or double quotation marks ("). -Quotation marks are also used to create a here-string. A here-string is a single-quoted or double-quoted string in which quotation marks are interpreted literally. A here-string can span multiple lines. All the lines in a here-string are interpreted as strings, even though they are not enclosed in quotation marks. +Quotation marks are used to specify a literal string. You can enclose a string +in single quotation marks (') or double quotation marks ("). -In commands to remote computers, quotation marks define the parts of the command that are run on the remote computer. In a remote session, quotation marks also determine whether the variables in a command are interpreted first on the local computer or on the remote computer. +Quotation marks are also used to create a here-string. A here-string is a +single-quoted or double-quoted string in which quotation marks are interpreted +literally. A here-string can span multiple lines. All the lines in a +here-string are interpreted as strings, even though they are not enclosed in +quotation marks. +In commands to remote computers, quotation marks define the parts of the +command that are run on the remote computer. In a remote session, quotation +marks also determine whether the variables in a command are interpreted first +on the local computer or on the remote computer. ### SINGLE AND DOUBLE-QUOTED STRINGS -When you enclose a string in double quotation marks (a double-quoted string), variable names that are preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing. -For example: +When you enclose a string in double quotation marks (a double-quoted string), +variable names that are preceded by a dollar sign ($) are replaced with the +variable's value before the string is passed to the command for processing. +For example: -``` +```powershell $i = 5 "The value of $i is $i." ``` - The output of this command is: - -``` +```output The value of 5 is 5. ``` +Also, in a double-quoted string, expressions are evaluated, and the result is +inserted in the string. For example: -Also, in a double-quoted string, expressions are evaluated, and the result is inserted in the string. For example: - - -``` +```powershell "The value of $(2+3) is 5." ``` - The output of this command is: - -``` +```output The value of 5 is 5. ``` +When you enclose a string in single-quotation marks (a single-quoted string), +the string is passed to the command exactly as you type it. No substitution is +performed. For example: -When you enclose a string in single-quotation marks (a single-quoted string), the string is passed to the command exactly as you type it. No substitution is performed. For example: - - -``` +```powershell $i = 5 'The value of $i is $i.' ``` - The output of this command is: - -``` +```output The value $i is $i. ``` +Similarly, expressions in single-quoted strings are not evaluated. They are +interpreted as literals. For example: -Similarly, expressions in single-quoted strings are not evaluated. They are interpreted as literals. For example: - - -``` +```powershell 'The value of $(2+3) is 5.' ``` - The output of this command is: - -``` +```output The value of $(2+3) is 5. ``` +To prevent the substitution of a variable value in a double-quoted string, use +the backtick character (`)(ASCII 96), which is the Windows PowerShell escape +character. -To prevent the substitution of a variable value in a double-quoted string, use the backtick character (`)(ASCII 96), which is the Windows PowerShell escape character. - -In the following example, the backtick character that precedes the first $i variable prevents Windows PowerShell from replacing the variable name with its value. For example: - +In the following example, the backtick character that precedes the first $i +variable prevents Windows PowerShell from replacing the variable name with its +value. For example: -``` +```powershell $i = 5 "The value of `$i is $i." ``` - The output of this command is: - -``` +```output The value $i is 5. ``` +To make double-quotation marks appear in a string, enclose the entire string +in single quotation marks. For example: -To make double-quotation marks appear in a string, enclose the entire string in single quotation marks. For example: - - -``` +```powershell 'As they say, "live and learn."' ``` - The output of this command is: - -``` +```output As they say, "live and learn." ``` +You can also enclose a single-quoted string in a double-quoted string. For +example: -You can also enclose a single-quoted string in a double-quoted string. For example: - - -``` +```powershell "As they say, 'live and learn.'" ``` - The output of this command is: - -``` +```output As they say, 'live and learn.' ``` - Or, double the quotation marks around a double-quoted phrase. For example: - -``` +```powershell "As they say, ""live and learn.""" ``` - The output of this command is: - -``` +```output As they say, "live and learn." ``` +To include a single quotation mark in a single-quoted string, use a second +consecutive single quote. For example: -To include a single quotation mark in a single-quoted string, use a second consecutive single quote. For example: - - -``` +```powershell 'don''t' ``` - The output of this command is: - -``` +```output don't ``` +To force Windows PowerShell to interpret a double quotation mark literally, +use a backtick character. This prevents Windows PowerShell from interpreting +the quotation mark as a string delimiter. For example: -To force Windows PowerShell to interpret a double quotation mark literally, use a backtick character. This prevents Windows PowerShell from interpreting the quotation mark as a string delimiter. For example: - - -``` +```powershell "Use a quotation mark (`") to begin a string." ``` +Because the contents of single-quoted strings are interpreted literally, you +cannot use the backtick character to force a literal character interpretation +in a single-quoted string. -Because the contents of single-quoted strings are interpreted literally, you cannot use the backtick character to force a literal character interpretation in a single-quoted string. - -For example, the following command generates an error because Windows PowerShell does not recognize the escape character. Instead, it interprets the second quotation mark as the end of the string. - +For example, the following command generates an error because Windows +PowerShell does not recognize the escape character. Instead, it interprets the +second quotation mark as the end of the string. -``` +```output PS C:\> 'Use a quotation mark (`') to begin a string.' Unexpected token ')' in expression or statement. At line:1 char:27 + 'Use a quotation mark (`') <<<< to begin a string.' ``` - - ### HERE-STRINGS + The quotation rules for here-strings are slightly different. -A here-string is a single-quoted or double-quoted string in which quotation marks are interpreted literally. A here-string can span multiple lines. All the lines in a here-string are interpreted as strings even though they are not enclosed in quotation marks. +A here-string is a single-quoted or double-quoted string in which quotation +marks are interpreted literally. A here-string can span multiple lines. All +the lines in a here-string are interpreted as strings even though they are not +enclosed in quotation marks. -Like regular strings, variables are replaced by their values in double-quoted here-strings. In single-quoted here-strings, variables are not replaced by their values. +Like regular strings, variables are replaced by their values in double-quoted +here-strings. In single-quoted here-strings, variables are not replaced by +their values. -You can use here-strings for any text, but they are particularly useful for the following kinds of text: +You can use here-strings for any text, but they are particularly useful for +the following kinds of text: --- Text that contains literal quotation marks --- Multiple lines of text, such as the text in an HTML or XML --- The Help text for a script or function document +- Text that contains literal quotation marks +- Multiple lines of text, such as the text in an HTML or XML +- The Help text for a script or function document -A here-string can have either of the following formats, where represents the linefeed or newline hidden character that is added when you press the ENTER key. +A here-string can have either of the following formats, where \ +represents the linefeed or newline hidden character that is added when you +press the ENTER key. +Double-quotes: ``` -Double-quotes: - @" - [string] ... - "@ +@" + [string] ... +"@ ``` - - -``` Single-quotes: - @' - [string] ... - '@ +``` +@' + [string] ... +'@ ``` +In either format, the closing quotation mark must be the first character in +the line. -In either format, the closing quotation mark must be the first character in the line. - -A here-string contains all the text between the two hidden characters. In the here-string, all quotation marks are interpreted literally. For example: - +A here-string contains all the text between the two hidden characters. In the +here-string, all quotation marks are interpreted literally. For example: -``` +```powershell @" For help, type "get-help" "@ ``` - The output of this command is: - -``` +```output For help, type "get-help" ``` - Using a here-string can simplify using a string in a command. For example: - -``` +```powershell @" Use a quotation mark (') to begin a string. "@ ``` - The output of this command is: - -``` +```output Use a quotation mark (') to begin a string. ``` +In single-quoted here-strings, variables are interpreted literally and +reproduced exactly. For example: -In single-quoted here-strings, variables are interpreted literally and reproduced exactly. For example: - - -``` +```powershell @' The $profile variable contains the path of your Windows PowerShell profile. '@ ``` - The output of this command is: - -``` +```output The $profile variable contains the path of your Windows PowerShell profile. ``` +In double-quoted here-strings, variables are replaced by their values. For +example: -In double-quoted here-strings, variables are replaced by their values. For example: - - -``` +```powershell @" Even if you have not created a profile, the path of the profile file is: @@ -298,21 +280,19 @@ $profile. "@ ``` - The output of this command is: - -``` +```output Even if you have not created a profile, the path of the profile file is: -C:\Users\User01\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1. +C:\Users\User1\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1. ``` +Here-strings are typically used to assign multiple lines to a variable. For +example, the following here-string assigns a page of XML to the $page +variable. -Here-strings are typically used to assign multiple lines to a variable. For example, the following here-string assigns a page of XML to the $page variable. - - -``` +```powershell $page = [XML] @" "@ ``` - -Here-strings are also a convenient format for input to the ConvertFrom-StringData cmdlet, which converts here-strings to hash tables. For more information, see ConvertFrom-StringData. - - -## KEYWORDS -about_Here-Strings - -about_Quotes - -about_Quotation_Marks - +Here-strings are also a convenient format for input to the +ConvertFrom-StringData cmdlet, which converts here-strings to hash tables. For +more information, see ConvertFrom-StringData. ## SEE ALSO [about_Special_Characters](about_Special_Characters.md) -ConvertFrom-StringData - +[ConvertFrom-StringData](../../Microsoft.PowerShell.Utility/ConvertFrom-StringData.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Remote.md b/reference/6/Microsoft.PowerShell.Core/About/about_Remote.md index ac5e0c6fa90a..36455b275f7e 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Remote.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Remote.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,73 +7,74 @@ title: about_Remote --- # About Remote -## about_Remote - -# SHORT DESCRIPTION +## SHORT DESCRIPTION Describes how to run remote commands in Windows PowerShell. -# LONG DESCRIPTION - -You can run remote commands on a single computer or on multiple -computers by using a temporary or persistent connection. You can also -start an interactive session with a single remote computer. +## LONG DESCRIPTION -This topic provides a series of examples to show you how to -run different types of remote command. After you try these basic -commands, read the Help topics that describe each cmdlet that is -used in these commands. The topics provide the details and explain -how you can modify the commands to meet your needs. +You can run remote commands on a single computer or on multiple computers by +using a temporary or persistent connection. You can also start an interactive +session with a single remote computer. -Note: To use Windows PowerShell remoting, the local and remote computers -must be configured for remoting. For more information, see -about_Remote_Requirements. +This topic provides a series of examples to show you how to run different +types of remote command. After you try these basic commands, read the Help +topics that describe each cmdlet that is used in these commands. The topics +provide the details and explain how you can modify the commands to meet your +needs. -# HOW TO START AN INTERACTIVE SESSION (ENTER-PSSESSION) +Note: To use Windows PowerShell remoting, the local and remote computers must +be configured for remoting. For more information, see +[about_Remote_Requirements](about_Remote_Requirements.md). +## HOW TO START AN INTERACTIVE SESSION (ENTER-PSSESSION) -The easiest way to run remote commands is to start an -interactive session with a remote computer. +The easiest way to run remote commands is to start an interactive session with +a remote computer. -When the session starts, the commands that you type run on the -remote computer, just as though you typed them directly -on the remote computer. You can connect to only one -computer in each interactive session. +When the session starts, the commands that you type run on the remote +computer, just as though you typed them directly on the remote computer. You +can connect to only one computer in each interactive session. -To start an interactive session, use the Enter-PSSession -cmdlet. The following command starts an interactive session -with the Server01 computer: +To start an interactive session, use the Enter-PSSession cmdlet. The following +command starts an interactive session with the Server01 computer: +```powershell Enter-PSSession Server01 +``` -The command prompt changes to indicate that you are connected -to the Server01 computer. +The command prompt changes to indicate that you are connected to the Server01 +computer. +``` Server01\PS> +``` Now, you can type commands on the Server01 computer. To end the interactive session, type: +```powershell Exit-PSSession +``` For more information, see Enter-PSSession. -# HOW TO USE CMDLETS THAT HAVE A COMPUTERNAME PARAMETER TO GET REMOTE DATA +## HOW TO USE CMDLETS THAT HAVE A COMPUTERNAME PARAMETER TO GET REMOTE DATA - -Several cmdlets have a ComputerName parameter that lets you -get objects from remote computers. +Several cmdlets have a ComputerName parameter that lets you get objects from +remote computers. Because these cmdlets do not use WS-Management-based Windows PowerShell remoting, you can use the ComputerName parameter of these cmdlets on any -computer that is running Windows PowerShell. The computers do not have to -be configured for Windows PowerShell remoting, and the computers do not -have to meet the system requirements for remoting. +computer that is running Windows PowerShell. The computers do not have to be +configured for Windows PowerShell remoting, and the computers do not have to +meet the system requirements for remoting. The following cmdlets have a ComputerName parameter: +``` Clear-EventLog Limit-EventLog Get-Counter New-EventLog Get-EventLog Remove-EventLog @@ -82,15 +83,18 @@ Get-Process Show-EventLog Get-Service Stop-Computer Get-WinEvent Test-Connection Get-WmiObject Write-EventLog +``` For example, the following command gets the services on the Server01 remote computer: +```powershell Get-Service -ComputerName Server01 +``` -Typically, cmdlets that support remoting without special configuration -have a **ComputerName** parameter and do not have a **Session** parameter. -To find these cmdlets in your session, type: +Typically, cmdlets that support remoting without special configuration have a +**ComputerName** parameter and do not have a **Session** parameter. To find +these cmdlets in your session, type: ```powershell Get-Command | Where-Object { @@ -99,131 +103,134 @@ Get-Command | Where-Object { } ``` -# HOW TO RUN A REMOTE COMMAND +## HOW TO RUN A REMOTE COMMAND +To run other commands on remote computers, use the Invoke-Command cmdlet. -To run other commands on remote computers, use the -Invoke-Command cmdlet. +To run a single command or a few unrelated commands, use the ComputerName +parameter of Invoke-Command to specify the remote computers. Use the +ScriptBlock parameter to specify the command. -To run a single command or a few unrelated commands, use the -ComputerName parameter of Invoke-Command to specify the remote -computers. Use the ScriptBlock parameter to specify the command. - -For example, the following command runs a Get-Culture command -on the Server01 computer. +For example, the following command runs a Get-Culture command on the Server01 +computer. +```powershell Invoke-Command -ComputerName Server01 -ScriptBlock {Get-Culture} +``` -The ComputerName parameter is designed for situation in which you run -a single command or several unrelated commands on one or many computers. -To establish a persistent connection to a remote computer, use -the Session parameter. - -# HOW TO CREATE A PERSISTENT CONNECTION (PSSESSION) +The ComputerName parameter is designed for situation in which you run a single +command or several unrelated commands on one or many computers. To establish a +persistent connection to a remote computer, use the Session parameter. +## HOW TO CREATE A PERSISTENT CONNECTION (PSSESSION) -When you use the ComputerName parameter of the Invoke-Command -cmdlet, Windows PowerShell establishes a connection just for the -command. Then, it closes the connection when the command is complete. Any -variables or functions that are defined in the command are lost. +When you use the ComputerName parameter of the Invoke-Command cmdlet, Windows +PowerShell establishes a connection just for the command. Then, it closes the +connection when the command is complete. Any variables or functions that are +defined in the command are lost. -To create a persistent connection to a remote computer, use the -New-PSSession cmdlet. For example, the following command creates -PSSessions on the Server01 and Server02 computers and then saves the -PSSessions in the $s variable. +To create a persistent connection to a remote computer, use the New-PSSession +cmdlet. For example, the following command creates PSSessions on the Server01 +and Server02 computers and then saves the PSSessions in the $s variable. +```powershell $s = New-PSSession -ComputerName Server01, Server02 +``` -# HOW TO RUN COMMANDS IN A PSSESSION - +## HOW TO RUN COMMANDS IN A PSSESSION -With a PSSession, you can run a series of remote commands that -share data, like functions, aliases, and the values of variables. -To run commands in a PSSession, use the Session parameter of the -Invoke-Command cmdlet. +With a PSSession, you can run a series of remote commands that share data, +like functions, aliases, and the values of variables. To run commands in a +PSSession, use the Session parameter of the Invoke-Command cmdlet. -For example, the following command uses the Invoke-Command cmdlet -to run a Get-Process command in the PSSessions on the Server01 -and Server02 computers. The command saves the processes in a $p -variable in each PSSession. +For example, the following command uses the Invoke-Command cmdlet to run a +Get-Process command in the PSSessions on the Server01 and Server02 computers. +The command saves the processes in a $p variable in each PSSession. +```powershell Invoke-Command -Session $s -ScriptBlock {$p = Get-Process} +``` -Because the PSSession uses a persistent connection, you can run -another command in the same PSSession that uses the $p variable. -The following command counts the number of processes saved in $p. +Because the PSSession uses a persistent connection, you can run another +command in the same PSSession that uses the $p variable. The following command +counts the number of processes saved in $p. +```powershell Invoke-Command -Session $s -ScriptBlock {$p.count} +``` -# HOW TO RUN A REMOTE COMMAND ON MULTIPLE COMPUTERS - +## HOW TO RUN A REMOTE COMMAND ON MULTIPLE COMPUTERS -To run a remote command on multiple computers, type all of -the computer names in the value of the ComputerName parameter of -Invoke-Command. Separate the names with commas. +To run a remote command on multiple computers, type all of the computer names +in the value of the ComputerName parameter of Invoke-Command. Separate the +names with commas. -For example, the following command runs a Get-Culture command -on three computers: +For example, the following command runs a Get-Culture command on three +computers: +```powershell Invoke-Command -ComputerName S1, S2, S3 -ScriptBlock {Get-Culture} +``` -You can also run a command in multiple PSSessions. The following -commands create PSSessions on the Server01, Server02, and Server03 -computers and then run a Get-Culture command in each of the PSSessions. +You can also run a command in multiple PSSessions. The following commands +create PSSessions on the Server01, Server02, and Server03 computers and then +run a Get-Culture command in each of the PSSessions. +```powershell $s = New-PSSession -ComputerName S1, S2, S3 Invoke-Command -Session $s -ScriptBlock {Get-Culture} +``` To include the local computer list of computers, type the name of the local computer, type a dot (.), or type "localhost". +```powershell Invoke-Command -ComputerName S1, S2, S3, localhost -ScriptBlock {Get-Culture} +``` -# HOW TO RUN A SCRIPT ON REMOTE COMPUTERS - +## HOW TO RUN A SCRIPT ON REMOTE COMPUTERS -To run a local script on remote computers, use the -FilePath parameter of Invoke-Command. +To run a local script on remote computers, use the FilePath parameter of +Invoke-Command. -For example, the following command runs the Sample.ps1 script -on the S1 and S2 computers: +For example, the following command runs the Sample.ps1 script on the S1 and S2 +computers: +```powershell Invoke-Command -ComputerName S1, S2 -FilePath C:\Test\Sample.ps1 +``` -The results of the script are returned to the local computer. You -do not need to copy any files. - -# HOW TO STOP A REMOTE COMMAND - +The results of the script are returned to the local computer. You do not need +to copy any files. -To interrupt a command, press CTRL+C. The interrupt request is -passed to the remote computer where it terminates the remote command. +## HOW TO STOP A REMOTE COMMAND -# FOR MORE INFORMATION +To interrupt a command, press CTRL+C. The interrupt request is passed to the +remote computer where it terminates the remote command. +## FOR MORE INFORMATION --- For information about the system requirements for remoting, -see about_Remote_Requirements. +- For information about the system requirements for remoting, see + [about_Remote_Requirements](about_Remote_Requirements.md). --- For help in formatting remote output, see about_Remote_Output. +- For help in formatting remote output, see [about_Remote_Output](about_Remote_Output.md). --- For information about how remoting works, how to manage remote -data, special configurations, security issues, and other frequently -asked questions, see about_Remote_FAQ. +- For information about how remoting works, how to manage remote data, special + configurations, security issues, and other frequently asked questions, see + [about_Remote_FAQ](about_Remote_FAQ.md). --- For help in resolving remoting errors, see about_Remote_Troubleshooting. +- For help in resolving remoting errors, see about_Remote_Troubleshooting. --- For information about PSSessions and persistent connections, see -about_PSSessions. +- For information about PSSessions and persistent connections, see + [about_PSSessions](about_PSSessions.md). --- For information about Windows PowerShell background jobs, see -about_Jobs. +- For information about Windows PowerShell background jobs, see [about_Jobs](about_Jobs.md). -# KEYWORDS +## KEYWORDS about_Remoting -# SEE ALSO +## SEE ALSO [about_PSSessions](about_PSSessions.md) @@ -237,9 +244,8 @@ about_Remoting [about_Remote_Variables](about_Remote_Variables.md) -Enter-PSSession - -Invoke-Command +[Enter-PSSession](../Enter-PSSession.md) -New-PSSession +[Invoke-Command](../Invoke-Command.md) +[New-PSSession](../New-PSSession.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Remote_Requirements.md b/reference/6/Microsoft.PowerShell.Core/About/about_Remote_Requirements.md index eda447268fcd..445c1fa6f6b9 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Remote_Requirements.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Remote_Requirements.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,77 +7,71 @@ title: about_Remote_Requirements --- # About Remote Requirements -## about_Remote_Requirements +## SHORT DESCRIPTION +Describes the system requirements and configuration requirements for running +remote commands in Windows PowerShell. -# SHORT DESCRIPTION +## LONG DESCRIPTION -Describes the system requirements and configuration requirements for -running remote commands in Windows PowerShell. - -# LONG DESCRIPTION - -This topic describes the system requirements, user requirements, and -resource requirements for establishing remote connections and running -remote commands in Windows PowerShell. It also provides instructions for -configuring remote operations. +This topic describes the system requirements, user requirements, and resource +requirements for establishing remote connections and running remote commands +in Windows PowerShell. It also provides instructions for configuring remote +operations. Note: Many cmdlets (including the Get-Service, Get-Process, Get-WMIObject, -Get-EventLog, and Get-WinEvent cmdlets) get objects from remote -computers by using Microsoft .NET Framework methods to retrieve the -objects. They do not use the Windows PowerShell remoting -infrastructure. The requirements in this document do not apply to -these cmdlets. +Get-EventLog, and Get-WinEvent cmdlets) get objects from remote computers by +using Microsoft .NET Framework methods to retrieve the objects. They do not +use the Windows PowerShell remoting infrastructure. The requirements in this +document do not apply to these cmdlets. -To find the cmdlets that have a ComputerName parameter but do not use -Windows PowerShell remoting, read the description of the ComputerName -parameter of the cmdlets. - -# SYSTEM REQUIREMENTS +To find the cmdlets that have a ComputerName parameter but do not use Windows +PowerShell remoting, read the description of the ComputerName parameter of the +cmdlets. +## SYSTEM REQUIREMENTS To run remote sessions on Windows PowerShell 3.0, the local and remote computers must have the following: --- Windows PowerShell 3.0 or later --- The Microsoft .NET Framework 4 or later --- Windows Remote Management 3.0 +- Windows PowerShell 3.0 or later +- The Microsoft .NET Framework 4 or later +- Windows Remote Management 3.0 -To run remote sessions on Windows PowerShell 2.0, the local and remote computers -must have the following: +To run remote sessions on Windows PowerShell 2.0, the local and remote +computers must have the following: --- Windows PowerShell 2.0 or later --- The Microsoft .NET Framework 2.0 or later --- Windows Remote Management 2.0 +- Windows PowerShell 2.0 or later +- The Microsoft .NET Framework 2.0 or later +- Windows Remote Management 2.0 -You can create remote sessions between computers running Windows PowerShell 2.0 -and Windows PowerShell 3.0. However, features that run only on Windows -PowerShell 3.0, such as the ability to disconnect and reconnect to sessions, are -available only when both computers are running Windows PowerShell 3.0. +You can create remote sessions between computers running Windows PowerShell +2.0 and Windows PowerShell 3.0. However, features that run only on Windows +PowerShell 3.0, such as the ability to disconnect and reconnect to sessions, +are available only when both computers are running Windows PowerShell 3.0. To find the version number of an installed version of Windows PowerShell, use the $PSVersionTable automatic variable. -Windows Remote Management (WinRM) 3.0 and Microsoft .NET Framework 4 are included -in Windows 8, Windows Server 2012, and newer releases of the Windows operating -system. WinRM 3.0 is included in Windows Management Framework 3.0 for older -operating systems. If the computer does not have the required version of -WinRM or the Microsoft .NET Framework, the installation fails. - -# USER PERMISSIONS +Windows Remote Management (WinRM) 3.0 and Microsoft .NET Framework 4 are +included in Windows 8, Windows Server 2012, and newer releases of the Windows +operating system. WinRM 3.0 is included in Windows Management Framework 3.0 +for older operating systems. If the computer does not have the required +version of WinRM or the Microsoft .NET Framework, the installation fails. +## USER PERMISSIONS To create remote sessions and run remote commands, by default, the current user must be a member of the Administrators group on the remote computer or provide the credentials of an administrator. Otherwise, the command fails. The permissions required to create sessions and run commands on a remote -computer (or in a remote session on the local computer) are established by -the session configuration (also known as an "endpoint") on the remote -computer to which the session connects. Specifically, the security -descriptor on the session configuration determines who has access to the -session configuration and who can use it to connect. +computer (or in a remote session on the local computer) are established by the +session configuration (also known as an "endpoint") on the remote computer to +which the session connects. Specifically, the security descriptor on the +session configuration determines who has access to the session configuration +and who can use it to connect. The security descriptors on the default session configurations, Microsoft.PowerShell, Microsoft.PowerShell32, and @@ -85,48 +79,50 @@ Microsoft.PowerShell.Workflow, allow access only to members of the Administrators group. If the current user doesn't have permission to use the session configuration, -the command to run a command (which uses a temporary session) or create -a persistent session on the remote computer fails. The user can use the +the command to run a command (which uses a temporary session) or create a +persistent session on the remote computer fails. The user can use the ConfigurationName parameter of cmdlets that create sessions to select a different session configuration, if one is available. Members of the Administrators group on a computer can determine who has permission to connect to the computer remotely by changing the security -descriptors on the default session configurations and by creating new -session configurations with different security descriptors. +descriptors on the default session configurations and by creating new session +configurations with different security descriptors. For more informations about session configurations, see -about_Session_Configurations (http://go.microsoft.com/fwlink/?LinkID=145152). +[about_Session_Configurations](about_Session_Configurations.md). -# WINDOWS NETWORK LOCATIONS +## WINDOWS NETWORK LOCATIONS Beginning in Windows PowerShell 3.0, the Enable-PSRemoting cmdlet can enable remoting on client and server versions of Windows on private, domain, and public networks. On server versions of Windows with private and domain networks, the -Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted -remote access. It also creates a firewall rule for public networks that -allows remote access only from computers in the same local subnet. This -local subnet firewall rule is enabled by default on server versions of -Windows on public networks, but Enable-PSRemoting reapplies the rule in -case it was changed or deleted. - -On client versions of Windows with private and domain networks, by -default, the Enable-PSRemoting cmdlet creates firewall rules that -allow unrestricted remote access. - -To enable remoting on client versions of Windows with public networks, -use the SkipNetworkProfileCheck parameter of the Enable-PSRemoting cmdlet. -It creates a firewall rule that that allows remote access only from -computers in the same local subnet. +Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted remote +access. It also creates a firewall rule for public networks that allows remote +access only from computers in the same local subnet. This local subnet +firewall rule is enabled by default on server versions of Windows on public +networks, but Enable-PSRemoting reapplies the rule in case it was changed or +deleted. + +On client versions of Windows with private and domain networks, by default, +the Enable-PSRemoting cmdlet creates firewall rules that allow unrestricted +remote access. + +To enable remoting on client versions of Windows with public networks, use the +SkipNetworkProfileCheck parameter of the Enable-PSRemoting cmdlet. It creates +a firewall rule that that allows remote access only from computers in the same +local subnet. To remove the local subnet restriction on public networks and allow remote -access from all locations on client and server versions of Windows, use -the Set-NetFirewallRule cmdlet in the NetSecurity module. Run the following +access from all locations on client and server versions of Windows, use the +Set-NetFirewallRule cmdlet in the NetSecurity module. Run the following command: +```powershell Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any +``` In Windows PowerShell 2.0, on server versions of Windows, Enable-PSRemoting creates firewall rules that permit remote access on all networks. @@ -134,64 +130,55 @@ creates firewall rules that permit remote access on all networks. In Windows PowerShell 2.0, on client versions of Windows, Enable-PSRemoting creates firewall rules only on private and domain networks. If the network location is public, Enable-PSRemoting fails. -# . - -# RUN AS ADMINISTRATOR +## RUN AS ADMINISTRATOR +Administrator privileges are required for the following remoting operations: -Administrator privileges are required for the following remoting -operations: +- Establishing a remote connection to the local computer. This is commonly + known as a "loopback" scenario. --- Establishing a remote connection to the local computer. This is -commonly known as a "loopback" scenario. +- Managing session configurations on the local computer. --- Managing session configurations on the local computer. +- Viewing and changing WS-Management settings on the local computer. These are + the settings in the LocalHost node of the WSMAN: drive. --- Viewing and changing WS-Management settings on the local computer. -These are the settings in the LocalHost node of the WSMAN: drive. +To perform these tasks, you must start Windows PowerShell with the "Run as +administrator" option even if you are a member of the Administrators group on +the local computer. -To perform these tasks, you must start Windows PowerShell with the "Run -as administrator" option even if you are a member of the Administrators -group on the local computer. - -In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell -with the "Run as administrator" option: +In Windows 7 and in Windows Server 2008 R2, to start Windows PowerShell with +the "Run as administrator" option: 1. Click Start, click All Programs, click Accessories, and then click -the Windows PowerShell folder. - -2. Right-click Windows PowerShell, and then click -"Run as administrator". + the Windows PowerShell folder. +2. Right-click Windows PowerShell, and then click "Run as administrator". To start Windows PowerShell with the "Run as administrator" option: -1. Click Start, click All Programs, and then click the Windows -PowerShell folder. +1. Click Start, click All Programs, and then click the Windows PowerShell + folder. +2. Right-click Windows PowerShell, and then click "Run as administrator". -2. Right-click Windows PowerShell, and then click -"Run as administrator". - -The "Run as administrator" option is also available in other Windows -Explorer entries for Windows PowerShell, including shortcuts. Just -right-click the item, and then click "Run as administrator". +The "Run as administrator" option is also available in other Windows Explorer +entries for Windows PowerShell, including shortcuts. Just right-click the +item, and then click "Run as administrator". When you start Windows PowerShell from another program such as Cmd.exe, use the "Run as administrator" option to start the program. -# HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING - +## HOW TO CONFIGURE YOUR COMPUTER FOR REMOTING Computers running all supported versions of Windows can establish remote connections to and run remote commands in Windows PowerShell without any configuration. However, to receive connections, and allow users to create -local and remote user-managed Windows PowerShell sessions ("PSSessions") -and run commands on the local computer, you must enable Windows PowerShell +local and remote user-managed Windows PowerShell sessions ("PSSessions") and +run commands on the local computer, you must enable Windows PowerShell remoting on the computer. Windows Server 2012 and newer releases of Windows Server are enabled for -Windows PowerShell remoting by default. If the settings are changed, -you can restore the default settings by running the Enable-PSRemoting cmdlet. +Windows PowerShell remoting by default. If the settings are changed, you can +restore the default settings by running the Enable-PSRemoting cmdlet. On all other supported versions of Windows, you need to run the Enable-PSRemoting cmdlet to enable Windows PowerShell remoting. @@ -199,45 +186,43 @@ Enable-PSRemoting cmdlet to enable Windows PowerShell remoting. The remoting features of Windows PowerShell are supported by the WinRM service, which is the Microsoft implementation of the Web Services for Management (WS-Management) protocol. When you enable Windows PowerShell -remoting, you change the default configuration of WS-Management and add -system configuration that allow users to connect to WS-Management. +remoting, you change the default configuration of WS-Management and add system +configuration that allow users to connect to WS-Management. To configure Windows PowerShell to receive remote commands: -1. Start Windows PowerShell with the "Run as administrator" -option. - -2. At the command prompt, type: -Enable-PSRemoting +1. Start Windows PowerShell with the "Run as administrator" option. +2. At the command prompt, type: `Enable-PSRemoting` To verify that remoting is configured correctly, run a test command such as -the following command, which creates a remote session on the local -computer. +the following command, which creates a remote session on the local computer. +```powershell New-PSSession +``` -If remoting is configured correctly, the command will create a session on -the local computer and return an object that represents the session. The -output should resemble the following sample output: - -C:\PS> new-pssession +If remoting is configured correctly, the command will create a session on the +local computer and return an object that represents the session. The output +should resemble the following sample output: +```output Id Name ComputerName State ConfigurationName -- ---- ------------ ----- ----- 1 Session1 localhost Opened Microsoft.PowerShell +``` -If the command fails, for assistance, see about_Remote_Troubleshooting. +If the command fails, for assistance, see +[about_Remote_Troubleshooting](about_Remote_Troubleshooting.md). -# UNDERSTAND POLICIES +## UNDERSTAND POLICIES +When you work remotely, you use two instances of Windows PowerShell, one on +the local computer and one on the remote computer. As a result, your work is +affected by the Windows policies and the Windows PowerShell policies on the +local and remote computers. -When you work remotely, you use two instances of Windows PowerShell, one -on the local computer and one on the remote computer. As a result, your -work is affected by the Windows policies and the Windows PowerShell -policies on the local and remote computers. - -In general, before you connect and as you are establishing the connection, -the policies on the local computer are in effect. When you are using the +In general, before you connect and as you are establishing the connection, the +policies on the local computer are in effect. When you are using the connection, the policies on the remote computer are in effect. # SEE ALSO @@ -248,9 +233,8 @@ connection, the policies on the remote computer are in effect. [about_PSSessions](about_PSSessions.md) -Invoke-Command - -Enter-PSSession +[Invoke-Command](../Invoke-Command.md) -New-PSSession +[Enter-PSSession](../Enter-PSSession.md) +[New-PSSession](../New-PSSession.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Remote_Variables.md b/reference/6/Microsoft.PowerShell.Core/About/about_Remote_Variables.md index 33bf188649a7..cdd13115f8e0 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Remote_Variables.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Remote_Variables.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,108 +7,109 @@ title: about_Remote_Variables --- # About Remote Variables -## about_Remote_Variables +## SHORT DESCRIPTION -# SHORT DESCRIPTION +Explains how to use local and remote variables in remote commands. -Explains how to use local and remote variables in remote -commands. +## LONG DESCRIPTION -# LONG DESCRIPTION - -You can use variables in commands that you run on remote -computers. Simply assign a value to the variable and then -use the variable in place of the value. - -By default, the variables in remote commands are assumed -to be defined in the session in which the command runs. You -can also use variables that are defined in the local session, -but you must identify them as local -variables in the command. - -# USING REMOTE VARIABLES - - -Windows PowerShell assumes that the variables used in remote -commands are defined in the session in which the command runs. +You can use variables in commands that you run on remote computers. Simply +assign a value to the variable and then use the variable in place of the +value. -In the following example, the $ps variable is defined in the -temporary session in which the Get-WinEvent command runs. +By default, the variables in remote commands are assumed to be defined in the +session in which the command runs. You can also use variables that are defined +in the local session, but you must identify them as local variables in the +command. -PS C:> Invoke-Command -ComputerName S1 -ScriptBlock {$ps = "Windows PowerShell"; Get-WinEvent -LogName $ps} +## USING REMOTE VARIABLES -Similarly, when the command runs in a persistent session (PSSession), -the remote variable must be defined in the same PSSession. +Windows PowerShell assumes that the variables used in remote commands are +defined in the session in which the command runs. -PS C:> $s = New-PSSession -ComputerName S1 +In the following example, the \$ps variable is defined in the temporary session +in which the Get-WinEvent command runs. -PS C:> Invoke-Command -ComputerName S1 -ScriptBlock {$ps = "Windows PowerShell"} +```powershell +Invoke-Command -ComputerName S1 -ScriptBlock { + $ps = "Windows PowerShell"; Get-WinEvent -LogName $ps +} +``` -PS C:> Invoke-Command -Sessions $s -ScriptBlock {Get-WinEvent -LogName $ps} +Similarly, when the command runs in a persistent session (PSSession), the +remote variable must be defined in the same PSSession. -# USING LOCAL VARIABLES +```powershell +$s = New-PSSession -ComputerName S1 +Invoke-Command -ComputerName S1 -ScriptBlock {$ps = "Windows PowerShell"} +Invoke-Command -Sessions $s -ScriptBlock {Get-WinEvent -LogName $ps} +``` +## USING LOCAL VARIABLES -You can also use local variables in remote commands, but you must -indicate that the variable is defined in the local session. +You can also use local variables in remote commands, but you must indicate +that the variable is defined in the local session. -Beginning in Windows PowerShell 3.0, you can use the Using scope -modifier to identify a local variable in a remote command. +Beginning in Windows PowerShell 3.0, you can use the Using scope modifier to +identify a local variable in a remote command. The syntax of Using is as follows: -The syntax is: +``` $Using: +``` -In the following example, the $ps variable is created in the local -session, but is used in the session in which the command runs. The -Using scope modifier identifies $ps as a local variable. +In the following example, the $ps variable is created in the local session, +but is used in the session in which the command runs. The Using scope modifier +identifies $ps as a local variable. -PS C:> $ps = "Windows PowerShell" -PS C:> Invoke-Command -ComputerName S1 -ScriptBlock {Get-WinEvent -LogName $Using:ps} +```powershell +$ps = "Windows PowerShell" +Invoke-Command -ComputerName S1 -ScriptBlock { + Get-WinEvent -LogName $Using:ps +} +``` You can also use the Using scope modifier in PSSessions. -PS C:> $s = New-PSSession -ComputerName S1 - -PS C:> $ps = "Windows PowerShell" +```powershell +$s = New-PSSession -ComputerName S1 +$ps = "Windows PowerShell" +Invoke-Command -Sessions $s -ScriptBlock {Get-WinEvent -LogName $Using:ps} +``` -PS C:> Invoke-Command -Sessions $s -ScriptBlock {Get-WinEvent -LogName $Using:ps} +## USING LOCAL VARIABLES IN WINDOWS POWERSHELL 2.0 -# USING LOCAL VARIABLES IN WINDOWS POWERSHELL 2.0 +You can use local variables in a remote command by defining parameters for the +remote command and using the ArgumentList parameter of the Invoke-Command +cmdlet to specify the local variable as the parameter value. +This command format is valid on Windows PowerShell 2.0 and later versions of +Windows PowerShell. -You can use local variables in a remote command by defining parameters -for the remote command and using the ArgumentList parameter of the -Invoke-Command cmdlet to specify the local variable as the parameter -value. - -This command format is valid on Windows PowerShell 2.0 and later versions -of Windows PowerShell. +- Use the param keyword to define parameters for the remote command. The + parameter names are placeholders that do not need to match the name of the + local variable. --- Use the param keyword to define parameters for the remote command. -The parameter names are placeholders that do not need to match the -name of the local variable. +- Use the parameters defined by the param keyword in the command. --- Use the parameters defined by the param keyword in the command. - --- Use the ArgumentList parameter of the Invoke-Command cmdlet to -specify the local variable as the parameter value. +- Use the ArgumentList parameter of the Invoke-Command cmdlet to specify the + local variable as the parameter value. For example, the following commands define the $ps variable in the local -session and then use it in a remote command. The command uses $log as -the parameter name and the local variable, $ps, as its value. - -C:\PS>$ps = "Windows PowerShell" +session and then use it in a remote command. The command uses $log as the +parameter name and the local variable, $ps, as its value. -C:\PS>Invoke-Command -ComputerName S1 -ScriptBlock {param($log) Get-WinEvent -logname $log} -ArgumentList $ps +```powershell +$ps = "Windows PowerShell" +Invoke-Command -ComputerName S1 -ScriptBlock { + param($log) + Get-WinEvent -logname $log +} -ArgumentList $ps +``` -# KEYWORDS - -about_Using - -# SEE ALSO +## SEE ALSO [about_Remote](about_Remote.md) @@ -116,9 +117,8 @@ about_Using [about_Scopes](about_Scopes.md) -Enter-PSSession - -Invoke-Command +[Invoke-Command](../Invoke-Command.md) -New-PSSession +[Enter-PSSession](../Enter-PSSession.md) +[New-PSSession](../New-PSSession.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Requires.md b/reference/6/Microsoft.PowerShell.Core/About/about_Requires.md index 4ae85a982fc2..93f468542189 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Requires.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Requires.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-12-01 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -142,8 +142,3 @@ always a snap-in. [about_Automatic_Variables](about_Automatic_Variables.md) [about_Language_Keywords](about_Language_Keywords.md) - -[about_PSSnapins](about_PSSnapins.md) - -Get-PSSnapin - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Reserved_Words.md b/reference/6/Microsoft.PowerShell.Core/About/about_Reserved_Words.md index 874a7e5fd8a1..4c2f92e8b5fc 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Reserved_Words.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Reserved_Words.md @@ -70,8 +70,8 @@ Get-Help ## SEE ALSO - [about_Command_Syntax](about_Command_Syntax.md) -- [about_Special_Characters](about_Special_Characters.md) - [about_Language_Keywords](about_Language_Keywords.md) - [about_Parsing](about_Parsing.md) - [about_Quoting_Rules](about_Quoting_Rules.md) - [about_Script_Blocks](about_Script_Blocks.md) +- [about_Special_Characters](about_Special_Characters.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Return.md b/reference/6/Microsoft.PowerShell.Core/About/about_Return.md index ff684edeef37..bcb1e40e8d25 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Return.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Return.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,118 +7,115 @@ title: about_Return --- # About Return -## about_Return - ## SHORT DESCRIPTION -Exits the current scope, which can be a function, script, or script block. +Exits the current scope, which can be a function, script, or script block. ## LONG DESCRIPTION -The Return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached. -Users who are familiar with languages like C or C\# might want to use the Return keyword to make the logic of leaving a scope explicit. + The Return keyword exits a function, script, or script block. It can be used + to exit a scope at a specific point, to return a value, or to indicate that + the end of the scope has been reached. -In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C\# return only the value or values that are specified by the Return keyword. +Users who are familiar with languages like C or C\# might want to use the +Return keyword to make the logic of leaving a scope explicit. +In PowerShell, the results of each statement are returned as output, +even without a statement that contains the Return keyword. Languages like C or +C\# return only the value or values that are specified by the Return keyword. ### SYNTAX -The syntax for the Return keyword is as follows: +The syntax for the Return keyword is as follows: ``` return [] ``` - -The Return keyword can appear alone, or it can be followed by a value or expression, as follows: - +The Return keyword can appear alone, or it can be followed by a value or +expression, as follows: ``` -return -return $a +return +return $a return (2 + $a) ``` - ### EXAMPLES -The following example uses the Return keyword to exit a function at a specific point if a conditional is met: +The following example uses the Return keyword to exit a function at a specific +point if a conditional is met: ``` -function ScreenPassword($instance) -{ - if (!($instance.screensaversecure)) {return $instance.name} - -} - +function ScreenPassword($instance) +{ + if (!($instance.screensaversecure)) {return $instance.name} + +} + foreach ($a in @(get-wmiobject win32_desktop)) { ScreenPassword($a) } ``` +This script checks each user account. The ScreenPassword function returns the +name of any user account that does not have a password-protected screen saver. +If the screen saver is password protected, the function completes any other +statements to be run, and PowerShell does not return any value. -This script checks each user account. The ScreenPassword function returns the name of any user account that does not have a password-protected screen saver. If the screen saver is password protected, the function completes any other statements to be run, and Windows PowerShell does not return any value. - -In Windows PowerShell, values can be returned even if the Return keyword is not used. The results of each statement are returned. For example, the following statements return the value of the $a variable: - +In PowerShell, values can be returned even if the Return keyword is not used. +The results of each statement are returned. For example, the following +statements return the value of the \$a variable: ``` -$a +$a return ``` - The following statement also returns the value of $a: - ``` return $a ``` +The following example includes a statement intended to let the user know that +the function is performing a calculation: -The following example includes a statement intended to let the user know that the function is performing a calculation: +```powershell +function calculation { + param ($value) - -``` -function calculation { - param ($value) - - "Please wait. Working on calculation..." - $value += 73 - return $value - } + "Please wait. Working on calculation..." + $value += 73 + return $value +} ``` +Running this function and assigning the result to a variable has the following +effect: -Running this function and assigning the result to a variable has the following effect: - - -``` -C:\PS> $a = calculation 14 -C:\PS> +```powershell +$a = calculation 14 ``` +The "Please wait. Working on calculation..." string is not displayed. Instead, +it is assigned to the $a variable, as in the following example: -The "Please wait. Working on calculation..." string is not displayed. Instead, it is assigned to the $a variable, as in the following example: - - -``` -C:\PS> $a -Please wait. Working on calculation... +```output +C:\PS> $a +Please wait. Working on calculation... 87 ``` - -Both the informational string and the result of the calculation are returned by the function and assigned to the $a variable. - +Both the informational string and the result of the calculation are returned +by the function and assigned to the \$a variable. ## SEE ALSO -Exit keyword in [about_Language_Keywords](about_Language_Keywords.md) +[about_Language_Keywords](about_Language_Keywords.md) [about_Functions](about_Functions.md) [about_Scopes](about_Scopes.md) [about_Script_Blocks](about_Script_Blocks.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Run_With_PowerShell.md b/reference/6/Microsoft.PowerShell.Core/About/about_Run_With_PowerShell.md index 43445a359c43..2e47af3dba57 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Run_With_PowerShell.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Run_With_PowerShell.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,62 +7,56 @@ title: about_Run_With_PowerShell --- # About Run With PowerShell -## about_Run_With_PowerShell +## SHORT DESCRIPTION -# SHORT DESCRIPTION +Explains how to use the "Run with PowerShell" feature to run a script from a +file system drive. -Explains how to use the "Run with PowerShell" feature to run -a script from a file system drive. +## LONG DESCRIPTION -# LONG DESCRIPTION +Beginning in Windows PowerShell 3.0, you can use the "Run with PowerShell" +feature to run scripts from File Explorer in Windows 8 and Windows Server 2012 +and from Windows Explorer in earlier versions of Windows. -Beginning in Windows PowerShell 3.0, you can use the "Run with -PowerShell" feature to run scripts from File Explorer in Windows 8 -and Windows Server 2012 and from Windows Explorer in earlier -versions of Windows. +The "Run with PowerShell" feature is designed to run scripts that do not have +required parameters and do not return output to the command prompt. -The "Run with PowerShell" feature is designed to run scripts -that do not have required parameters and do not return output -to the command prompt. - -When you use the "Run with PowerShell" feature, the Windows -PowerShell console window appears only briefly, if at all. -You cannot interact with it. +When you use the "Run with PowerShell" feature, the Windows PowerShell console +window appears only briefly, if at all. You cannot interact with it. To use the "Run with PowerShell" feature: -In File Explorer (or Windows Explorer), right-click the -script file name and then select "Run with PowerShell". +In File Explorer (or Windows Explorer), right-click the script file name and +then select "Run with PowerShell". -The "Run with PowerShell" feature starts a Windows PowerShell -session that has an execution policy of Bypass, runs the -script, and closes the session. +The "Run with PowerShell" feature starts a Windows PowerShell session that has +an execution policy of Bypass, runs the script, and closes the session. It runs a command that has the following format: + +``` PowerShell.exe -File -ExecutionPolicy Bypass +``` -"Run with PowerShell" sets the Bypass execution policy only -for the session (the current instance of the PowerShell process) -in which the script runs. This feature does not change the execution -policy for the computer or the user. +"Run with PowerShell" sets the Bypass execution policy only for the session +(the current instance of the PowerShell process) in which the script runs. +This feature does not change the execution policy for the computer or the +user. -The "Run with PowerShell" feature is affected only by the AllSigned -execution policy. If the AllSigned execution policy is effective for -the computer or the user, "Run with PowerShell" runs only signed -scripts. "Run with PowerShell" is not affected by any other execution -policy. For more information, see about_Execution_Policies. +The "Run with PowerShell" feature is affected only by the AllSigned execution +policy. If the AllSigned execution policy is effective for the computer or the +user, "Run with PowerShell" runs only signed scripts. "Run with PowerShell" is +not affected by any other execution policy. For more information, see +[about_Execution_Policies](about_Execution_Policies.md). -Troubleshooting Note: Run with PowerShell command might prompt you -to confirm the execution policy change. +Troubleshooting Note: Run with PowerShell command might prompt you to confirm +the execution policy change. -# SEE ALSO +## SEE ALSO [about_Execution_Policies](about_Execution_Policies.md) [about_Group_Policy_Settings](about_Group_Policy_Settings.md) [about_Scripts](about_Scripts.md) - -"Running Scripts" (http://go.microsoft.com/fwlink/?LinkId=257680) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Scopes.md b/reference/6/Microsoft.PowerShell.Core/About/about_Scopes.md index f4cc17c0121f..92f18f04064d 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Scopes.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Scopes.md @@ -1,124 +1,114 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-08 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet -title: about_Scopes +title: about_scopes --- # About Scopes -## about_Scopes - about_Scopes -# SHORT DESCRIPTION +## SHORT DESCRIPTION -Explains the concept of scope in Windows PowerShell and shows how to set -and change the scope of elements. +Explains the concept of scope in PowerShell and shows how to set and change +the scope of elements. -# LONG DESCRIPTION +## LONG DESCRIPTION -Windows PowerShell protects access to variables, aliases, functions, and -Windows PowerShell drives (PSDrives) by limiting where they can be read and -changed. By enforcing a few simple rules for scope, Windows PowerShell -helps to ensure that you do not inadvertently change an item that should -not be changed. +PowerShell protects access to variables, aliases, functions, and PowerShell +drives (PSDrives) by limiting where they can be read and changed. By enforcing +a few simple rules for scope, PowerShell helps to ensure that you do not +inadvertently change an item that should not be changed. The following are the basic rules of scope: -- An item you include in a scope is visible in the scope in which it -was created and in any child scope, unless you explicitly make it -private. You can place variables, aliases, functions, or Windows -PowerShell drives in one or more scopes. - -- An item that you created within a scope can be changed only in the -scope in which it was created, unless you explicitly specify a -different scope. - -If you create an item in a scope, and the item shares its name with an -item in a different scope, the original item might be hidden under the -new item. But, it is not overridden or changed. - -Windows PowerShell Scopes - -Scopes in Windows PowerShell have both names and numbers. The named -scopes specify an absolute scope. The numbers are relative and reflect -the relationship between scopes. - -Global: -The scope that is in effect when Windows PowerShell -starts. Variables and functions that are present when -Windows PowerShell starts have been created in the -global scope. This includes automatic variables and -preference variables. This also includes the variables, aliases, -and functions that are in your Windows PowerShell -profiles. - -Local: -The current scope. The local scope can be the global -scope or any other scope. - -Script: -The scope that is created while a script file runs. Only -the commands in the script run in the script scope. To -the commands in a script, the script scope is the local -scope. +- An item you include in a scope is visible in the scope in which it was +created and in any child scope, unless you explicitly make it private. You can +place variables, aliases, functions, or PowerShell drives in one or +more scopes. + +- An item that you created within a scope can be changed only in the scope in +which it was created, unless you explicitly specify a different scope. -Private: -Items in private scope cannot be seen outside of the current -scope. You can use private scope to create a private version -of an item with the same name in another scope. - -Numbered Scopes: -You can refer to scopes by name or by a number that -describes the relative position of one scope to another. -Scope 0 represents the current, or local, scope. Scope 1 -indicates the immediate parent scope. Scope 2 indicates the -parent of the parent scope, and so on. Numbered scopes -are useful if you have created many recursive +If you create an item in a scope, and the item shares its name with an item in +a different scope, the original item might be hidden under the new item. But, +it is not overridden or changed. + +## PowerShell Scopes + +Scopes in PowerShell have both names and numbers. The named scopes specify an +absolute scope. The numbers are relative and reflect the relationship between scopes. -Parent and Child Scopes +- Global: The scope that is in effect when PowerShell starts. Variables and +functions that are present when PowerShell starts have been created in the +global scope. This includes automatic variables and preference variables. This +also includes the variables, aliases, and functions that are in your +PowerShell profiles. + +- Local: The current scope. The local scope can be the global scope or any +other scope. -You can create a new scope by running a script or function, by creating -a session, or by starting a new instance of Windows PowerShell. When you -create a new scope, the result is a parent scope (the original scope) and -a child scope (the scope that you created). +- Script: The scope that is created while a script file runs. Only the +commands in the script run in the script scope. To the commands in a script, +the script scope is the local scope. -In Windows PowerShell, all scopes are child scopes of the global scope, -but you can create many scopes and many recursive scopes. +- Private: Items in private scope cannot be seen outside of the current scope. +You can use private scope to create a private version of an item with the same +name in another scope. + +- Numbered Scopes: You can refer to scopes by name or by a number that describes +the relative position of one scope to another. Scope 0 represents the current, +or local, scope. Scope 1 indicates the immediate parent scope. Scope 2 +indicates the parent of the parent scope, and so on. Numbered scopes are +useful if you have created many recursive scopes. + +## Parent and Child Scopes + +You can create a new scope by running a script or function, by creating a +session, or by starting a new instance of PowerShell. When you create a new +scope, the result is a parent scope (the original scope) and a child scope +(the scope that you created). + +In PowerShell, all scopes are child scopes of the global scope, but you can +create many scopes and many recursive scopes. Unless you explicitly make the items private, the items in the parent scope -are available to the child scope. However, items that you create and change -in the child scope do not affect the parent scope, unless you explicitly -specify the scope when you create the items. +are available to the child scope. However, items that you create and change in +the child scope do not affect the parent scope, unless you explicitly specify +the scope when you create the items. -Inheritance +## Inheritance -A child scope does not inherit the variables, aliases, and functions from -the parent scope. Unless an item is private, the child scope can view the -items in the parent scope. And, it can change the items by explicitly -specifying the parent scope, but the items are not part of the child scope. +A child scope does not inherit the variables, aliases, and functions from the +parent scope. Unless an item is private, the child scope can view the items in +the parent scope. And, it can change the items by explicitly specifying the +parent scope, but the items are not part of the child scope. -However, a child scope is created with a set of items. Typically, it -includes all the aliases that have the AllScope option. This option is -discussed later in this topic. It includes all the variables that have the -AllScope option, plus some variables that can be used to customize the -scope, such as MaximumFunctionCount. +However, a child scope is created with a set of items. Typically, it includes +all the aliases that have the AllScope option. This option is discussed later +in this topic. It includes all the variables that have the AllScope option, +plus some variables that can be used to customize the scope, such as +MaximumFunctionCount. To find the items in a particular scope, use the Scope parameter of Get-Variable or Get-Alias. For example, to get all the variables in the local scope, type: +```powershell get-variable -scope local +``` To get all the variables in the global scope, type: +```powershell get-variable -scope global +``` -Scope Modifiers +## Scope Modifiers To specify the scope of a new variable, alias, or function, use a scope modifier. The valid values of a modifier are Global, Local, Private, and @@ -126,362 +116,411 @@ Script. The syntax for a scope modifier in a variable is: +``` $[]: = +``` The syntax for a scope modifier in a function is: +``` function []: {} +``` The default scope for scripts is the script scope. The default scope for functions and aliases is the local scope, even if they are defined in a script. -The following command, which does not use a scope modifier, creates a -variable in the current or local scope: +The following command, which does not use a scope modifier, creates a variable +in the current or local scope: +```powershell $a = "one" +``` To create the same variable in the global scope, use the Global scope modifier: +```powershell $global:a = "one" +``` -To create the same variable in the script scope, use the script -scope modifier: +To create the same variable in the script scope, use the script scope +modifier: +```powershell $script:a = "one" +``` You can also use a scope modifier in functions. The following function definition creates a function in the global scope: -function global:Hello -{ -write-host "Hello, World" +```powershell +function global:Hello { + write-host "Hello, World" } +``` -You can also use scope modifiers to refer to a variable in a different -scope. The following command refers to the $test variable, first in the -local scope and then in the global scope: +You can also use scope modifiers to refer to a variable in a different scope. +The following command refers to the $test variable, first in the local scope +and then in the global scope: +```powershell $test - $global:test +``` -The Using scope modifier +### The Using scope modifier -Using is a special scope modifier that identifies a local -variable in a remote command. By default, variables in remote -commands are assumed to be defined in the remote session. +Using is a special scope modifier that identifies a local variable in a remote +command. By default, variables in remote commands are assumed to be defined in +the remote session. -The Using scope modifier is introduced in Windows PowerShell 3.0. +The Using scope modifier is introduced in PowerShell 3.0. -For more information, see about_Remote_Variables. +For more information, see [about_Remote_Variables](about_Remote_Variables.md). -The AllScope Option +### The AllScope Option Variables and aliases have an Option property that can take a value of AllScope. Items that have the AllScope property become part of any child scopes that you create, although they are not retroactively inherited by parent scopes. -An item that has the AllScope property is visible in the child scope, and -it is part of that scope. Changes to the item in any scope affect all the -scopes in which the variable is defined. +An item that has the AllScope property is visible in the child scope, and it +is part of that scope. Changes to the item in any scope affect all the scopes +in which the variable is defined. -Managing Scope +### Managing Scope -Several cmdlets have a Scope parameter that lets you get or set (create -and change) items in a particular scope. Use the following command to find -all the cmdlets in your session that have a Scope parameter: +Several cmdlets have a Scope parameter that lets you get or set (create and +change) items in a particular scope. Use the following command to find all the +cmdlets in your session that have a Scope parameter: +```powershell get-help * -parameter scope +``` -To find the variables that are visible in a particular scope, use the -Scope parameter of Get-Variable. The visible parameters include global -parameters, parameters in the parent scope, and parameters in the current -scope. +To find the variables that are visible in a particular scope, use the Scope +parameter of Get-Variable. The visible parameters include global parameters, +parameters in the parent scope, and parameters in the current scope. -For example, the following command gets the variables that are visible in -the local scope: +For example, the following command gets the variables that are visible in the +local scope: +```powershell get-variable -scope local +``` -To create a variable in a particular scope, use a scope modifier or the -Scope parameter of Set-Variable. The following command creates a variable -in the global scope: +To create a variable in a particular scope, use a scope modifier or the Scope +parameter of Set-Variable. The following command creates a variable in the +global scope: +```powershell new-variable -scope global -name a -value "One" +``` -You can also use the Scope parameter of the New-Alias, Set-Alias, or -Get-Alias cmdlets to specify the scope. The following command creates an -alias in the global scope: +You can also use the Scope parameter of the New-Alias, Set-Alias, or Get-Alias +cmdlets to specify the scope. The following command creates an alias in the +global scope: +```powershell new-alias -scope global -name np -value Notepad.exe +``` -To get the functions in a particular scope, use the Get-Item cmdlet when -you are in the scope. The Get-Item cmdlet does not have a scope parameter. +To get the functions in a particular scope, use the Get-Item cmdlet when you +are in the scope. The Get-Item cmdlet does not have a scope parameter. -Using Dot Source Notation with Scope +### Using Dot Source Notation with Scope Scripts and functions follow all the rules of scope. You create them in a particular scope, and they affect only that scope unless you use a cmdlet parameter or a scope modifier to change that scope. -But, you can add a script or function to the current scope by using dot -source notation. Then, when a script runs in the current scope, any -functions, aliases, and variables that the script creates are available -in the current scope. +But, you can add a script or function to the current scope by using dot source +notation. Then, when a script runs in the current scope, any functions, +aliases, and variables that the script creates are available in the current +scope. -To add a function to the current scope, type a dot (.) and a space before -the path and name of the function in the function call. +To add a function to the current scope, type a dot (.) and a space before the +path and name of the function in the function call. -For example, to run the Sample.ps1 script from the C:\Scripts directory in -the script scope (the default for scripts), use the following command: +For example, to run the Sample.ps1 script from the C:\Scripts directory in the +script scope (the default for scripts), use the following command: +```powershell c:\scripts\sample.ps1 +``` To run the Sample.ps1 script in the local scope, use the following command: +```powershell . c:\scripts.sample.ps1 +``` When you use the call operator (&) to run a function or script, it is not added to the current scope. The following example uses the call operator: +```powershell & c:\scripts.sample.ps1 +``` + +Any aliases, functions, or variables that the Sample.ps1 script creates are +not available in the current scope. + +### Restricting Without Scope + +A few PowerShell concepts are similar to scope or interact with scope. These +concepts may be confused with scope or the behavior of scope. + +Sessions, modules, and nested prompts are self-contained environments, but +they are not child scopes of the global scope in the session. + +- Sessions: A session is an environment in which PowerShell runs. When you + create a session on a remote computer, PowerShell establishes a + persistent connection to the remote computer. The persistent connection lets + you use the session for multiple related commands. + + Because a session is a contained environment, it has its own scope, but a + session is not a child scope of the session in which is was created. The + session starts with its own global scope. This scope is independent of the + global scope of the session. You can create child scopes in the session. For + example, you can run a script to create a child scope in a session. + +- Modules: You can use a PowerShell module to share and deliver PowerShell + tools. A module is a unit that can contain cmdlets, scripts, functions, + variables, aliases, and other useful items. Unless explicitly defined, the + items in a module are not accessible outside the module. Therefore, you can + add the module to your session and use the public items without worrying that + the other items might override the cmdlets, scripts, functions, and other + items in your session. -Any aliases, functions, or variables that the Sample.ps1 script creates -are not available in the current scope. - -Restricting Without Scope - -A few Windows PowerShell concepts are similar to scope or interact with -scope. These concepts may be confused with scope or the behavior of scope. - -Sessions, modules, and nested prompts are self-contained environments, -but they are not child scopes of the global scope in the session. - -Sessions: -A session is an environment in which Windows PowerShell runs. -When you create a session on a remote computer, Windows -PowerShell establishes a persistent connection to the remote -computer. The persistent connection lets you use the session for -multiple related commands. - -Because a session is a contained environment, it has its own -scope, but a session is not a child scope of the session in -which is was created. The session starts with its own global -scope. This scope is independent of the global scope of the session. -You can create child scopes in the session. For example, you can run -a script to create a child scope in a session. - -Modules: -You can use a Windows PowerShell module to share and deliver -Windows PowerShell tools. A module is a unit that can contain -cmdlets, scripts, functions, variables, aliases, and other useful -items. Unless explicitly defined, the items in a module are not -accessible outside the module. Therefore, you can add the module to -your session and use the public items without worrying that the -other items might override the cmdlets, scripts, functions, and other -items in your session. - -The privacy of a module behaves like a scope, but adding a module -to a session does not change the scope. And, the module does not have -its own scope, although the scripts in the module, like all Windows -PowerShell scripts, do have their own scope. - -Nested Prompts: -Similarly, nested prompts do not have their own scope. When you enter -a nested prompt, the nested prompt is a subset of the environment. -But, you remain within the local scope. - -Scripts do have their own scope. If you are debugging a script, and -you reach a breakpoint in the script, you enter the script scope. - -Private Option: -Aliases and variables have an Option property that can take a value -of Private. Items that have the Private option can be viewed and -changed in the scope in which they are created, but they cannot be -viewed or changed outside that scope. - -For example, if you create a variable that has a private option in the -global scope and then run a script, Get-Variable commands in the script -do not display the private variable. This occurs even if you use -the global scope modifier. - -You can use the Option parameter of the New-Variable, Set-Variable, -New-Alias, and Set-Alias cmdlets to set the value of the Option -property to Private. - -Visibility: -The Visibility property of a variable or alias determines whether you -can see the item outside the container, such as a module, in which it -was created. Visibility is designed for containers in the same way that -the Private value of the Option property is designed for scopes. - -The Visibility property takes the Public and Private values. Items -that have private visibility can be viewed and changed only in the -container in which they were created. If the container is added or -imported, the items that have private visibility cannot be viewed or -changed. - -Because Visibility is designed for containers, it works differently -in a scope. If you create an item that has private visibility in the -global scope, you cannot view or change the item in any scope. If you -try to view or change the value of a variable that has private -visibility, Windows PowerShell returns an error message. - -You can use the New-Variable and Set-Variable cmdlets to create a -variable that has private visibility. - -# EXAMPLES - - -Example 1: Change a Variable Value Only in a Script - -The following command changes the value of the $ConfirmPreference -variable in a script. The change does not affect the global scope. - -First, to display the value of the $ConfirmPreference variable in -the local scope, use the following command: + The privacy of a module behaves like a scope, but adding a module to a session + does not change the scope. And, the module does not have its own scope, + although the scripts in the module, like all PowerShell scripts, do + have their own scope. +- Nested Prompts: Similarly, nested prompts do not have their own scope. When + you enter a nested prompt, the nested prompt is a subset of the environment. + But, you remain within the local scope. + + Scripts do have their own scope. If you are debugging a script, and you reach + a breakpoint in the script, you enter the script scope. + +- Private Option: Aliases and variables have an Option property that can take a + value of Private. Items that have the Private option can be viewed and changed + in the scope in which they are created, but they cannot be viewed or changed + outside that scope. + + For example, if you create a variable that has a private option in the global + scope and then run a script, Get-Variable commands in the script do not + display the private variable. This occurs even if you use the global scope + modifier. + + You can use the Option parameter of the New-Variable, Set-Variable, New-Alias, + and Set-Alias cmdlets to set the value of the Option property to Private. + +- Visibility: The Visibility property of a variable or alias determines whether + you can see the item outside the container, such as a module, in which it was + created. Visibility is designed for containers in the same way that the + Private value of the Option property is designed for scopes. + + The Visibility property takes the Public and Private values. Items that have + private visibility can be viewed and changed only in the container in which + they were created. If the container is added or imported, the items that have + private visibility cannot be viewed or changed. + + Because Visibility is designed for containers, it works differently in a + scope. If you create an item that has private visibility in the global scope, + you cannot view or change the item in any scope. If you try to view or change + the value of a variable that has private visibility, PowerShell returns an + error message. + + You can use the New-Variable and Set-Variable cmdlets to create a variable + that has private visibility. + +## EXAMPLES + +### Example 1: Change a Variable Value Only in a Script + +The following command changes the value of the \$ConfirmPreference variable in +a script. The change does not affect the global scope. + +First, to display the value of the \$ConfirmPreference variable in the local +scope, use the following command: + +``` C:\PS> $ConfirmPreference High +``` Create a Scope.ps1 script that contains the following commands: +```powershell $ConfirmPreference = "Low" "The value of `$ConfirmPreference is $ConfirmPreference." +``` -Run the script. The script changes the value of the $ConfirmPreference -variable and then reports its value in the script scope. The output -should resemble the following output: +Run the script. The script changes the value of the \$ConfirmPreference +variable and then reports its value in the script scope. The output should +resemble the following output: +```output The value of $ConfirmPreference is Low. +``` -Next, test the current value of the $ConfirmPreference variable in the -current scope. +Next, test the current value of the \$ConfirmPreference variable in the current +scope. +``` C:\PS> $ConfirmPreference High +``` -This example shows that changes to the value of a variable in the script -scope do not affect the value of that variable in the parent scope. +This example shows that changes to the value of a variable in the script scope +do not affect the value of that variable in the parent scope. -Example 2: View a Variable Value in Different Scopes +### Example 2: View a Variable Value in Different Scopes -You can use scope modifiers to view the value of a variable in the local -scope and in a parent scope. +You can use scope modifiers to view the value of a variable in the local scope +and in a parent scope. First, define a $test variable in the global scope. +```powershell $test = "Global" +``` -Next, create a Sample.ps1 script that defines the $test -variable. In the script, use a scope modifier to refer -to either the global or local versions of the $test variable. +Next, create a Sample.ps1 script that defines the \$test variable. In the +script, use a scope modifier to refer to either the global or local versions +of the \$test variable. -In Sample.ps1 +In Sample.ps1: +```powershell $test = "Local" "The local value of `$test is $test." "The global value of `$test is $global:test." +``` When you run Sample.ps1, the output should resemble the following output: +```output The local value of $test is Local. The global value of $test is Global. +``` -When the script is complete, only the global value of $test is defined -in the session. +When the script is complete, only the global value of \$test is defined in the +session. +``` C:\PS> $test Global +``` -Example 3: Change the Value of a Variable in a Parent Scope +### Example 3: Change the Value of a Variable in a Parent Scope -Unless you protect an item by using the Private option or another -method, you can view and change the value of a variable in a parent -scope. +Unless you protect an item by using the Private option or another method, you +can view and change the value of a variable in a parent scope. -First, define a $test variable in the global scope. +First, define a \$test variable in the global scope. +```powershell $test = "Global" +``` -Next, create a Sample.ps1 script that defines the $test variable. In the -script, use a scope modifier to refer to either the global or local -versions of the $test variable. +Next, create a Sample.ps1 script that defines the \$test variable. In the +script, use a scope modifier to refer to either the global or local versions +of the \$test variable. -In Sample.ps1 +In Sample.ps1: +```powershell $global:test = "Local" "The global value of `$test is $global:test." +``` -When the script is complete, the global value of $test is changed. +When the script is complete, the global value of \$test is changed. +``` C:\PS> $test Local +``` -Example 4: Creating a Private Variable +### Example 4: Creating a Private Variable -A private variable is a variable that has an Option property that has a -value of Private. Private variables are inherited by the child scope, but -they can be viewed or changed only in the scope in which they were -created. +A private variable is a variable that has an Option property that has a value +of Private. Private variables are inherited by the child scope, but they can +be viewed or changed only in the scope in which they were created. -The following command creates a private variable called $ptest in the -local scope. +The following command creates a private variable called \$ptest in the local +scope. +```powershell New-Variable -Name ptest -Value 1 -Option private +``` -You can display and change the value of $ptest in the local scope. +You can display and change the value of \$ptest in the local scope. +``` C:\PS> $ptest -# 1 +1 C:\PS> $ptest = 2 C:\PS> $ptest -# 2 - +2 +``` -Next, create a Sample.ps1 script that contains the following commands. -The command tries to display and change the value of $ptest. +Next, create a Sample.ps1 script that contains the following commands. The +command tries to display and change the value of \$ptest. -In Sample.ps1 +In Sample.ps1: +```powershell "The value of `$Ptest is $Ptest." "The value of `$Ptest is $global:Ptest." +``` -Because the $ptest variable is not visible in the script scope, the -output is empty. +Because the $ptest variable is not visible in the script scope, the output is +empty. +```powershell "The value of $Ptest is ." "The value of $Ptest is ." +``` -Example 5: Using a Local Variable in a Remote Command +### Example 5: Using a Local Variable in a Remote Command -To indicate that a variable in a remote command was created in the -local session, use the Using scope modifier. By default, Windows -PowerShell assumes that the variables in remote commands were created -in the remote session. +To indicate that a variable in a remote command was created in the local +session, use the Using scope modifier. By default, PowerShell assumes +that the variables in remote commands were created in the remote session. The syntax is: + +``` $Using: +``` -For example, the following commands create a $Cred variable in the -local session and then use the $Cred variable in a remote command: +For example, the following commands create a $Cred variable in the local +session and then use the $Cred variable in a remote command: +```powershell $Cred = Get-Credential Invoke-Command $s {Remove-Item .\Test*.ps1 -Credential $Using:Cred} +``` -The Using scope was introduced in Windows PowerShell 3.0. - -In Windows PowerShell 2.0, to indicate that a variable was created in -the local session, use the following command format. +The Using scope was introduced in PowerShell 3.0. In PowerShell 2.0, to +indicate that a variable was created in the local session, use the following +command format. +```powershell $Cred = Get-Credential -Invoke-Command $s {param($c) Remove-Item .\Test*.ps1 -Credential $c} -ArgumentList $Cred +Invoke-Command $s { + param($c) + Remove-Item .\Test*.ps1 -Credential $c +} -ArgumentList $Cred +``` -# SEE ALSO +## SEE ALSO [about_Variables](about_Variables.md) @@ -490,4 +529,3 @@ Invoke-Command $s {param($c) Remove-Item .\Test*.ps1 -Credential $c} -ArgumentLi [about_Functions](about_Functions.md) [about_Script_Blocks](about_Script_Blocks.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Script_Internationalization.md b/reference/6/Microsoft.PowerShell.Core/About/about_Script_Internationalization.md index f56bd3f816ae..06219eb3961e 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Script_Internationalization.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Script_Internationalization.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,190 +7,244 @@ title: about_Script_Internationalization --- # About Script Internationalization -## about_Script_Internationalization +## Short Description -# SHORT DESCRIPTION +Describes the script internationalization features that make it easy for +scripts to display messages and instructions to users in their user interface +(UI) language. -Describes the script internationalization features of Windows PowerShell 2.0 -that make it easy for scripts to display messages and instructions to users -in their user interface (UI) language. - -# LONG DESCRIPTION +## Long Description The Windows PowerShell script internationalization features allow you to -better serve users throughout the world by displaying Help and user -messages for scripts and functions in the user's UI language. - -The script internationalization features query the UI culture of the -operating system during execution, import the appropriate -translated text strings, and display them to the user. The Data section -lets you store text strings separate from code so they are easily -identified and extracted. A new cmdlet, ConvertFrom-StringData, -converts text strings into dictionary-like hash tables to facilitate -translation. +better serve users throughout the world by displaying Help and user messages +for scripts and functions in the user's UI language. -The Windows PowerShell 2.0 features used in script internationalization -are not supported by Windows PowerShell 1.0. Scripts that include these -features will not run in Windows PowerShell 1.0 without modification. +The script internationalization features query the UI culture of the operating +system during execution, import the appropriate translated text strings, and +display them to the user. The Data section lets you store text strings +separate from code so they are easily identified and extracted. A new cmdlet, +`ConvertFrom-StringData`, converts text strings into dictionary-like hash +tables to facilitate translation. -To support international Help text, Windows PowerShell 2.0 includes the -following features: +To support international Help text, Windows PowerShell includes the following +features: --- A Data section that separates text strings from code instructions. For -more information about the Data section, see about_Data_Sections. +* A Data section that separates text strings from code instructions. For more + information about the Data section, see + [aout_Data_Sections](about_Data_Sections.md). --- New automatic variables, $PSCulture and $PSUICulture. $PSCulture stores -the name of the UI language used on the system for elements such as -the date, time, and currency. The $PSUICulture variable stores the -name of the UI language used on the system for user interface elements -such as menus and text strings. +* New automatic variables, \$PSCulture and \$PSUICulture. \$PSCulture stores the + name of the UI language used on the system for elements such as the date, + time, and currency. The $PSUICulture variable stores the name of the UI + language used on the system for user interface elements such as menus and text + strings. --- A cmdlet, ConvertFrom-StringData, that converts text strings into -dictionary-like hash tables to facilitate translation. For more -information, see ConvertFrom-StringData. +* A cmdlet, `ConvertFrom-StringData`, that converts text strings into + dictionary-like hash tables to facilitate translation. For more information, + see [ConvertFrom-StringData](../../Microsoft.PowerShell.Utility/ConvertFrom-StringData.md). --- A new file type, .psd1, that stores translated text strings. The .psd1 -files are stored in language-specific subdirectories of the script -directory. +* A new file type, .psd1, that stores translated text strings. The .psd1 files + are stored in language-specific subdirectories of the script directory. --- A cmdlet, Import-LocalizedData, that imports translated text strings -for a specified language into a script at runtime. This cmdlet recognizes -and imports strings in any Windows-supported language. For more -information see Import-LocalizedData. +* A cmdlet, `Import-LocalizedData`, that imports translated text strings for a + specified language into a script at runtime. This cmdlet recognizes and + imports strings in any Windows-supported language. For more information see + [Import-LocalizedData](../../Microsoft.PowerShell.Utility/Import-LocalizedData.md). -THE DATA SECTION: Storing Default Strings +### The Data Section: Storing Default Strings -Use a Data section in the script to store the text strings in the default language. -Arrange the strings in key/value pairs in a here-string. Each key/value pair must -be on a separate line. If you include comments, the comments must be on separate -lines. +Use a Data section in the script to store the text strings in the default +language. Arrange the strings in key/value pairs in a here-string. Each +key/value pair must be on a separate line. If you include comments, the +comments must be on separate lines. -The ConvertFrom-StringData cmdlet converts the key/value pairs in the here-string -into a dictionary-like hash table that is stored in the value of the Data section -variable. +The `ConvertFrom-StringData` cmdlet converts the key/value pairs in the +here-string into a dictionary-like hash table that is stored in the value of +the Data section variable. In the following example, the Data section of the World.ps1 script includes the English-United States (en-US) set of prompt messages for a script. The -ConvertFrom-StringData cmdlet converts the strings into a hash table and stores -them in the $msgtable variable. +`ConvertFrom-StringData` cmdlet converts the strings into a hash table and +stores them in the $msgtable variable. +```powershell $msgTable = Data { -culture="en-US" -ConvertFrom-StringData @' -helloWorld = Hello, World. -errorMsg1 = You cannot leave the user name field blank. -promptMsg = Please enter your user name. -# '@ - + #culture="en-US" + ConvertFrom-StringData @' + helloWorld = Hello, World. + errorMsg1 = You cannot leave the user name field blank. + promptMsg = Please enter your user name. +'@ } +``` -For more information about here-strings, see about_Quoting_Rules. +For more information about here-strings, see +[about_Quoting_Rules](about_Quoting_Rules.md). -PSD1 FILES: Storing Translated Strings +### PSD1 Files: Storing Translated Strings -Save the script messages for each UI language in separate text files with -the same name as the script and the .psd1 file name extension. Store the files -in subdirectories of the script directory with names of cultures in the following +Save the script messages for each UI language in separate text files with the +same name as the script and the .psd1 file name extension. Store the files in +subdirectories of the script directory with names of cultures in the following format: -- +\-\ Examples: de-DE, ar-SA, and zh-Hans -For example, if the World.ps1 script is stored in the C:\Scripts directory, you -would create a file directory structure that resembles the following: +For example, if the World.ps1 script is stored in the C:\Scripts directory, +you would create a file directory structure that resembles the following: +``` C:\Scripts C:\Scripts\World.ps1 C:\Scripts\de-DE\World.psd1 C:\Scripts\ar-SA\World.psd1 C:\Scripts\zh-CN\World.psd1 -# ... +... +``` +The World.psd1 file in the de-DE subdirectory of the script directory might +include the following statement: -The World.psd1 file in the de-DE subdirectory of the script directory -might include the following statement: - -ConvertFrom-StringData @' +```powershell +ConvertFrom-StringData -StringData @' helloWorld = Hello, World (in German). errorMsg1 = You cannot leave the user name field blank (in German). promptMsg = Please enter your user name (in German). -# '@ +'@ +``` +Similarly, the World.psd1 file in the ar-SA subdirectory of the script +directory might includes the following statement: -Similarly, the World.psd1 file in the ar-SA subdirectory of the script directory -might includes the following statement: - -ConvertFrom-StringData @' +```powershell +ConvertFrom-StringData -StringData @' helloWorld = Hello, World (in Arabic). errorMsg1 = You cannot leave the user name field blank (in Arabic). promptMsg = Please enter your user name (in Arabic). -# '@ +'@ +``` +### Import-LocalizedData: Dynamic Retrieval of Translated Strings -IMPORT-LOCALIZEDDATA: Dynamic Retrieval of Translated Strings +To retrieve the strings in the UI language of the current user, use the +`Import-LocalizedData` cmdlet. -To retrieve the strings in the UI language of the current user, use -the Import-LocalizedData cmdlet. +`Import-LocalizedData` finds the value of the \$PSUICulture automatic variable +and imports the content of the \.psd1 files in the subdirectory +that matches the \$PSUICulture value. Then, it saves the imported content in +the variable specified by the value of the **BindingVariable** parameter. -Import-LocalizedData finds the value of the $PSUICulture automatic -variable and imports the content of the .psd1 files in -the subdirectory that matches the $PSUICulture value. Then, it saves -the imported content in the variable specified by the value of the -BindingVariable parameter. +```powershell +Import-LocalizedData -BindingVariable msgTable +``` -import-localizeddata -bindingVariable msgTable +For example, if the `Import-LocalizedData` command appears in the +C:\\Scripts\\World.ps1 script and the value of $PSUICulture is "ar-SA", +`Import-LocalizedData` finds the following file: -For example, if the Import-LocalizedData command appears in the -C:\Scripts\World.ps1 script and the value of $PSUICulture is -"ar-SA", Import-LocalizedData finds the following file: +C:\\Scripts\\ar-SA\\World.psd1 -C:\Scripts\ar-SA\World.psd1 - -Then, it imports the Arabic text strings from the file into -the $msgTable variable, replacing any default strings that might -be defined in the Data section of the World.ps1 script. +Then, it imports the Arabic text strings from the file into the $msgTable +variable, replacing any default strings that might be defined in the Data +section of the World.ps1 script. -As a result, when the script uses the $msgTable variable -to display user messages, the messages are displayed in -Arabic. +As a result, when the script uses the $msgTable variable to display user +messages, the messages are displayed in Arabic. -For example, the following script displays the "Please enter your user -name" message in Arabic: +For example, the following script displays the "Please enter your user name" +message in Arabic: +```powershell if (!($username)) { $msgTable.promptMsg } +``` -If Import-LocalizedData cannot find a .psd1 file that matches the -value of $PSUIculture, the value of $msgTable is not replaced, -and the call to $msgTable.promptMsg displays the fallback en-US -strings. +If `Import-LocalizedData` cannot find a .psd1 file that matches the value of +\$PSUIculture, the value of \$msgTable is not replaced, and the call to +\$msgTable.promptMsg displays the fallback en-US strings. -ExAMPLE +## Examples -This example shows how the script internationalization features -are used in a script to display a day of the week to users -in the language that is set on the computer. +This example shows how the script internationalization features are used in a +script to display a day of the week to users in the language that is set on +the computer. -The following is a complete listing of the Sample1.ps1 script -file. +The following is a complete listing of the Sample1.ps1 script file. -The script begins with a Data section named Day ($Day) that -contains a ConvertFrom-StringData command. The expression -submitted to ConvertFrom-StringData is a here-string that -contains the day names in the default UI culture, en-US, in -key/value pairs. The ConvertFrom-StringData cmdlet converts -the key/value pairs in the here-string into a hash table and +The script begins with a Data section named Day ($Day) that contains a +`ConvertFrom-StringData` command. The expression submitted to +`ConvertFrom-StringData` is a here-string that contains the day names in the +default UI culture, en-US, in key/value pairs. The `ConvertFrom-StringData` +cmdlet converts the key/value pairs in the here-string into a hash table and then saves it in the value of the $Day variable. -The Import-LocalizedData command imports the contents of the -.psd1 file in the directory that matches the value of the -$PSUICulture automatic variable and then saves it in the $Day -variable, replacing the values of $Day that are defined in the -Data section. +The `Import-LocalizedData` command imports the contents of the .psd1 file in +the directory that matches the value of the $PSUICulture automatic variable +and then saves it in the $Day variable, replacing the values of $Day that are +defined in the Data section. + +The remaining commands load the strings into an array and display them. + +```powershell +$Day = Data { +#culture="en-US" +ConvertFrom-StringData -StringData @' + messageDate = Today is + d0 = Sunday + d1 = Monday + d2 = Tuesday + d3 = Wednesday + d4 = Thursday + d5 = Friday + d6 = Saturday +'@ +} + +Import-LocalizedData -BindingVariable Day -The remaining commands load the strings into an array and display -them. +#Build an array of weekdays. +$a = $Day.d0, $Day.d1, $Day.d2, $Day.d3, $Day.d4, $Day.d5, $Day.d6 -$Day = DATA { +# Get the day of the week as a number (Monday = 1). +# Index into $a to get the name of the day. +# Use string formatting to build a sentence. +"{0} {1}" -f $Day.messageDate, $a[(Get-Date -uformat %u)] | Out-Host +``` + +The .psd1 files that support the script are saved in subdirectories of +the script directory with names that match the $PSUICulture values. + +The following is a complete listing of .\de-DE\sample1.psd1: + +```powershell +# culture="de-DE" +ConvertFrom-StringData @' + messageDate = Today is + d0 = Sunday (in German) + d1 = Monday (in German) + d2 = Tuesday (in German) + d3 = Wednesday (in German) + d4 = Thursday (in German) + d5 = Friday (in German) + d6 = Saturday (in German) +'@ +``` + +As a result, when you run Sample.ps1 on a system on which the value of +\$PSUICulture is de-DE, the output of the script is: + +```output +Today is Friday (in German) +``` + +## See also + +* [about_Data_Sections](about_Data_Sections.md) +* [about_Automatic_Variables](about_Automatic_Variables.md) +* [about_Hash_Tables](about_Hash_Tables.md) +* [about_Quoting_Rules](about_Quoting_Rules.md) +* [ConvertFrom-StringData](../../Microsoft.PowerShell.Utility/ConvertFrom-StringData.md) +* [Import-LocalizedData](../../Microsoft.PowerShell.Utility/Import-LocalizedData.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Session_Configuration_Files.md b/reference/6/Microsoft.PowerShell.Core/About/about_Session_Configuration_Files.md index fe470e6bc5b4..b3d7fc0d56e2 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Session_Configuration_Files.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Session_Configuration_Files.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,284 +7,296 @@ title: about_Session_Configuration_Files --- # About Session Configuration Files -## about_Session_Configuration_Files +## SHORT DESCRIPTION +Describes session configuration files, which are used in a session +configuration (also known as an "endpoint") to define the environment of +sessions that use the session configuration. -# SHORT DESCRIPTION +## LONG DESCRIPTION -Describes session configuration files, which are used in a -session configuration (also known as an "endpoint") to define the -environment of sessions that use the session configuration. - -# LONG DESCRIPTION - -A "session configuration file" is a text file with a .pssc file -name extension that contains a hash table of session configuration -properties and values. You can use a session configuration file to -set the properties of a session configuration. Doing so defines -the environment of any Windows PowerShell sessions that use that -session configuration. +A "session configuration file" is a text file with a .pssc file name extension +that contains a hash table of session configuration properties and values. You +can use a session configuration file to set the properties of a session +configuration. Doing so defines the environment of any Windows PowerShell +sessions that use that session configuration. Session configuration files make it easy to create custom session configurations without using complex C# assemblies or scripts. -A "session configuration" or "endpoint" is a collection of local -computer settings that determine such things as which users can -create sessions on the computer; which commands users can run in -those sessions; and whether the session should run as a privileged -virtual account. For more information about session configurations, -see about_Session_Configurations -(http://go.microsoft.com/fwlink/?LinkID=145152). - -Session configurations were introduced in Windows PowerShell 2.0, -and session configuration files were introduced in Windows -PowerShell 3.0. You must use Windows PowerShell 3.0 to include a -session configuration file in a session configuration. However, -users of Windows PowerShell 2.0 (and later) are affected by the -settings in the session configuration. - -Creating Custom Sessions -You can customize many features of a Windows PowerShell session -by specifying session properties in a session configuration. You -can customize a session by writing a C# program that defines a -custom runspace, or you can use a session configuration file to -define the properties of sessions created by using the session -configuration. As a general rule, it is easier to use the session +A "session configuration" or "endpoint" is a collection of local computer +settings that determine such things as which users can create sessions on the +computer; which commands users can run in those sessions; and whether the +session should run as a privileged virtual account. For more information about +session configurations, see [about_Session_Configurations](about_Session_Configurations.md). + +Session configurations were introduced in Windows PowerShell 2.0, and session +configuration files were introduced in Windows PowerShell 3.0. You must use +Windows PowerShell 3.0 to include a session configuration file in a session +configuration. However, users of Windows PowerShell 2.0 (and later) are +affected by the settings in the session configuration. + +## Creating Custom Sessions + +You can customize many features of a Windows PowerShell session by specifying +session properties in a session configuration. You can customize a session by +writing a C# program that defines a custom runspace, or you can use a session +configuration file to define the properties of sessions created by using the +session configuration. As a general rule, it is easier to use the session configuration file than to write a C# program. You can use a session configuration file to create items such as -fully-functioning sessions for highly trusted users; locked-down -sessions that allow minimal access; sessions designed for -particular and that contain only the modules required for those -tasks; and sessions where unprivileged users can only run -specific commands as a privileged account. - -In addition to that, you can manage whether users of the -session can use Windows PowerShell language elements such as -script blocks, or whether they can only run commands. You can -manage the version of Windows PowerShell users can run in the -session; manage which modules are imported into the session; and -manage which cmdlets, functions, and aliases session users can -run. When using the RoleDefinitions field, you can give users -different capabilities in the session based on group membership. - -For more information about RoleDefinitions and how to define this -Value, see the help topic for the New-PSRoleCapabilityFile -Cmdlet. - -Creating a Session Configuration File -The easiest way to create a session configuration file is by -using the New-PSSessionConfigurationFile cmdlet. This cmdlet -generates a file that uses the correct syntax and format, and -that automatically verifies many of the configuration file -property values. - -For detailed descriptions of the properties that you can set in -a session configuration file, see the help topic for the -New-PSSessionConfigurationFile cmdlet. - -The following command creates a session configuration file that -uses the default values. The resulting configuration file uses only -the default values because no parameters other than the Path -parameter (which specifies the file path) are included: - -PS C:> New-PSSessionConfigurationFile -Path .\Defaults.pssc - -To view the new configuration file in your default text editor, -use the following command: - -PS C:> Invoke-Item -Path .\Defaults.pssc - -To create a session configuration for sessions in which -user can run commands, but not use other elements of the Windows -PowerShell language, type: - -PS C:> New-PSSessionConfigurationFile -LanguageMode NoLanguage +fully-functioning sessions for highly trusted users; locked-down sessions that +allow minimal access; sessions designed for particular and that contain only +the modules required for those tasks; and sessions where unprivileged users +can only run specific commands as a privileged account. + +In addition to that, you can manage whether users of the session can use +Windows PowerShell language elements such as script blocks, or whether they +can only run commands. You can manage the version of Windows PowerShell users +can run in the session; manage which modules are imported into the session; +and manage which cmdlets, functions, and aliases session users can run. When +using the RoleDefinitions field, you can give users different capabilities in +the session based on group membership. + +For more information about RoleDefinitions and how to define this Value, see +the help topic for the New-PSRoleCapabilityFile Cmdlet. + +## Creating a Session Configuration File + +The easiest way to create a session configuration file is by using the +New-PSSessionConfigurationFile cmdlet. This cmdlet generates a file that uses +the correct syntax and format, and that automatically verifies many of the +configuration file property values. + +For detailed descriptions of the properties that you can set in a session +configuration file, see the help topic for the New-PSSessionConfigurationFile +cmdlet. + +The following command creates a session configuration file that uses the +default values. The resulting configuration file uses only the default values +because no parameters other than the Path parameter (which specifies the file +path) are included: + +```powershell +New-PSSessionConfigurationFile -Path .\Defaults.pssc +``` + +To view the new configuration file in your default text editor, use the +following command: + +```powershell +Invoke-Item -Path .\Defaults.pssc +``` + +To create a session configuration for sessions in which user can run commands, +but not use other elements of the Windows PowerShell language, type: + +```powershell +New-PSSessionConfigurationFile -LanguageMode NoLanguage -Path .\NoLanguage.pssc +``` -In the preceding command, setting the LanguageMode parameter to -NoLanguage prevents users from doing such things as writing or -running scripts, or using variables. +In the preceding command, setting the LanguageMode parameter to NoLanguage +prevents users from doing such things as writing or running scripts, or using +variables. -To create a session configuration for sessions in which users can -use only Get cmdlets, type: +To create a session configuration for sessions in which users can use only Get +cmdlets, type: -PS C:> New-PSSessionConfigurationFile -VisibleCmdlets Get-* +```powershell +New-PSSessionConfigurationFile -VisibleCmdlets Get-* -Path .\GetSessions.pssc +``` -In the preceding example, setting the VisibleCmdlets parameter to -Get-* limits users to cmdlets that have names that start with the -string value "Get-". +In the preceding example, setting the VisibleCmdlets parameter to Get-* limits +users to cmdlets that have names that start with the string value "Get-". -To create a session configuration for sessions that run under a -privileged virtual account instead of the user's credentials, type: +To create a session configuration for sessions that run under a privileged +virtual account instead of the user's credentials, type: -PS C:> New-PSSessionConfigurationFile -RunAsVirtualAccount +```powershell +New-PSSessionConfigurationFile -RunAsVirtualAccount -Path .\VirtualAccount.pssc +``` -To create a session configuration for sessions in which the -commands visible to the user are specified in a role capabilities -file, type: +To create a session configuration for sessions in which the commands visible +to the user are specified in a role capabilities file, type: -PS C:> New-PSSessionConfigurationFile -RoleDefinitions +```powershell +New-PSSessionConfigurationFile -RoleDefinitions @{ 'CONTOSO\User' = @{ RoleCapabilities = 'Maintenance' }} -Path .\Maintenance.pssc +``` -Using a Session Configuration File -You can include a session configuration file when you create a -session configuration or add you can add a file to the session -configuration at a later time. +### Using a Session Configuration File -To include a session configuration file when creating a session -configuration, use the Path parameter of the -Register-PSSessionConfiguration cmdlet. +You can include a session configuration file when you create a session +configuration or add you can add a file to the session configuration at a +later time. -For example, the following command uses the NoLanguage.pssc file -when it creates a NoLanguage session configuration. +To include a session configuration file when creating a session configuration, +use the Path parameter of the Register-PSSessionConfiguration cmdlet. -PS C:> Register-PSSessionConfiguration -Name NoLanguage +For example, the following command uses the NoLanguage.pssc file when it +creates a NoLanguage session configuration. + +```powershell +Register-PSSessionConfiguration -Name NoLanguage -Path .\NoLanguage.pssc +``` -When a new NoLanguage session starts, users will only have access -to Windows PowerShell commands. +When a new NoLanguage session starts, users will only have access to Windows +PowerShell commands. -To add a session configuration file to an existing session -configuration, use the Set-PSSessionConfiguration cmdlet and the -Path parameter. This affects any new sessions created with the -specified session configuration. Note that the -Set-PSSessionConfiguration cmdlet changes the session itself and -does not modify the session configuration file. +To add a session configuration file to an existing session configuration, use +the Set-PSSessionConfiguration cmdlet and the Path parameter. This affects any +new sessions created with the specified session configuration. Note that the +Set-PSSessionConfiguration cmdlet changes the session itself and does not +modify the session configuration file. -For example, the following command adds the NoLanguage.pssc file -to the LockedDown session configuration. +For example, the following command adds the NoLanguage.pssc file to the +LockedDown session configuration. -PS C:> Set-PSSessionConfiguration -Name LockedDown +```powershell +Set-PSSessionConfiguration -Name LockedDown -Path .\NoLanguage.pssc +``` -When users use the LockedDown session configuration to create a -session, they will be able to run cmdlets but they will not be -able to create or use variables, assign values, or use other -Windows PowerShell language elements. +When users use the LockedDown session configuration to create a session, they +will be able to run cmdlets but they will not be able to create or use +variables, assign values, or use other Windows PowerShell language elements. -The following command uses the New-PSSession cmdlet to create a -session on the computer Srv01 that uses the LockedDown session -configuration, saving an object reference to the session in the $s -variable. The ACL (access control list) of the session -configuration determines who can use it to create a session. +The following command uses the New-PSSession cmdlet to create a session on the +computer Srv01 that uses the LockedDown session configuration, saving an +object reference to the session in the $s variable. The ACL (access control +list) of the session configuration determines who can use it to create a +session. -PS C:> $s = New-PSSession -ComputerName Srv01 +```powershell +$s = New-PSSession -ComputerName Srv01 -ConfigurationName LockedDown - -Because the NoLanguage constraints were added to the LockedDown -session configuration, users in LockedDown sessions will only be -able to run Windows PowerShell commands and cmdlets. For example, -the following two commands use the Invoke-Command cmdlet to run -commands in the session referenced in the $s variable. The first -command, which runs the Get-UICulture cmdlet and does not use any -variables, succeeds. The second command, which gets the value of -the $PSUICulture variable, fails. - -PS C:> Invoke-Command -Session $s {Get-UICulture} +``` + +Because the NoLanguage constraints were added to the LockedDown session +configuration, users in LockedDown sessions will only be able to run Windows +PowerShell commands and cmdlets. For example, the following two commands use +the Invoke-Command cmdlet to run commands in the session referenced in the $s +variable. The first command, which runs the Get-UICulture cmdlet and does not +use any variables, succeeds. The second command, which gets the value of the +$PSUICulture variable, fails. + +``` +Invoke-Command -Session $s {Get-UICulture} en-US -PS C:> Invoke-Command -Session $s {$PSUICulture} +Invoke-Command -Session $s {$PSUICulture} The syntax is not supported by this runspace. This might be because it is in no-language mode. + CategoryInfo : ParserError: ($PSUICulture:String) [], ParseException + FullyQualifiedErrorId : ScriptsNotAllowed +``` + +## Editing a Session Configuration File -Editing a Session Configuration File -All settings in a session configuration except for -RunAsVirtualAccount and RunAsVirtualAccountGroups can be modified -by editing the session configuration file used by the session -configuration. To do this, begin by locating the active copy of the -session configuration file. +All settings in a session configuration except for RunAsVirtualAccount and +RunAsVirtualAccountGroups can be modified by editing the session configuration +file used by the session configuration. To do this, begin by locating the +active copy of the session configuration file. -When you use a session configuration file in a session -configuration, Windows PowerShell creates an active copy of the -session configuration file and stores it in the -$pshome\SessionConfig directory on the local computer. +When you use a session configuration file in a session configuration, Windows +PowerShell creates an active copy of the session configuration file and stores +it in the \$pshome\\SessionConfig directory on the local computer. -The location of the active copy of a session configuration file is -stored in the ConfigFilePath property of the session configuration -object. +The location of the active copy of a session configuration file is stored in +the ConfigFilePath property of the session configuration object. -The following command gets the location of the session -configuration file for the NoLanguage session configuration. +The following command gets the location of the session configuration file for +the NoLanguage session configuration. -PS C:> (Get-PSSessionConfiguration -Name NoLanguage).ConfigFilePath +```powershell +(Get-PSSessionConfiguration -Name NoLanguage).ConfigFilePath +``` That command returns a file path similar to the following: +``` C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\ NoLanguage_0c115179-ff2a-4f66-a5eb-e56e5692ba22.pssc +``` -You can edit the .pssc file in any text editor. After the file is -saved it will be employed by any new sessions that use the session -configuration. +You can edit the .pssc file in any text editor. After the file is saved it +will be employed by any new sessions that use the session configuration. -If you need to modify the RunAsVirtualAccount or the -RunAsVirtualAccountGroups settings, you must un-register the -session configuration and re-register a session configuration file -that includes the edited values. +If you need to modify the RunAsVirtualAccount or the RunAsVirtualAccountGroups +settings, you must un-register the session configuration and re-register a +session configuration file that includes the edited values. -Testing a Session Configuration File -Use the Test-PSSessionConfigurationFile cmdlet to test manually -edited session configuration files. That's important: if the file -syntax and values are not valid users will not be able to use the -session configuration to create a session. +## Testing a Session Configuration File -For example, the following command tests the active session -configuration file of the NoLanguage session configuration. +Use the Test-PSSessionConfigurationFile cmdlet to test manually edited session +configuration files. That's important: if the file syntax and values are not +valid users will not be able to use the session configuration to create a +session. -PS C:> Test-PSSessionConfigurationFile -Path C:\WINDOWS\System32\ +For example, the following command tests the active session configuration file +of the NoLanguage session configuration. + +```powershell +Test-PSSessionConfigurationFile -Path C:\WINDOWS\System32\ WindowsPowerShell\v1.0\SessionConfig\ NoLanguage_0c115179-ff2a-4f66-a5eb-e56e5692ba22.pssc +``` If the syntax and values in the configuration file are valid -Test-PSSessionConfigurationFile returns True. If the syntax and -values are not valid then the cmdlet returns False. - -You can use Test-PSSessionConfigurationFile to test any session -configuration file, including files that the -New-PSSessionConfiguration cmdlet creates. For more information, -see the help topic for the Test-PSSessionConfigurationFile cmdlet. - -Removing a Session Configuration File -You cannot remove a session configuration file from a session -configuration. However, you can replace the file with a new file -that uses the default settings. This effectively cancels the -settings used by the original configuration file. - -To replace a session configuration file, create a new session -configuration file that uses the default settings, then use the -Set-PSSessionConfiguration cmdlet to replace the custom session -configuration file with the new file. - -For example, the following commands create a Default session -configuration file and then replace the active session -configuration file in the NoLanguage session configuration. - -PS C:> New-PSSessionConfigurationFile -Path .\Default.pssc -PS C:> Set-PSSessionConfiguration -Name NoLanguage +Test-PSSessionConfigurationFile returns True. If the syntax and values are not +valid then the cmdlet returns False. + +You can use Test-PSSessionConfigurationFile to test any session configuration +file, including files that the New-PSSessionConfiguration cmdlet creates. For +more information, see the help topic for the Test-PSSessionConfigurationFile +cmdlet. + +## Removing a Session Configuration File + +You cannot remove a session configuration file from a session configuration. +However, you can replace the file with a new file that uses the default +settings. This effectively cancels the settings used by the original +configuration file. + +To replace a session configuration file, create a new session configuration +file that uses the default settings, then use the Set-PSSessionConfiguration +cmdlet to replace the custom session configuration file with the new file. + +For example, the following commands create a Default session configuration +file and then replace the active session configuration file in the NoLanguage +session configuration. + +```powershell +New-PSSessionConfigurationFile -Path .\Default.pssc +Set-PSSessionConfiguration -Name NoLanguage -Path .\Default.pssc +``` -When these commands finish, the NoLanguage session configuration -will actually provide full language support (the default setting) -for all sessions created with that session configuration. +When these commands finish, the NoLanguage session configuration will actually +provide full language support (the default setting) for all sessions created +with that session configuration. -Viewing the Properties of a Session Configuration -The session configuration objects that represent session -configurations using session configuration files have additional -properties that make it easy to discover and analyze the session -configuration. (Note that the type name shown below includes a -formatted view definition.) You can view the properties by running -the Get-PSSessionConfiguration cmdlet and piping the returned data -to the Get-Member cmdlet: +Viewing the Properties of a Session Configuration The session configuration +objects that represent session configurations using session configuration +files have additional properties that make it easy to discover and analyze the +session configuration. (Note that the type name shown below includes a +formatted view definition.) You can view the properties by running the +Get-PSSessionConfiguration cmdlet and piping the returned data to the +Get-Member cmdlet: -PS C:> Get-PSSessionConfiguration NoLanguage | Get-Member +```powershell +Get-PSSessionConfiguration NoLanguage | Get-Member +``` + +```output TypeName: Microsoft.PowerShell.Commands.PSSessionConfigurationCommands #PSSessionConfiguration @@ -331,62 +343,64 @@ SupportsOptions NoteProperty System.String Suppor... xmlns NoteProperty System.String xmlns=... XmlRenderingType NoteProperty System.String XmlRen... Permission ScriptProperty System.Object Permis... +``` -These properties make it easy to search for specific session -configurations. For example, you can use the ExecutionPolicy -property to find a session configuration that supports sessions -with the RemoteSigned execution policy. Note that, because the -ExecutionPolicy property exists only on sessions that use session -configuration files, the command might not return all qualifying +These properties make it easy to search for specific session configurations. +For example, you can use the ExecutionPolicy property to find a session +configuration that supports sessions with the RemoteSigned execution policy. +Note that, because the ExecutionPolicy property exists only on sessions that +use session configuration files, the command might not return all qualifying session configurations. -PS C:> Get-PSSessionConfiguration | +```powershell +Get-PSSessionConfiguration | where {$_.ExecutionPolicy -eq "RemoteSigned"} +``` -The following command gets session configurations in which the -RunAsUser is the Exchange administrator. +The following command gets session configurations in which the RunAsUser is +the Exchange administrator. -PS C:> Get-PSSessionConfiguration | +```powershell + Get-PSSessionConfiguration | where {$_.RunAsUser -eq "Exchange01\Admin01"} +``` -To view information about the role definitions associated with -a configuration use the Get-PSSessionCapability cmdlet. This -cmdlet enables you to determine the commands and environment -available to specific users in specific endpoints. +To view information about the role definitions associated with a configuration +use the Get-PSSessionCapability cmdlet. This cmdlet enables you to determine +the commands and environment available to specific users in specific +endpoints. -# NOTES +## NOTES -Session configurations also support a type of session known as an -"empty" session. An Empty session type enables you to create -custom sessions with selected commands. If you do not add modules, -functions, or scripts to an empty session, the session is limited -to expressions and might not be of any practical use. The -SessionType property tells you whether or not you are working with -an empty session. +Session configurations also support a type of session known as an "empty" +session. An Empty session type enables you to create custom sessions with +selected commands. If you do not add modules, functions, or scripts to an +empty session, the session is limited to expressions and might not be of any +practical use. The SessionType property tells you whether or not you are +working with an empty session. -# SEE ALSO +## SEE ALSO [about_Session_Configurations](about_Session_Configurations.md) -New-PSSession - -Disable-PSSessionConfiguration +[New-PSSession](../New-PSSession.md) -Enable-PSSessionConfiguration +[Disable-PSSessionConfiguration](../Disable-PSSessionConfiguration.md) -Get-PSSessionConfiguration +[Enable-PSSessionConfiguration](../Enable-PSSessionConfiguration.md) -New-PSSessionConfigurationFile +[Get-PSSessionConfiguration](../Get-PSSessionConfiguration.md) -Register-PSSessionConfiguration +[New-PSSessionConfigurationFile](../New-PSSessionConfigurationFile.md) -Set-PSSessionConfiguration +[Register-PSSessionConfiguration](../Register-PSSessionConfiguration.md) -Test-PSSessionConfigurationFile +[Set-PSSessionConfiguration](../Set-PSSessionConfiguration.md) -Unregister-PSSessionConfiguration +[Test-PSSessionConfigurationFile](../Test-PSSessionConfigurationFile.md) -Get-PSSessionCapability +[Unregister-PSSessionConfiguration](../Unregister-PSSessionConfiguration.md) -New-PSRoleCapabilityFile +[Get-PSSessionCapability](../Get-PSSessionCapability.md) +[New-PSRoleCapabilityFile](../New-PSRoleCapabilityFile.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Signing.md b/reference/6/Microsoft.PowerShell.Core/About/about_Signing.md index e5836ac5ec8e..f8c13a29566e 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Signing.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Signing.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,81 +7,81 @@ title: about_Signing --- # About Signing -## about_Signing +## SHORT DESCRIPTION +Explains how to sign scripts so that they comply with the PowerShell execution +policies. -# SHORT DESCRIPTION +## LONG DESCRIPTION -Explains how to sign scripts so that they comply with the Windows -PowerShell execution policies. +The Restricted execution policy does not permit any scripts to run. The +AllSigned and RemoteSigned execution policies prevent PowerShell from running +scripts that do not have a digital signature. -# LONG DESCRIPTION +This topic explains how to run selected scripts that are not signed, even +while the execution policy is RemoteSigned, and how to sign scripts for your +own use. -The Restricted execution policy does not permit any scripts to run. -The AllSigned and RemoteSigned execution policies prevent Windows -PowerShell from running scripts that do not have a digital signature. +For more information about PowerShell execution policies, see +[about_Execution_Policies](about_Execution_Policies.md). -This topic explains how to run selected scripts that are not signed, -even while the execution policy is RemoteSigned, and how to sign -scripts for your own use. +## TO PERMIT SIGNED SCRIPTS TO RUN -For more information about Windows PowerShell execution policies, -see about_Execution_Policy. - -# TO PERMIT SIGNED SCRIPTS TO RUN - -------------------------------- -When you start Windows PowerShell on a computer for the first time, the -Restricted execution policy (the default) is likely to be in effect. +When you start PowerShell on a computer for the first time, the Restricted +execution policy (the default) is likely to be in effect. The Restricted policy does not permit any scripts to run. To find the effective execution policy on your computer, type: +```powershell Get-ExecutionPolicy +``` -To run unsigned scripts that you write on your local computer and -signed scripts from other users, start Windows PowerShell with the -Run as Administrator option and then use the following command to -change the execution policy on the computer to RemoteSigned: +To run unsigned scripts that you write on your local computer and signed +scripts from other users, start PowerShell with the Run as Administrator +option and then use the following command to change the execution policy on +the computer to RemoteSigned: +```powershell Set-ExecutionPolicy RemoteSigned +``` -For more information, see the help topic for the -Set-ExecutionPolicy cmdlet. +For more information, see the help topic for the Set-ExecutionPolicy cmdlet. -# RUNNING UNSIGNED SCRIPTS (REMOTESIGNED EXECUTION POLICY) +## RUNNING UNSIGNED SCRIPTS (REMOTESIGNED EXECUTION POLICY) --------------------------------------------------------- -If your Windows PowerShell execution policy is RemoteSigned, Windows +If your PowerShell execution policy is RemoteSigned, Windows PowerShell will not run unsigned scripts that are downloaded from the Internet, including unsigned scripts you receive through e-mail and instant messaging programs. -If you try to run a downloaded script, Windows PowerShell displays the +If you try to run a downloaded script, PowerShell displays the following error message: -The file cannot be loaded. The file - is not digitally signed. The script -will not execute on the system. Please see "Get-Help +```output +The file cannot be loaded. The file is not digitally +signed. The script will not execute on the system. Please see "Get-Help about_Signing" for more details. +``` Before you run the script, review the code to be sure that you trust it. Scripts have the same effect as any executable program. -To run an unsigned script, use the Unblock-File cmdlet or use the -Following procedure. +To run an unsigned script, use the Unblock-File cmdlet or use the following +procedure. 1. Save the script file on your computer. 2. Click Start, click My Computer, and locate the saved script file. 3. Right-click the script file, and then click Properties. 4. Click Unblock. -If a script that was downloaded from the Internet is digitally signed, but -you have not yet chosen to trust its publisher, Windows PowerShell displays -the following message: +If a script that was downloaded from the Internet is digitally signed, but you +have not yet chosen to trust its publisher, PowerShell displays the following +message: +```output Do you want to run software from this untrusted publisher? The file is published by CN=. This publisher is not trusted on your system. Only run scripts @@ -89,231 +89,206 @@ from trusted publishers. [V] Never run [D] Do not run [R] Run once [A] Always run [?] Help (default is "D"): +``` -If you trust the publisher, select "Run once" or "Always run." -If you do not trust the publisher, select either "Never run" or -"Do not run." If you select "Never run" or "Always run," Windows -PowerShell will not prompt you again for this publisher. +If you trust the publisher, select "Run once" or "Always run." If you do not +trust the publisher, select either "Never run" or "Do not run." If you select +"Never run" or "Always run," PowerShell will not prompt you again for +this publisher. -# METHODS OF SIGNING SCRIPTS +## METHODS OF SIGNING SCRIPTS --------------------------- -You can sign the scripts that you write and the scripts that you obtain -from other sources. Before you sign any script, examine each command -to verify that it is safe to run. +You can sign the scripts that you write and the +scripts that you obtain from other sources. Before you sign any script, +examine each command to verify that it is safe to run. -For best practices about code signing, see "Code-Signing -Best Practices" at http://go.microsoft.com/fwlink/?LinkId=119096. +For best practices about code signing, see +[Code-Signing Best Practices](http://go.microsoft.com/fwlink/?LinkId=119096). For more information about how to sign a script file, see Set-AuthenticodeSignature. -The New-SelfSignedCertificate cmdlet, introduced in the PKI module -in Windows PowerShell 3.0, creates a self-signed certificate that is -Appropriate for testing. For more information, see the help -topic for the New-SelfSignedCertificate cmdlet. - -To add a digital signature to a script, you must sign it with a code -signing certificate. Two types of certificates are suitable for signing -a script file: +The New-SelfSignedCertificate cmdlet, introduced in the PKI module in +PowerShell 3.0, creates a self-signed certificate that is Appropriate for +testing. For more information, see the help topic for the +New-SelfSignedCertificate cmdlet. --- Certificates that are created by a certification authority: +To add a digital signature to a script, you must sign it with a code signing +certificate. Two types of certificates are suitable for signing a script file: -For a fee, a public certification authority verifies your -identity and gives you a code signing certificate. When -you purchase your certificate from a reputable certification -authority, you are able to share your script with users -on other computers that are running Windows because those other -computers trust the certification authority. +- Certificates that are created by a certification authority: For a fee, a + public certification authority verifies your identity and gives you a code + signing certificate. When you purchase your certificate from a reputable + certification authority, you are able to share your script with users on + other computers that are running Windows because those other computers trust + the certification authority. --- Certificates that you create: +- Certificates that you create: You can create a self-signed certificate for + which your computer is the authority that creates the certificate. This + certificate is free of charge and enables you to write, sign, and run scripts + on your computer. However, a script signed by a self-signed certificate will + not run on other computers. -You can create a self-signed certificate for which -your computer is the authority that creates the certificate. -This certificate is free of charge and enables you to write, -sign, and run scripts on your computer. However, a script -signed by a self-signed certificate will not run on other -computers. +Typically, you would use a self-signed certificate only to sign scripts that +you write for your own use and to sign scripts that you get from other sources +that you have verified to be safe. It is not appropriate for scripts that will +be shared, even within an enterprise. -Typically, you would use a self-signed certificate only to sign -scripts that you write for your own use and to sign scripts that you get -from other sources that you have verified to be safe. It is not -appropriate for scripts that will be shared, even within an enterprise. +If you create a self-signed certificate, be sure to enable strong private key +protection on your certificate. This prevents malicious programs from signing +scripts on your behalf. The instructions are included at the end of this +topic. -If you create a self-signed certificate, be sure to enable strong -private key protection on your certificate. This prevents malicious -programs from signing scripts on your behalf. The instructions are -included at the end of this topic. +## CREATE A SELF-SIGNED CERTIFICATE -# CREATE A SELF-SIGNED CERTIFICATE - --------------------------------- To create a self-signed certificate in use the New-SelfSignedCertificate -cmdlet in the PKI module. This module is introduced in Windows PowerShell -3.0 and is included in Windows 8 and Windows Server 2012. For more -information, see the help topic for the New-SelfSignedCertificate cmdlet. +cmdlet in the PKI module. This module is introduced in PowerShell 3.0 and is +included in Windows 8 and Windows Server 2012. For more information, see the +help topic for the New-SelfSignedCertificate cmdlet. -To create a self-signed certificate in earlier versions of Windows, use -the Certificate Creation tool (MakeCert.exe). This tool is included in -the Microsoft .NET Framework SDK (versions 1.1 and later) and in the -Microsoft Windows SDK. +To create a self-signed certificate in earlier versions of Windows, use the +Certificate Creation tool (MakeCert.exe). This tool is included in the +Microsoft .NET Framework SDK (versions 1.1 and later) and in the Microsoft +Windows SDK. For more information about the syntax and the parameter descriptions of the -MakeCert.exe tool, see "Certificate Creation Tool (MakeCert.exe)" in the -MSDN (Microsoft Developer Network) library at -http://go.microsoft.com/fwlink/?LinkId=119097. +MakeCert.exe tool, see [Certificate Creation Tool (MakeCert.exe)](http://go.microsoft.com/fwlink/?LinkId=119097) +in the MSDN library. To use the MakeCert.exe tool to create a certificate, run the following commands in an SDK Command Prompt window. -Note: The first command creates a local certification authority for -your computer. The second command generates a personal -certificate from the certification authority. +Note: The first command creates a local certification authority for your +computer. The second command generates a personal certificate from the +certification authority. -Note: You can copy or type the commands exactly as they appear. -No substitutions are necessary, although you can change the -certificate name. +Note: You can copy or type the commands exactly as they appear. No +substitutions are necessary, although you can change the certificate name. +```powershell makecert -n "CN=PowerShell Local Certificate Root" -a sha1 ` -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer ` -ss Root -sr localMachine makecert -pe -n "CN=PowerShell User" -ss MY -a sha1 ` -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer +``` -The MakeCert.exe tool will prompt you for a private key password. The -password ensures that no one can use or access the certificate without -your consent. Create and enter a password that you can remember. You will -use this password later to retrieve the certificate. +The MakeCert.exe tool will prompt you for a private key password. The password +ensures that no one can use or access the certificate without your consent. +Create and enter a password that you can remember. You will use this password +later to retrieve the certificate. -To verify that the certificate was generated correctly, use the -following command to get the certificate in the certificate -store on the computer. (You will not find a certificate file in the -file system directory.) +To verify that the certificate was generated correctly, use the following +command to get the certificate in the certificate store on the computer. (You +will not find a certificate file in the file system directory.) -At the Windows PowerShell prompt, type: +At the PowerShell prompt, type: +```powershell get-childitem cert:\CurrentUser\my -codesigning +``` -This command uses the Windows PowerShell Certificate provider to view -information about the certificate. +This command uses the PowerShell Certificate provider to view information +about the certificate. -If the certificate was created, the output shows the thumbprint -that identifies the certificate in a display that resembles the following: +If the certificate was created, the output shows the thumbprint that +identifies the certificate in a display that resembles the following: +```output Directory: Microsoft.PowerShell.Security\Certificate::CurrentUser\My Thumbprint Subject ---------- ------- 4D4917CB140714BA5B81B96E0B18AAF2C4564FDF CN=PowerShell User ] +``` -# SIGN A SCRIPT - -------------- +## SIGN A SCRIPT -After you create a self-signed certificate, you can sign scripts. If you -use the AllSigned execution policy, signing a script permits you to run -the script on your computer. +After you create a self-signed certificate, you can sign scripts. If you use +the AllSigned execution policy, signing a script permits you to run the script +on your computer. -The following sample script, Add-Signature.ps1, signs a script. However, -if you are using the AllSigned execution policy, you must sign the +The following sample script, Add-Signature.ps1, signs a script. However, if +you are using the AllSigned execution policy, you must sign the Add-Signature.ps1 script before you run it. -To use this script, copy the following text into a text file, and -name it Add-Signature.ps1. - -Note: Be sure that the script file does not have a .txt file name -extension. If your text editor appends ".txt", enclose the file name -in quotation marks: "add-signature.ps1". +To use this script, copy the following text into a text file, and name it +Add-Signature.ps1. -## add-signature.ps1 +```powershell ## Signs a file param([string] $file=$(throw "Please specify a filename.")) $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] Set-AuthenticodeSignature $file $cert +``` -To sign the Add-Signature.ps1 script file, type the following commands at -the Windows PowerShell command prompt: +To sign the Add-Signature.ps1 script file, type the following commands at the +PowerShell command prompt: +```powershell $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] - Set-AuthenticodeSignature add-signature.ps1 $cert +``` -After the script is signed, you can run it on the local computer. -However, the script will not run on computers on which the Windows -PowerShell execution policy requires a digital signature from a -trusted authority. If you try, Windows PowerShell displays the following -error message: +After the script is signed, you can run it on the local computer. However, the +script will not run on computers on which the PowerShell execution +policy requires a digital signature from a trusted authority. If you try, +PowerShell displays the following error message: +```output The file C:\remote_file.ps1 cannot be loaded. The signature of the certificate cannot be verified. At line:1 char:15 + .\ remote_file.ps1 <<<< +``` -If Windows PowerShell displays this message when you run a -script that you did not write, treat the file as you would treat any -unsigned script. Review the code to determine whether you can trust the -script. - -# ENABLE STRONG PRIVATE KEY PROTECTION FOR YOUR CERTIFICATE +If PowerShell displays this message when you run a script that you did not +write, treat the file as you would treat any unsigned script. Review the code +to determine whether you can trust the script. ---------------------------------------------------------- +## ENABLE STRONG PRIVATE KEY PROTECTION FOR YOUR CERTIFICATE -If you have a private certificate on your computer, malicious -programs might be able to sign scripts on your behalf, which -authorizes Windows PowerShell to run them. +If you have a private certificate on your computer, malicious programs might +be able to sign scripts on your behalf, which authorizes PowerShell to run +them. -To prevent automated signing on your behalf, use Certificate -Manager (Certmgr.exe) to export your signing certificate to -a .pfx file. Certificate Manager is included in the Microsoft -.NET Framework SDK, the Microsoft Windows SDK, and in Internet -Explorer 5.0 and later versions. +To prevent automated signing on your behalf, use Certificate Manager +(Certmgr.exe) to export your signing certificate to a .pfx file. Certificate +Manager is included in the Microsoft .NET Framework SDK, the Microsoft Windows +SDK, and in Internet Explorer 5.0 and later versions. To export the certificate: 1. Start Certificate Manager. - 2. Select the certificate issued by PowerShell Local Certificate Root. - 3. Click Export to start the Certificate Export Wizard. - 4. Select "Yes, export the private key", and then click Next. - 5. Select "Enable strong protection." - 6. Type a password, and then type it again to confirm. - 7. Type a file name that has the .pfx file name extension. - 8. Click Finish. To re-import the certificate: 1. Start Certificate Manager. - 2. Click Import to start the Certificate Import Wizard. - -3. Open to the location of the .pfx file that you created during the -export process. - +3. Open to the location of the .pfx file that you created during the export + process. 4. On the Password page, select "Enable strong private key protection", -and then enter the password that you assigned during the export -process. - + and then enter the password that you assigned during the export + process. 5. Select the Personal certificate store. - 6. Click Finish. -# PREVENT THE SIGNATURE FROM EXPIRING +## PREVENT THE SIGNATURE FROM EXPIRING ------------------------------------ The digital signature in a script is valid until the signing certificate expires or as long as a time stamp server can verify that the script was signed while the signing certificate was valid. -Because most signing certificates are valid for one year only, using a -time stamp server ensures that users can use your script for many years -to come. +Because most signing certificates are valid for one year only, using a time +stamp server ensures that users can use your script for many years to come. # SEE ALSO @@ -321,13 +296,10 @@ to come. [about_Profiles](about_Profiles.md) -Get-ExecutionPolicy - -New-SelfSignedCertificate - -Set-ExecutionPolicy +[Get-ExecutionPolicy](../../Microsoft.PowerShell.Security/Get-ExecutionPolicy.md) -Set-AuthenticodeSignature +[Set-ExecutionPolicy](../../Microsoft.PowerShell.Security/Set-ExecutionPolicy.md) -"Introduction to Code Signing" (http://go.microsoft.com/fwlink/?LinkId=106296) +[Set-AuthenticodeSignature](../../Microsoft.PowerShell.Security/Set-AuthenticodeSignature.md) +[Introduction to Code Signing](http://go.microsoft.com/fwlink/?LinkId=106296) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Splatting.md b/reference/6/Microsoft.PowerShell.Core/About/about_Splatting.md index 10b1d7bc00db..02d2b8d169e7 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Splatting.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Splatting.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-12-01 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,68 +7,61 @@ title: about_Splatting --- # About Splatting -## about_Splatting +## SHORT DESCRIPTION +Describes how to use splatting to pass parameters to commands in Windows +PowerShell. -# SHORT DESCRIPTION +## LONG DESCRIPTION -Describes how to use splatting to pass parameters to commands -in Windows PowerShell. +[This topic was contributed by Rohn Edwards of Gulfport, Mississippi, a system +administrator and the winner of the Advanced Division of the 2012 Scripting +Games. Revised for Windows PowerShell 3.0.] -# LONG DESCRIPTION +Splatting is a method of passing a collection of parameter values to a command +as unit. Windows PowerShell associates each value in the collection with a +command parameter. Splatted parameter values are stored in named splatting +variables, which look like standard variables, but begin with an At symbol (@) +instead of a dollar sign ($). The At symbol tells Windows PowerShell that you +are passing a collection of values, instead of a single value. -[This topic was contributed by Rohn Edwards of Gulfport, -Mississippi, a system administrator and the winner -of the Advanced Division of the 2012 Scripting Games. -Revised for Windows PowerShell 3.0.] +Splatting makes your commands shorter and easier to read. You can re-use the +splatting values in different command calls and use splatting to pass +parameter values from the `$PSBoundParameters` automatic variable to other +scripts and functions. -Splatting is a method of passing a collection of parameter -values to a command as unit. Windows PowerShell associates -each value in the collection with a command parameter. -Splatted parameter values are stored in named splatting -variables, which look like standard variables, but begin with -an At symbol (@) instead of a dollar sign ($). The At symbol -tells Windows PowerShell that you are passing a collection of -values, instead of a single value. +Beginning in Windows PowerShell 3.0, you can also use splatting to represent +all parameters of a command. -Splatting makes your commands shorter and easier to read. You -can re-use the splatting values in different command calls and -use splatting to pass parameter values from the `$PSBoundParameters` -automatic variable to other scripts and functions. +## SYNTAX -Beginning in Windows PowerShell 3.0, you can also use splatting -to represent all parameters of a command. - -# SYNTAX - -```powershell +``` @ @ ``` -To provide parameter values for positional parameters, in which -parameter names are not required, use the array syntax. To provide -parameter name and value pairs, use the hash table syntax. The -splatted value can appear anywhere in the parameter list. +To provide parameter values for positional parameters, in which parameter +names are not required, use the array syntax. To provide parameter name and +value pairs, use the hash table syntax. The splatted value can appear anywhere +in the parameter list. -When splatting, you do not need to use a hash table or an array to -pass all parameters. You may pass some parameters by using splatting -and pass others by position or by parameter name. Also, you can splat -multiple objects in a single command just so you pass no more than one -value for each parameter. +When splatting, you do not need to use a hash table or an array to pass all +parameters. You may pass some parameters by using splatting and pass others by +position or by parameter name. Also, you can splat multiple objects in a +single command just so you pass no more than one value for each parameter. -# SPLATTING WITH HASH TABLES +## SPLATTING WITH HASH TABLES -Use a hash table to splat parameter name and value pairs. You can use -this format for all parameter types, including positional and named -parameters and switch parameters. +Use a hash table to splat parameter name and value pairs. You can use this +format for all parameter types, including positional and named parameters and +switch parameters. -The following examples compare two `Copy-Item` commands that copy the -Test.txt file to the Test2.txt file in the same directory. +The following examples compare two `Copy-Item` commands that copy the Test.txt +file to the Test2.txt file in the same directory. -The first example uses the traditional format in which parameter names -are included. +The first example uses the traditional format in which parameter names are +included. ```powershell Copy-Item -Path "test.txt" -Destination "test2.txt" -WhatIf @@ -76,9 +69,9 @@ Copy-Item -Path "test.txt" -Destination "test2.txt" -WhatIf The second example uses hash table splatting. The first command creates a hash table of parameter-name and parameter-value pairs and stores it in the -\$HashArguments variable. The second command uses the `$HashArguments` variable -in a command with splatting. The At symbol (`@HashArguments`) replaces the -dollar sign (`$HashArguments`) in the command. +\$HashArguments variable. The second command uses the `$HashArguments` +variable in a command with splatting. The At symbol (`@HashArguments`) +replaces the dollar sign (`$HashArguments`) in the command. To provide a value for the WhatIf switch parameter, use $True or $False. @@ -91,11 +84,11 @@ $HashArguments = @{ Copy-Item @HashArguments ``` -Note: In the first command, the At symbol (@) indicates a hash table, not -a splatted value. The syntax for hash tables in Windows PowerShell is: +Note: In the first command, the At symbol (@) indicates a hash table, not a +splatted value. The syntax for hash tables in Windows PowerShell is: @{\=\; \=\; …}* -# SPLATTING WITH ARRAYS +## SPLATTING WITH ARRAYS Use an array to splat values for positional parameters, which do not require parameter names. The values must be in position-number order in the array. @@ -122,8 +115,7 @@ $ArrayArguments = "test.txt", "test2.txt" Copy-Item @ArrayArguments -WhatIf ``` -# EXAMPLES - +## EXAMPLES This example shows how to re-use splatted values in different commands. The commands in this example use the Write-Host cmdlet to write messages to the @@ -153,18 +145,16 @@ Write-Host "This is a test." @Colors Write-Host @Colors "This is another test." ``` -This example shows how to forward their parameters to other commands by -using splatting and the `$PSBoundParameters` automatic variable. +This example shows how to forward their parameters to other commands by using +splatting and the `$PSBoundParameters` automatic variable. -The $PSBoundParameters automatic variable is a dictionary -(System.Collections.Generic.Dictionary) that contains all of the -parameter names and values that are used when a script or function -is run. +The \$PSBoundParameters automatic variable is a dictionary +(System.Collections.Generic.Dictionary) that contains all of the parameter +names and values that are used when a script or function is run. -In the following example, we use the `$PSBoundParameters` variable to -forward the parameters values passed to a script or function from Test2 -function to the Test1 function. Both calls to the Test1 function from -Test2 use splatting. +In the following example, we use the `$PSBoundParameters` variable to forward +the parameters values passed to a script or function from Test2 function to +the Test1 function. Both calls to the Test1 function from Test2 use splatting. ```powershell function Test1 @@ -188,7 +178,9 @@ function Test2 $LimitedParameters.Remove("a") | Out-Null Test1 @LimitedParameters } +``` +```output Test2 -a 1 -b 2 -c 3 1 2 @@ -197,7 +189,7 @@ Test2 -a 1 -b 2 -c 3 3 ``` -# SPLATTING COMMAND PARAMETERS +## SPLATTING COMMAND PARAMETERS You can use splatting to represent the parameters of a command. This technique is useful when you are creating a proxy function, that is, a function that @@ -207,8 +199,8 @@ To splat the parameters of a command, use `@Args` to represent the command parameters. This technique is easier than enumerating command parameters and it works without revision even if the parameters of the called command change. -The feature uses the `$Args` automatic variable, which contains -all unassigned parameter values. +The feature uses the `$Args` automatic variable, which contains all unassigned +parameter values. For example, the following function calls the Get-Process cmdlet. In this function, `@Args` represents all of the parameters of the Get-Process cmdlet. @@ -217,19 +209,24 @@ function, `@Args` represents all of the parameters of the Get-Process cmdlet. function Get-MyProcess { Get-Process @Args } ``` -When you use the Get-MyProcess function, all unassigned -parameters and parameter values are passed to `@Args`, as -shown in the following commands. +When you use the Get-MyProcess function, all unassigned parameters and +parameter values are passed to `@Args`, as shown in the following commands. ```powershell Get-MyProcess -Name PowerShell +``` +```output Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 463 46 225484 237196 719 15.86 3228 powershell +``` +```powershell Get-MyProcess -Name PowerShell_Ise -FileVersionInfo +``` +```output ProductVersion FileVersion FileName -------------- ----------- -------- 6.2.9200.16384 6.2.9200.1638... C:\Windows\system32\WindowsPowerShell\... @@ -248,7 +245,9 @@ function Get-MyCommand } Get-MyCommand -P -C -Name PowerShell +``` +```output Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 408 28 75568 83176 620 1.33 1692 powershell diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Switch.md b/reference/6/Microsoft.PowerShell.Core/About/about_Switch.md index 1bfafbe78470..cf7500531b40 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Switch.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Switch.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-12-01 +ms.date: 2017-12-06 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -167,9 +167,9 @@ Switch has the following parameters: | |condition. Wildcard and Exact are ignored. Also, if the | | |match clause is not a string, this parameter is ignored. | +In this example, there is no matching case so there is no output. ```powershell -Example: PS> switch ("fourteen") { 1 {"It is one."; Break} @@ -179,7 +179,12 @@ Example: 3 {"Three again."; Break} "fo*" {"That's too many."} } +``` + +For the word "fourteen" to match a case you must use the **-Wildcard** or +**-Regex** parameter. +```powershell PS> switch -Regex ("fourteen") { 1 {"It is one."; Break} @@ -189,6 +194,11 @@ Example: 3 {"Three again."; Break} "fo*" {"That's too many."} } + ``` + + Result: + + ```Output That's too many. ``` diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Transactions.md b/reference/6/Microsoft.PowerShell.Core/About/about_Transactions.md deleted file mode 100644 index e93860f24d7f..000000000000 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Transactions.md +++ /dev/null @@ -1,780 +0,0 @@ ---- -ms.date: 2017-06-09 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_Transactions ---- - -# About Transactions -## about_Transactions - - - -# SHORT DESCRIPTION - -Describes how to manage transacted operations in Windows PowerShell. - -# LONG DESCRIPTION - -Transactions are supported in Windows PowerShell beginning -in Windows PowerShell 2.0. This feature enables you to start -a transaction, to indicate which commands are part of the -transaction, and to commit or roll back a transaction. - -# ABOUT TRANSACTIONS - - -In Windows PowerShell, a transaction is a set of one or more -commands that are managed as a logical unit. A transaction can -be completed ("committed"), which changes data affected by the -transaction. Or, a transaction can be completely undone ("rolled back") -so that the affected data is not changed by the transaction. - -Because the commands in a transaction are managed as a unit, -either all commands are committed, or all commands are rolled -back. - -Transactions are widely used in data processing, most notably -in database operations and for financial transactions. Transactions -are most often used when the worst-case scenario for a set of -commands is not that they all fail, but that some commands succeed -while others fail, leaving the system in a damaged, false, or -uninterpretable state that is difficult to repair. - -# TRANSACTION CMDLETS - - -Windows PowerShell includes several cmdlets designed for managing -transactions. - -Cmdlet Description --------------- --------------------------------- -Start-Transaction Starts a new transaction. - -Use-Transaction Adds a command or expression to the -transaction. The command must use -transaction-enabled objects. - -Undo-Transaction Rolls back the transaction so that -no data is changed by the transaction. - -Complete-Transaction Commits the transaction. The data -affected by the transaction is changed. - -Get-Transaction Gets information about the active -transaction. - -For a list of transaction cmdlets, type: - -get-command *transaction - -For detailed information about the cmdlets, type: - -get-help -detailed - -For example: - -get-help use-transaction -detailed - -# TRANSACTION-ENABLED ELEMENTS - - -To participate in a transaction, both the cmdlet and the provider -must support transactions. This feature is built in to the objects -that are affected by the transaction. - -The Windows PowerShell Registry provider supports transactions -in Windows Vista. The TransactedString object -(Microsoft.PowerShell.Commands.Management.TransactedString) works -with any operating system that runs Windows PowerShell. - -Other Windows PowerShell providers can support transactions. To -find the Windows PowerShell providers in your session that support -transactions, use the following command to find the "Transactions" -value in the Capabilities property of providers: - -get-psprovider | where {$_.Capabilities -like "transactions"} - -For more information about a provider, see the Help for the provider. -To get provider Help, type: - -get-help - -For example, to get Help for the Registry provider, type: - -get-help registry - -# THE USETRANSACTION PARAMETER - - -Cmdlets that can support transactions have a UseTransaction -parameter. This parameter includes the command in the active -transaction. You can use the full parameter name or its alias, -"usetx". - -The parameter can be used only when the session contains an -active transaction. If you enter a command with the UseTransaction -parameter when there is no active transaction, the command fails. - -To find cmdlets with the UseTransaction parameter, type: - -get-help * -parameter UseTransaction - -In Windows PowerShell core, all of the cmdlets designed to work -with Windows PowerShell providers support transactions. As a -result, you can use the provider cmdlets to manage transactions. - -For more information about Windows PowerShell providers, -see about_Providers. - -# THE TRANSACTION OBJECT - - -Transactions are represented in Windows PowerShell by a -transaction object, System.Management.Automation.Transaction. - -The object has the following properties: - -RollbackPreference: -Contains the rollback preference set for the current -transaction. You can set the rollback preference when you -use Start-Transaction to start the transaction. - -The rollback preference determines the conditions under -which the transaction is rolled back automatically. Valid -values are Error, TerminatingError, and Never. The default -value is Error. - -Status: -Contains the current status of the transaction. Valid -values are Active, Committed, and RolledBack. - -SubscriberCount: -Contains the number of subscribers to the transaction. A -subscriber is added to a transaction when you start a -transaction while another transaction is in progress. The -subscriber count is decremented when a subscriber commits -the transaction. - -# ACTIVE TRANSACTIONS - - -In Windows PowerShell, only one transaction is active at a -time, and you can manage only the active transaction. Multiple -transactions can be in progress in the same session at the same -time, but only the most-recently started transaction is active. - -As a result, you cannot specify a particular transaction when -using the transaction cmdlets. Commands always apply to the -active transaction. - -This is most evident in the behavior of the Get-Transaction cmdlet. -When you enter a Get-Transaction command, Get-Transaction always -gets only one transaction object. This object is the object that -represents the active transaction. - -To manage a different transaction, you must first finish the active -transaction, either by committing it or rolling it back. When you -do this, the previous transaction becomes active automatically. -Transactions become active in the reverse of order of which they are -started, so that the most recently started transaction is always -active. - -# SUBSCRIBERS AND INDEPENDENT TRANSACTIONS - - -If you start a transaction while another transaction is in progress, -by default, Windows PowerShell does not start a new transaction. -Instead, it adds a "subscriber" to the current transaction. - -When a transaction has multiple subscribers, a single -Undo-Transaction command at any point rolls back the entire -transaction for all subscribers. However, to commit the transaction, -you must enter a Complete-Transaction command for every subscriber. - -To find the number of subscribers to a transaction, check the -SubscriberCount property of the transaction object. For example, -the following command uses the Get-Transaction cmdlet to get -the value of the SubscriberCount property of the active transaction: - -(Get-Transaction).SubscriberCount - -Adding a subscriber is the default behavior because most transactions -that are started while another transaction is in progress are related -to the original transaction. In the typical model, a script that -contains a transaction calls a helper script that contains its own -transaction. Because the transactions are related, they should be -rolled back or committed as a unit. - -However, you can start a transaction that is independent of the -current transaction by using the Independent parameter of the -Start-Transaction cmdlet. - -When you start an independent transaction, Start-Transaction -creates a new transaction object, and the new transaction becomes -the active transaction. The independent transaction can be -committed or rolled back without affecting the original transaction. - -When the independent transaction is finished (committed or rolled -back), the original transaction becomes the active transaction -again. - -# CHANGING DATA - - -When you use transactions to change data, the data that is affected -by the transaction is not changed until you commit the transaction. -However, the same data can be changed by commands that are not -part of the transaction. - -Keep this in mind when you are using transactions to manage shared -data. Typically, databases have mechanisms that lock the data while -you are working on it, preventing other users, and other commands, -scripts, and functions, from changing it. - -However, the lock is a feature of the database. It is not related -to transactions. If you are working in a transaction-enabled -file system or other data store, the data can be changed while -the transaction is in progress. - -# EXAMPLES - -The examples in this section use the Windows PowerShell Registry -provider and assume that you are familiar with it. For information -about the Registry provider, type "get-help registry". - -# EXAMPLE 1: COMMITTING A TRANSACTION - - -To create a transaction, use the Start-Transaction cmdlet. The -following command starts a transaction with the default settings. - -start-transaction - -To include commands in the transaction, use the UseTransaction -parameter of the cmdlet. By default, commands are not included -in the transaction, - -For example, the following command, which sets the current -location in the Software key of the HKCU: drive, is not included -in the transaction. - -cd hkcu:\Software - -The following command, which creates the MyCompany key, uses the -UseTransaction parameter of the New-Item cmdlet to include the -command in the active transaction. - -new-item MyCompany -UseTransaction - -The command returns an object that represents the new key, but -because the command is part of the transaction, the registry -is not yet changed. - -Hive: HKEY_CURRENT_USER\Software - -SKC VC Name Property ---- -- ---- -------- -0 0 MyCompany {} - -To commit the transaction, use the Complete-Transaction cmdlet. -Because it always affects the active transaction, you cannot specify -the transaction. - -complete-transaction - -As a result, the MyCompany key is added to the registry. - -dir m* - -Hive: HKEY_CURRENT_USER\software - -SKC VC Name Property ---- -- ---- -------- -83 1 Microsoft {(default)} -0 0 MyCompany {} - -# EXAMPLE 2: ROLLING BACK A TRANSACTION - - -To create a transaction, use the Start-Transaction cmdlet. The -following command starts a transaction with the default settings. - -start-transaction - -The following command, which creates the MyOtherCompany key, uses the -UseTransaction parameter of the New-Item cmdlet to include the -command in the active transaction. - -new-item MyOtherCompany -UseTransaction - -The command returns an object that represents the new key, but -because the command is part of the transaction, the registry -is not yet changed. - -Hive: HKEY_CURRENT_USER\Software - -SKC VC Name Property ---- -- ---- -------- -0 0 MyOtherCompany {} - -To roll back the transaction, use the Undo-Transaction cmdlet. -Because it always affects the active transaction, you do not specify -the transaction. - -Undo-transaction - -The result is that the MyOtherCompany key is not added to the registry. - -dir m* - -Hive: HKEY_CURRENT_USER\software - -SKC VC Name Property ---- -- ---- -------- -83 1 Microsoft {(default)} -0 0 MyCompany {} - -# EXAMPLE 3: PREVIEWING A TRANSACTION - - -Typically, the commands used in a transaction change data. However, -the commands that get data are useful in a transaction, too, because -they get data inside of the transaction. This provides a preview of the -changes that committing the transaction would cause. - -The following example shows how to use the Get-ChildItem command -(the alias is "dir") to preview the changes in a transaction. - -The following command starts a transaction. - -start-transaction - -The following command uses the New-ItemProperty cmdlet to add the -MyKey registry entry to the MyCompany key. The command uses the -UseTransaction parameter to include the command in the transaction. - -new-itemproperty -path MyCompany -Name MyKey -value 123 -UseTransaction - -The command returns an object representing the new registry entry, -but the registry entry is not changed. - -MyKey ------ -# 123 - - -To get the items that are currently in the registry, use a Get-ChildItem -command ("dir") without the UseTransaction parameter. The following -command gets items that begin with "M." - -dir m* - -The result shows that no entries have yet been added to the MyCompany key. - -Hive: HKEY_CURRENT_USER\Software - -SKC VC Name Property ---- -- ---- -------- -83 1 Microsoft {(default)} -0 0 MyCompany {} - -To preview the effect of committing the transaction, enter a Get-ChildItem -("dir") command with the UseTransaction parameter. This command has a view -of the data from within the transaction. - -dir m* -useTransaction - -The result shows that, if the transaction is committed, the MyKey entry -will be added to the MyCompany key. - -Hive: HKEY_CURRENT_USER\Software - -SKC VC Name Property ---- -- ---- -------- -83 1 Microsoft {(default)} -0 1 MyCompany {MyKey} - -# EXAMPLE 4: COMBINING TRANSACTED AND NON-TRANSACTED COMMANDS - - -You can enter non-transacted commands during a transaction. The -non-transacted commands affect the data immediately, but they do -not affect the transaction. - -The following command starts a transaction in the HKCU:\Software -registry key. - -start-transaction - -The next three commands use the New-Item cmdlet to add keys to -the registry. The first and third commands use the UseTransaction -parameter to include the commands in the transaction. The second -command omits the parameter. Because the second command is not -included in the transaction, it is effective immediately. - -new-item MyCompany1 -UseTransaction - -new-item MyCompany2 - -new-item MyCompany3 -UseTransaction - -To view the current state of the registry, use a Get-ChildItem ("dir") -command without the UseTransaction parameter. This command gets items -that begin with "M." - -dir m* - -The result shows that the MyCompany2 key is added to the registry, but -the MyCompany1 and MyCompany3 keys, which are part of the transaction, -are not added. - -Hive: HKEY_CURRENT_USER\Software - -SKC VC Name Property ---- -- ---- -------- -83 1 Microsoft {(default)} -0 0 MyCompany2 {} - -The following command commits the transaction. - -complete-transaction - -Now, the keys that were added as part of the transaction appear in the -registry. - -dir m* - -Hive: HKEY_CURRENT_USER\Software - -SKC VC Name Property ---- -- ---- -------- -83 1 Microsoft {(default)} -0 0 MyCompany1 {} -0 0 MyCompany2 {} -0 0 MyCompany3 {} - -# EXAMPLE 5: USING AUTOMATIC ROLLBACK - - -When a command in a transaction generates an error -of any kind, the transaction is automatically rolled -back. - -This default behavior is designed for scripts that -run transactions. Scripts are typically well tested -and include error-handling logic, so errors are not -expected and should terminate the transaction. - -The first command starts a transaction in the HKCU:\Software -registry key. - -start-transaction - -The following command uses the New-Item cmdlet to -add the MyCompany key to the registry. The command uses -the UseTransaction parameter (the alias is "usetx") to include -the command in the transaction. - -New-Item MyCompany -UseTX - -Because the MyCompany key already exists in the registry, -the command fails, and the transaction is rolled back. - -New-Item : A key at this path already exists -At line:1 char:9 -+ new-item <<<< MyCompany -usetx - -A Get-Transaction command confirms that the transaction -has been rolled back and that the SubscriberCount is 0. - -RollbackPreference SubscriberCount Status ------------------- --------------- ------ -Error 0 RolledBack - -# EXAMPLE 6: CHANGING THE ROLLBACK PREFERENCE - - -If you want the transaction to be more error tolerant, -you can use the RollbackPreference parameter of -Start-Transaction to change the preference. - -The following command starts a transaction with a -rollback preference of "Never". - -start-transaction -rollbackpreference Never - -In this case, when the command fails, the transaction -is not automatically rolled back. - -New-Item MyCompany -UseTX - -New-Item : A key at this path already exists -At line:1 char:9 -+ new-item <<<< MyCompany -usetx - -Because the transaction is still active, you can -resubmit the command as part of the transaction. - -New-Item MyOtherCompany -UseTX - -# EXAMPLE 7: USING THE USE-TRANSACTION CMDLET - - -The Use-Transaction cmdlet enables you to do direct scripting -against transaction-enabled Microsoft .NET Framework objects. -Use-Transaction takes a script block that can only contain commands -and expressions that use transaction-enabled .NET Framework objects, -such as instances of the -Microsoft.PowerShell.Commands.Management.TransactedString class. - -The following command starts a transaction. - -start-transaction - -The following New-Object command creates an instance of the -TransactedString class and saves it in the $t variable. - -$t = New-Object Microsoft.PowerShell.Commands.Management.TransactedString - -The following command uses the Append method of the TransactedString -object to add text to the string. Because the command is not part -of the transaction, the change is effective immediately. - -$t.append("Windows") - -The following command uses the same Append method to add text, but -it adds the text as part of the transaction. The command is enclosed -in braces, and it is set as the value of the ScriptBlock parameter of -Use-Transaction. The UseTransaction parameter (UseTx) is required. - -use-transaction {$t.append(" PowerShell")} -usetx - -To see the current content of the transacted string in $t, use the -ToString method of the TransactedString object. - -$t.tostring() - -The output shows that only the non-transacted changes are effective. - -Windows - -To see the current content of the transacted string in $t from within -the transaction, embed the expression in a Use-Transaction command. - -use-transaction {$s.tostring()} -usetx - -The output shows the transaction view. - -Windows PowerShell - -The following command commits the transaction. - -complete-transaction - -To see the final string: - -$t.tostring() - -Windows PowerShell - -# EXAMPLE 8: MANAGING MULTI-SUBSCRIBER TRANSACTIONS - - -When you start a transaction while another transaction is in -progress, Windows PowerShell does not create a second transaction -by default. Instead, it adds a subscriber to the current -transaction. - -This example shows how to view and manage a multi-subscriber -transaction. - -Begin by starting a transaction in the HKCU:\Software key. - -start-transaction - -The following command uses the Get-Transaction command to -get the active transaction. - -get-transaction - -The result shows the object that represents the active transaction. - -RollbackPreference SubscriberCount Status ------------------- --------------- ------ -Error 1 Active - -The following command adds the MyCompany key to the registry. -The command uses the UseTransaction parameter to include the -command in the transaction. - -new-item MyCompany -UseTransaction - -The following command uses the Start-Transaction command to -start a transaction. Although this command is typed at the command -prompt, this scenario is more likely to happen when you run a -script that contains a transaction. - -start-transaction - -A Get-Transaction command shows that the subscriber count on the -transaction object is incremented. The value is now 2. - -RollbackPreference SubscriberCount Status ------------------- --------------- ------ -Error 2 Active - -The next command uses the New-ItemProperty cmdlet to add the -MyKey registry entry to the MyCompany key. It uses the UseTransaction -parameter to include the command in the transaction. - -new-itemproperty -path MyCompany -name MyKey -UseTransaction - -The MyCompany key does not exist in the registry, but this -command succeeds because the two commands are part of the -same transaction. - -The following command commits the transaction. If it rolled back -the transaction, the transaction would be rolled back for all the -subscribers. - -complete-transaction - -A Get-Transaction command shows that the subscriber count on the -transaction object is 1, but the value of Status is still Active -(not Committed). - -RollbackPreference SubscriberCount Status ------------------- --------------- ------ -Error 1 Active - -To finish committing the transaction, enter a second Complete- -Transaction command. To commit a multi-subscriber transaction, -you must enter one Complete-Transaction command for each -Start-Transaction command. - -complete-transaction - -Another Get-Transaction command shows that the transaction -has been committed. - -RollbackPreference SubscriberCount Status ------------------- --------------- ------ -Error 0 Committed - -# EXAMPLE 9: MANAGING INDEPENDENT TRANSACTIONS - - -When you start a transaction while another transaction is in -progress, you can use the Independent parameter of Start-Transaction -to make the new transaction independent of the original transaction. - -When you do, Start-Transaction creates a new transaction object -and makes the new transaction the active transaction. - -Begin by starting a transaction in the HKCU:\Software key. - -start-transaction - -The following command uses the Get-Transaction command to -get the active transaction. - -get-transaction - -The result shows the object that represents the active transaction. - -RollbackPreference SubscriberCount Status ------------------- --------------- ------ -Error 1 Active - -The following command adds the MyCompany registry key as part of -the transaction. It uses the UseTransaction parameter (UseTx) -to include the command in the active transaction. - -new-item MyCompany -use - -The following command starts a new transaction. The command uses -the Independent parameter to indicate that this transaction -is not a subscriber to the active transaction. - -start-transaction -independent - -When you create an independent transaction, the new (most-recently -created) transaction becomes the active transaction. You can use -a Get-Transaction command to get the active transaction. - -get-transaction - -Note that the SubscriberCount of the transaction is 1, indicating -that there are no other subscribers and that the transaction is -new. - -RollbackPreference SubscriberCount Status ------------------- --------------- ------ -Error 1 Active - -The new transaction must be finished (either committed or rolled -back) before you can manage the original transaction. - -The following command adds the MyOtherCompany key to the registry. -It uses the UseTransaction parameter (UseTx) to include the command -in the active transaction. - -new-item MyOtherCompany -usetx - -Now, roll back the transaction. If there were a single -transaction with two subscribers, rolling back the transaction -would roll back the entire transaction for all the subscribers. - -However, because these transactions are independent, rolling -back the newest transaction cancels the registry changes and -makes the original transaction the active transaction. - -undo-transaction - -A Get-Transaction command confirms that the original -transaction is still active in the session. - -get-transaction - -RollbackPreference SubscriberCount Status ------------------- --------------- ------ -Error 1 Active - -The following command commits the active transaction. - -complete-transaction - -A Get-ChildItem command shows that the registry has been -changed. - -dir m* - -Hive: HKEY_CURRENT_USER\Software - -SKC VC Name Property ---- -- ---- -------- -83 1 Microsoft {(default)} -0 0 MyCompany {} - -# SEE ALSO - -Start-Transaction - -Get-Transaction - -Complete-Transaction - -Undo-Transaction - -Use-Transaction - -Registry (provider) - -[about_Providers](about_Providers.md) - -Get-PSProvider - -Get-ChildItem - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Updatable_Help.md b/reference/6/Microsoft.PowerShell.Core/About/about_Updatable_Help.md index 77f69a3b6008..7d45f6555135 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Updatable_Help.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Updatable_Help.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -7,487 +7,455 @@ title: about_Updatable_Help --- # About Updatable Help -## about_Updatable_Help +## SHORT DESCRIPTION +Describes the updatable help system in PowerShell. -# SHORT DESCRIPTION +## LONG DESCRIPTION -Describes the updatable help system in Windows PowerShell. +PowerShell provides several different ways to access the most up-to-date help +topics for PowerShell cmdlets and concepts. -# LONG DESCRIPTION +The Updatable Help system, introduced in PowerShell 3.0, is designed to assure +that you always have the newest help topics on your local computer so that you +can read them at the command line. It makes it easy to download and install +help files and to update them whenever newer help files become available. -Windows PowerShell provides several different ways to access -the most up-to-date help topics for Windows PowerShell cmdlets -and concepts. +To provide updated help for multiple computers in an enterprise and for +computers that do not have access to the Internet, Updatable Help lets you +download help files to a file system directory or file share, and then install +the help files from the file share. -The Updatable Help system, introduced in Windows PowerShell 3.0, -is designed to assure that you always have the newest help topics -on your local computer so that you can read them at the command -line. It makes it easy to download and install help files and -to update them whenever newer help files become available. +In PowerShell 4.0, the HelpInfoUri property is preserved over Windows +PowerShell remoting, which allows Save-Help to work for modules that are +installed on a remote computer, but are not necessarily installed on the local +computer. You can save a PSModuleInfo object to disk or removable media (such +as a USB drive) by running Export-Clixml on a computer that does not have +Internet access, importing the PSModuleInfo object on a computer that does +have Internet access, and then running Save-Help on the PSModuleInfo object. +The saved help can be copied to the remote, disconnected computer by using +removable media, and then installed by running Update-Help. These improvements +in Save-Help functionality let you install help on computers that are without +any kind of network access. For an example of how to use the new Save-Help +functionality, see "HOW TO UPDATE HELP FROM A FILE SHARE: SAVE-HELP" in this +topic. -To provide updated help for multiple computers in an enterprise -and for computers that do not have access to the Internet, Updatable -Help lets you download help files to a file system directory or file -share, and then install the help files from the file share. +Updatable Help also supports online access to the newest help topics and basic +help for cmdlets, even when there are no help files on the computer. -In Windows PowerShell 4.0, the HelpInfoUri property is preserved over -Windows PowerShell remoting, which allows Save-Help to work for -modules that are installed on a remote computer, but are not -necessarily installed on the local computer. You can save a PSModuleInfo -object to disk or removable media (such as a USB drive) by running -Export-CliXml on a computer that does not have Internet access, -importing the PSModuleInfo object on a computer that does have Internet -access, and then running Save-Help on the PSModuleInfo object. The -saved help can be copied to the remote, disconnected computer by using -removable media, and then installed by running Update-Help. These -improvements in Save-Help functionality let you install help on -computers that are without any kind of network access. For an example -of how to use the new Save-Help functionality, see "HOW TO UPDATE HELP -FROM A FILE SHARE: SAVE-HELP" in this topic. +PowerShell 3.0 does not come with Help files. You can use the Updatable Help +feature to install the help files for all of the commands that are included by +default in PowerShell and for all Windows modules. -Updatable Help also supports online access to the newest help topics -and basic help for cmdlets, even when there are no help files on the -computer. - -Windows PowerShell 3.0 does not come with Help files. You can use -the Updatable Help feature to install the help files for all of the -commands that are included by default in Windows PowerShell and for -all Windows modules. - -# UPDATABLE HELP CMDLETS - - -Update-Help: Downloads the newest help files from the Internet or -a file share, and installs them on the local computer. - -Save-Help: Downloads the newest help files from the Internet and -saves them in a file system directory or file share. To -install the help files on computers, use Update-Help. +## UPDATABLE HELP CMDLETS -Get-Help: -- Displays help topics at the command line. --- Gets help from the help files on the computer. --- Displays auto-generated help for cmdlets and functions -that do not have help files. --- Opens online help topics for cmdlets, functions, -scripts, and workflows in your default Internet -browser. +- Update-Help: Downloads the newest help files from the Internet or a file + share, and installs them on the local computer. -# UPDATE HELP IN WINDOWS POWERSHELL ISE +- Save-Help: Downloads the newest help files from the Internet and saves them in + a file system directory or file share. To install the help files on computers, + use Update-Help. -You can also update help by using the "Update Windows PowerShell -Help" item in the Help menu in Windows PowerShell Integrated -Scripting Environment (ISE). +- Get-Help: Displays help topics at the command line. Gets help from the + help files on the computer. Displays auto-generated help for cmdlets and + functions that do not have help files. Opens online help topics for + cmdlets, functions, scripts, and workflows in your default Internet browser. -The "Update Windows PowerShell Help" item runs an Update-Help -command without parameters. +## UPDATE HELP IN PowerShell ISE -# AUTO-GENERATED HELP: HELP WITHOUT HELP FILES +You can also update help by using the "Update PowerShell Help" item in the +Help menu in PowerShell Integrated Scripting Environment (ISE). +The "Update PowerShell Help" item runs an Update-Help command without +parameters. -If you do not have the help file for a cmdlet, function, -or workflow on the computer, the Get-Help cmdlet displays -auto-generated help and prompts you to download the help -files or read them online. +## AUTO-GENERATED HELP: HELP WITHOUT HELP FILES -Auto-generated help includes syntax and aliases, and remarks -that explain how to use the Updatable Help cmdlets and to -access the online help topics. +If you do not have the help file for a cmdlet, function, or workflow on the +computer, the Get-Help cmdlet displays auto-generated help and prompts you to +download the help files or read them online. -For example, the following command gets basic help for the -Get-Culture cmdlet. The output shows the Get-Help display -when there are no help files on the computer. +Auto-generated help includes syntax and aliases, and remarks that explain how +to use the Updatable Help cmdlets and to access the online help topics. -PS C:> Get-Help Get-Culture - -# NAME - -Get-Culture - -# SYNTAX +For example, the following command gets basic help for the Get-Culture cmdlet. +The output shows the Get-Help display when there are no help files on the +computer. -Get-Culture [] +```powershell +Get-Help Get-Culture +``` -# ALIASES +```output +NAME + Get-Culture -None +SYNTAX + Get-Culture [] -# REMARKS +ALIASES + None -To get the latest Help content including descriptions -and examples type: Update-Help. +REMARKS + To get the latest Help content including descriptions and examples + type: Update-Help. +``` -# HELP FILES FOR MODULES +## HELP FILES FOR MODULES +The smallest unit of Updatable Help is help for a module. Module help includes +help for all of the cmdlets, functions, workflows, providers, scripts, and +concepts in a module. You can update help for all modules that are installed +on the computer, even if they are not imported into the current session. -The smallest unit of Updatable Help is help for a module. Module -help includes help for all of the cmdlets, functions, workflows, -providers, scripts, and concepts in a module. You can update help -for all modules that are installed on the computer, even if they -are not imported into the current session. +You can update help for the entire module, but you cannot update help for +individual cmdlets. -You can update help for the entire module, but you cannot update -help for individual cmdlets. - -To find the module that contains a particular cmdlet, use the -following command format: +To find the module that contains a particular cmdlet, use the following +command format: +```powershell (Get-Command ).ModuleName +``` For example, to find the module that contains the Set-ExecutionPolicy cmdlet, type: +```powershell (Get-Command Set-ExecutionPolicy).ModuleName +``` To update help for a particular module, type: +```powershell Update-Help -Module +``` For example, to update help for the module that contains the Set-ExecutionPolicy cmdlet, type: +```powershell Update-Help -Module Microsoft.PowerShell.Security +``` -# PERMISSIONS FOR UPDATABLE HELP - - -To update help for the modules in the $pshome\Modules directory, -you must be member of the Administrators group on the computer. +## PERMISSIONS FOR UPDATABLE HELP -If you are not a member of the Administrators group, you cannot -update help for these modules; but if you have Internet access, -you can view help online in the TechNet Library. +To update help for the modules in the \$pshome\\Modules directory, you must be +member of the Administrators group on the computer. -Updating help for modules in the -$home\Documents\WindowsPowerShell\Modules -directory or modules in other subdirectories of the $home -directory do not require special permissions. +If you are not a member of the Administrators group, you cannot update help +for these modules; but if you have Internet access, you can view help online +in the TechNet Library. -The Update-Help and Save-Help cmdlets have a UseDefaultCredentials -parameter that provides the explicit credentials of the current -user. This parameter is designed for accessing secure Internet -locations. +Updating help for modules in the \$home\\Documents\\WindowsPowerShell\\Modules +directory or modules in other subdirectories of the \$home directory do not +require special permissions. -The Update-Help and Save-Help cmdlets also have a Credential -parameter that allows you to run the command on a remote -computer and access a file share on a third computer. The -Credential parameter is valid only when you use the SourcePath -or LiteralPath parameters of Update-Help and the DestinationPath -or LiteralPath parameters of Save-Help. +The Update-Help and Save-Help cmdlets have a UseDefaultCredentials parameter +that provides the explicit credentials of the current user. This parameter is +designed for accessing secure Internet locations. -# HOW TO INSTALL AND UPDATE HELP FILES +The Update-Help and Save-Help cmdlets also have a Credential parameter that +allows you to run the command on a remote computer and access a file share on +a third computer. The Credential parameter is valid only when you use the +SourcePath or LiteralPath parameters of Update-Help and the DestinationPath or +LiteralPath parameters of Save-Help. +## HOW TO INSTALL AND UPDATE HELP FILES -To download and install help files for the first time, or to update -the help files on your computer, use the Update-Help cmdlet. +To download and install help files for the first time, or to update the help +files on your computer, use the Update-Help cmdlet. -The Update-Help cmdlet does all of the hard work for you, including -the following tasks. +The Update-Help cmdlet does all of the hard work for you, including the +following tasks. --- Determines which modules support Updatable Help. --- Finds the Internet location where each module stores its -Updatable Help files. --- Compares the help files for each module on your computer to -the newest help files that are available for each module. --- Downloads the new files from the Internet. --- Unwraps the help file package. --- Verifies that the files are valid help files. --- Installs the help files in the language-specific subdirectory -of the module directory. +- Determines which modules support Updatable Help. +- Finds the Internet location where each module stores its Updatable Help files. +- Compares the help files for each module on your computer to the newest help + files that are available for each module. +- Downloads the new files from the Internet. +- Unwraps the help file package. +- Verifies that the files are valid help files. +- Installs the help files in the language-specific subdirectory of the module + directory. -To access the new help topics, use the Get-Help cmdlet. You do not -need to restart Windows PowerShell. +To access the new help topics, use the Get-Help cmdlet. You do not need to +restart PowerShell. -To install or update help for all modules on the computer that -supports Updatable Help, type: +To install or update help for all modules on the computer that supports +Updatable Help, type: +```powershell Update-Help +``` -To update help for particular modules, add the Module parameter -of Update-Help. Wildcard characters are permitted in the module name. +To update help for particular modules, add the Module parameter of +Update-Help. Wildcard characters are permitted in the module name. For example, to update help for the ServerManager module, type: +```powershell Update-Help -Module ServerManager - -# NOTES - -Without parameters, Update-Help updates help for all modules -in the session and for all installed modules that support -Updatable Help. To be included, modules must be installed in -directories that are listed in the value of the PSModulePath -environment variable. These are also modules that -are returned by a "Get-Help -ListAvailable" command. - -If the value of the Module parameter is * (all), Update-Help -attempts to update help for all installed modules, including -modules that do not support Updatable Help. This command -typically generates many errors as the cmdlet encounters modules -that do not support Updatable Help. - -# HOW TO UPDATE HELP FROM A FILE SHARE: SAVE-HELP - - -To support computers that are not connected to the Internet, -or to control or streamline help updating in an enterprise, -use the Save-Help cmdlet. The Save-Help cmdlet downloads help -files from the Internet and saves them in a file system directory -that you specify. - -Save-Help compares the help files in the specified directory to -the newest help files that are available for each module. If the -directory has no help files or newer help files are available for -the module, the Save-Help cmdlet downloads the new files from the -Internet. However, it does not unwrap or install the help files. - -To install or update the help files on a computer from help -files that were saved to a file system directory, use the -SourcePath parameter of the Update-Help cmdlet. The Update-Help -cmdlet identifies the newest help files, unwraps and validates them, -and installs them in the language-specific subdirectories of the -module directories. - -For example, to save help for all installed modules to the -\Server\Share directory, type: - -Save-Help -DestinationPath \Server\Share - -Then, to update help from the \Server\Share directory, type: - -Update-Help -SourcePath \Server\Share - -The following examples show the use of Save-Help to save help -for modules that are not installed on the local computer. In -this example, the administrator runs Save-Help to save the help -for the DhcpServer module from an Internet-connected client computer, -without installing the DhcpServer module or DHCP Server role on the -local computer. - -Option 1: Run Invoke-Command to get the PSModuleInfo object for -the remote module, save it in a variable, $m, and then run Save-Help -on the PSModuleInfo object by specifying the variable $m as the -module name. - +``` + +Without parameters, Update-Help updates help for all modules in the session +and for all installed modules that support Updatable Help. To be included, +modules must be installed in directories that are listed in the value of the +PSModulePath environment variable. These are also modules that are returned by +a "Get-Help -ListAvailable" command. + +If the value of the Module parameter is * (all), Update-Help attempts to +update help for all installed modules, including modules that do not support +Updatable Help. This command typically generates many errors as the cmdlet +encounters modules that do not support Updatable Help. + +## HOW TO UPDATE HELP FROM A FILE SHARE: SAVE-HELP + +To support computers that are not connected to the Internet, or to control or +streamline help updating in an enterprise, use the Save-Help cmdlet. The +Save-Help cmdlet downloads help files from the Internet and saves them in a +file system directory that you specify. + +Save-Help compares the help files in the specified directory to the newest +help files that are available for each module. If the directory has no help +files or newer help files are available for the module, the Save-Help cmdlet +downloads the new files from the Internet. However, it does not unwrap or +install the help files. + +To install or update the help files on a computer from help files that were +saved to a file system directory, use the SourcePath parameter of the +Update-Help cmdlet. The Update-Help cmdlet identifies the newest help files, +unwraps and validates them, and installs them in the language-specific +subdirectories of the module directories. + +For example, to save help for all installed modules to the \\\\Server\\Share +directory, type: + +```powershell +Save-Help -DestinationPath \\Server\Share +``` + +Then, to update help from the \\\\Server\\Share directory, type: + +```powershell +Update-Help -SourcePath \\Server\Share +``` + +The following examples show the use of Save-Help to save help for modules that +are not installed on the local computer. In this example, the administrator +runs Save-Help to save the help for the DhcpServer module from an +Internet-connected client computer, without installing the DhcpServer module +or DHCP Server role on the local computer. + +Option 1: Run Invoke-Command to get the PSModuleInfo object for the remote +module, save it in a variable, $m, and then run Save-Help on the PSModuleInfo +object by specifying the variable $m as the module name. + +```powershell $m = Invoke-Command -ComputerName RemoteServer -ScriptBlock { Get-Module -Name DhcpServer -ListAvailable } Save-Help -Module $m -DestinationPath C:\SavedHelp +``` -Option 2: Open a PSSession, targeted at the computer that is -running the DHCP Server module, to get the PSModuleInfo object for -the module, save it in a variable $m, and then run Save-Help on the -object that is saved in the $m variable. +Option 2: Open a PSSession, targeted at the computer that is running the DHCP +Server module, to get the PSModuleInfo object for the module, save it in a +variable $m, and then run Save-Help on the object that is saved in the $m +variable. +```powershell $s = New-PSSession -ComputerName RemoteServer $m = Get-Module -PSSession $s -Name DhcpServer -ListAvailable Save-Help -Module $m -DestinationPath C:\SavedHelp +``` -Option 3: Open a CIM session, targeted at the computer that is -running the DHCP Server module, to get the PSModuleInfo object for -the module, save it in a variable $m, and then run Save-Help on the -object that is saved in the $m variable. +Option 3: Open a CIM session, targeted at the computer that is running the +DHCP Server module, to get the PSModuleInfo object for the module, save it in +a variable $m, and then run Save-Help on the object that is saved in the $m +variable. +```powershell $c = New-CimSession -ComputerName RemoteServer $m = Get-Module -CimSession $c -Name DhcpServer -ListAvailable Save-Help -Module $m -DestinationPath C:\SavedHelp +``` -In the following example, the administrator installs help for the -DHCP Server module on a computer that does not have network access. +In the following example, the administrator installs help for the DHCP Server +module on a computer that does not have network access. -First, run Export-CliXml to export the PSModuleInfo object to -a shared folder or to removable media. +First, run Export-Clixml to export the PSModuleInfo object to a shared folder +or to removable media. +```powershell $m = Get-Module -Name DhcpServer -ListAvailable -Export-CliXml -Path E:\UsbFlashDrive\DhcpModule.xml -InputObject $m - -Next, transport the removable media to a computer that has -Internet access, and then import the PSModuleInfo object with -Import-CliXml. Run Save-Help to save the Help for the imported -DhcpServer module PSModuleInfo object. - -$deserialized_m = Import-CliXml E:\UsbFlashDrive\DhcpModule.xml -Save-Help -Module $deserialized_m -DestinationPath -E:\UsbFlashDrive\SavedHelp +Export-Clixml -Path E:\UsbFlashDrive\DhcpModule.xml -InputObject $m +``` -Finally, transport the removable media back to the computer that -does not have network access, and then install the help by running -Update-Help. +Next, transport the removable media to a computer that has Internet access, +and then import the PSModuleInfo object with Import-Clixml. Run Save-Help to +save the Help for the imported DhcpServer module PSModuleInfo object. -Update-Help -Module DhcpServer -SourcePath +```powershell +$deserialized_m = Import-Clixml E:\UsbFlashDrive\DhcpModule.xml +Save-Help -Module $deserialized_m -DestinationPath ` E:\UsbFlashDrive\SavedHelp +``` -# NOTES: +Finally, transport the removable media back to the computer that does not have +network access, and then install the help by running Update-Help. -Without parameters, Save-Help downloads help for all modules -in the session and for all installed modules that support -Updatable Help. To be included, modules must be installed in -directories that are listed in the value of the PSModulePath -environment variable, on either the local computer or on a remote -computer for which you want to save help. These are also modules -that are returned by running a "Get-Help -ListAvailable" command. +```powershell +Update-Help -Module DhcpServer -SourcePath E:\UsbFlashDrive\SavedHelp +``` -# HOW TO UPDATE HELP FILES IN DIFFERENT LANGUAGES +Without parameters, Save-Help downloads help for all modules in the session +and for all installed modules that support Updatable Help. To be included, +modules must be installed in directories that are listed in the value of the +PSModulePath environment variable, on either the local computer or on a remote +computer for which you want to save help. These are also modules that are +returned by running a "Get-Help -ListAvailable" command. +## HOW TO UPDATE HELP FILES IN DIFFERENT LANGUAGES -By default, the Update-Help and Save-Help cmdlets download -help in the UI culture and language that is set for Windows -on the local computer. If help files for the specified modules -are not available in the local UI culture, Update-Help and -Save-Help use the Windows language fallback rules to find the +By default, the Update-Help and Save-Help cmdlets download help in the UI +culture and language that is set for Windows on the local computer. If help +files for the specified modules are not available in the local UI culture, +Update-Help and Save-Help use the Windows language fallback rules to find the best supported language. -However, you can use the UICulture parameters of the Update-Help -and Save-Help cmdlets to download and install help files in any -UI cultures in which they are available. +However, you can use the UICulture parameters of the Update-Help and Save-Help +cmdlets to download and install help files in any UI cultures in which they +are available. -For example, to save the newest help files for all modules on -the session in Japanese (Ja-jp) and French (fr-FR), type: +For example, to save the newest help files for all modules on the session in +Japanese (Ja-jp) and French (fr-FR), type: +```powershell Save-Help -Path \Server\Share -UICulture ja-jp, fr-fr +``` -If help files for the modules are not available in the languages -that you specified, the Update-Help and Save-Help cmdlets return -an error message that lists the languages in which help for each -module is available so you can choose the alternative that best -meets your needs. +If help files for the modules are not available in the languages that you +specified, the Update-Help and Save-Help cmdlets return an error message that +lists the languages in which help for each module is available so you can +choose the alternative that best meets your needs. -# HOW TO UPDATE HELP AUTOMATICALLY +## HOW TO UPDATE HELP AUTOMATICALLY +To assure that you always have the newest help files, you can add an +Update-Help command to your PowerShell profile. -To assure that you always have the newest help files, you can -add an Update-Help command to your Windows PowerShell profile. +An internal quota prevents the Update-Help command from running more than once +each day. To override the once-per-day maximum, use the Force parameter. -An internal quota prevents the Update-Help command from running -more than once each day. To override the once-per-day maximum, -use the Force parameter. - -Use a command like the following one in your profile. This command -updates help for all installed modules in a background job so it -doesn't disturb your work. It uses an Out-Null command to suppress -the job that is returned and any error messages that would otherwise -appear when you use the command more than once per day. +Use a command like the following one in your profile. This command updates +help for all installed modules in a background job so it doesn't disturb your +work. It uses an Out-Null command to suppress the job that is returned and any +error messages that would otherwise appear when you use the command more than +once per day. +```powershell Start-Job {Update-Help} | Out-Null +``` -You can also create a scheduled job that runs the Update-Help or -Save-Help cmdlet at any interval. +You can also create a scheduled job that runs the Update-Help or Save-Help +cmdlet at any interval. For example, the following command creates a scheduled job that runs an -Update-Help help command every Friday at 5:00 AM. To run this command, -start Windows PowerShell with the "Run as administrator" option. +Update-Help help command every Friday at 5:00 AM. To run this command, start +PowerShell with the "Run as administrator" option. +```powershell Register-ScheduledJob -Name UpdateHelpJob -ScriptBlock {Update-Help} ` -Trigger (New-JobTrigger -Weekly -DaysOfWeek Friday -At "5:00 AM") +``` -For more information about scheduled jobs, see about_Scheduled_Jobs. - -# HOW TO USE ONLINE HELP - +## HOW TO USE ONLINE HELP -If you cannot or choose not to update the help files on your -local computer, you can still get the newest help files online. +If you cannot or choose not to update the help files on your local computer, +you can still get the newest help files online. -To open the online help topic for any cmdlet or function, use -the Online parameter of the Get-Help cmdlet. +To open the online help topic for any cmdlet or function, use the Online +parameter of the Get-Help cmdlet. -For example, the following command opens the online help topic -for the Get-Job cmdlet in your default Internet browser: +For example, the following command opens the online help topic for the Get-Job +cmdlet in your default Internet browser: +```powershell Get-Help Get-Job -Online --or- -Get-Help -on Get-Job - -To get online help for a script, use the Online parameter and -the full path to the script. - -The Online parameter does not work with About topics. To see -the about topics for Windows PowerShell Core, including help -topics about the Windows PowerShell language, see "Windows -PowerShell Core Module About Topics" at -http://go.microsoft.com/fwlink/?LinkID=113206. - -# HOW TO MINIMIZE OR PREVENT INTERNET DOWNLOADS - -To minimize Internet downloads and provide Updatable Help to -users who are not connected to the Internet, use the Save-Help -cmdlet. Download help from the Internet and save it to a network -share. Then, create a Group Policy setting or scheduled job that -runs an Update-Help command on all computers. Set the value of -the SourcePath parameter of the Update-Help cmdlet to the network -share. - -To prevent users who have Internet access from downloading Updatable -Help from the Internet, use the "Set the default source path for -Update-Help" Group Policy setting. +``` -This Group Policy setting implicitly adds the SourcePath parameter, -with the file system location that you specify, to every Update-Help -command on every affected computer. Users can use the SourcePath -parameter explicitly to specify a different file system location, but -they cannot exclude the SourcePath parameter and download help from -the Internet. +To get online help for a script, use the Online parameter and the full path to +the script. -NOTE: The "Set the default source path for Update-Help" group -policy setting appears under Computer Configuration and -User Configuration. However, only the policy setting -under Computer Configuration is effective. The policy -setting under User Configuration is ignored. +The Online parameter does not work with About topics. To see the about topics +for PowerShell Core, including help topics about the PowerShell language, see +[Windows PowerShell Core Module About Topics](http://go.microsoft.com/fwlink/?LinkID=113206). -For more information, see about_Group_Policy_Settings. +## HOW TO MINIMIZE OR PREVENT INTERNET DOWNLOADS -# HOW TO UPDATE HELP FOR NON-STANDARD MODULES +To minimize Internet downloads and provide Updatable Help to users who are not +connected to the Internet, use the Save-Help cmdlet. Download help from the +Internet and save it to a network share. Then, create a Group Policy setting +or scheduled job that runs an Update-Help command on all computers. Set the +value of the SourcePath parameter of the Update-Help cmdlet to the network +share. -To update or save help for a module that is not returned -by the ListAvailable parameter of the Get-Module cmdlet, -import the module into the current session before running -an Update-Help or Save-Help command. On a remote computer, -before running the Save-Help command, import the module into -the current CIM or PSSession--or Invoke-Command script block-- -that is connected to the remote computer. +To prevent users who have Internet access from downloading Updatable Help from +the Internet, use the "Set the default source path for Update-Help" Group +Policy setting. -When the module is in the current session, run the Update-Help -or Save-Help cmdlets without parameters, or use the Module -parameter to specify the module name. +This Group Policy setting implicitly adds the SourcePath parameter, with the +file system location that you specify, to every Update-Help command on every +affected computer. Users can use the SourcePath parameter explicitly to +specify a different file system location, but they cannot exclude the +SourcePath parameter and download help from the Internet. -The Module parameters of the Update-Help and Save-Help -cmdlets accept only a module name. They do not accept the -path to a module file. +NOTE: The "Set the default source path for Update-Help" group policy setting +appears under Computer Configuration and User Configuration. However, only the +policy setting under Computer Configuration is effective. The policy setting +under User Configuration is ignored. -Use this technique to update or save help for any module -that is not returned by the ListAvailable parameter of the -Get-Module cmdlet, such as a module that is installed in a -location that is not listed in the PSModulePath environment -variable, or a module that is not well-formed (the module -directory does not contain at least one file whose base name -is the same as the directory name). +For more information, see [about_Group_Policy_Settings](about_Group_Policy_Settings.md). -# HOW TO SUPPORT UPDATABLE HELP +## HOW TO UPDATE HELP FOR NON-STANDARD MODULES +To update or save help for a module that is not returned by the ListAvailable +parameter of the Get-Module cmdlet, import the module into the current session +before running an Update-Help or Save-Help command. On a remote computer, +before running the Save-Help command, import the module into the current CIM +or PSSession--or Invoke-Command script block-- that is connected to the remote +computer. -If you author a module, you can support online help and -Updatable Help for your modules. For more information, see -"Supporting Updatable Help" and "Supporting Online Help" -in the MSDN Library. +When the module is in the current session, run the Update-Help or Save-Help +cmdlets without parameters, or use the Module parameter to specify the module +name. -Updatable help not available for Windows PowerShell snap-ins -or comment-based help. +The Module parameters of the Update-Help and Save-Help cmdlets accept only a +module name. They do not accept the path to a module file. -# KEYWORDS +Use this technique to update or save help for any module that is not returned +by the ListAvailable parameter of the Get-Module cmdlet, such as a module that +is installed in a location that is not listed in the PSModulePath environment +variable, or a module that is not well-formed (the module directory does not +contain at least one file whose base name is the same as the directory name). -About_Updateable_Help +## HOW TO SUPPORT UPDATABLE HELP -# REMARKS +If you author a module, you can support online help and Updatable Help for +your modules. For more information, see "Supporting Updatable Help" and +"Supporting Online Help" in the MSDN Library. -The Update-Help and Save-Help cmdlets are not supported on -Windows Preinstallation Environment (Windows PE). +Updatable help not available for PowerShell snap-ins or comment-based help. -# SEE ALSO +# REMARKS -Get-Help +The Update-Help and Save-Help cmdlets are not supported on Windows +Preinstallation Environment (Windows PE). -Save-Help +## SEE ALSO -Update-Help +[Get-Help](../Get-Help.md) -Updatable Help Status Table (http://go.microsoft.com/fwlink/?LinkID=270007) +[Save-Help](../Save-Help.md) +[Update-Help](../Update-Help.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_WMI.md b/reference/6/Microsoft.PowerShell.Core/About/about_WMI.md deleted file mode 100644 index 816338a248a5..000000000000 --- a/reference/6/Microsoft.PowerShell.Core/About/about_WMI.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -ms.date: 2017-06-09 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_WMI ---- - -# About WMI -## about_WMI - - -## SHORT DESCRIPTION -Windows Management Instrumentation (WMI) uses the Common Information Model (CIM) to represent systems, applications, networks, devices, and other manageable components of the modern enterprise. - - -## LONG DESCRIPTION -Windows Management Instrumentation (WMI) is Microsoft’s implementation of Web-Based Enterprise Management (WBEM), the industry standard. - -Classic WMI uses DCOM to communicate with networked devices to manage remote systems. Windows PowerShell 3.0 introduces a CIM provider model that uses WinRM to remove the dependency on DCOM. This CIM provider model also uses new WMI provider APIs that enable developers to write Windows PowerShell cmdlets in native code (C\+\+). - -Do not confuse WMI providers with Windows PowerShell providers. Many Windows features have an associated WMI provider that exposes their management capabilities. To get WMI providers, run a WMI query that gets instances of the __Provider WMI class, such as the following query. - - -``` -Get-WmiObject -Class __Provider -``` - - - -## THREE COMPONENTS OF WMI -The following three components of WMI interact with Windows PowerShell: Namespaces, Providers, and Classes. - -WMI Namespaces organize WMI providers and WMI classes into groups of related components. In this way, they are similar to .NET Framework namespaces. Namespaces are not physical locations, but are more like logical databases. All WMI namespaces are instances of the __Namespace system class. The default WMI namespace is Root\/CIMV2 (since Microsoft Windows 2000). To use Windows PowerShell to get WMI namespaces in the current session, use a command with the following format. - - -``` -Get-WmiObject -Class __Namespace -``` - - -To get WMI namespaces in other namespaces, use the Namespace parameter to change the location of the search. The following command finds WMI namespaces that reside in the Root\/Cimv2\/Applications namespace. - - -``` -Get-WmiObject -Class __Namespace -Namespace -root/CIMv2/applications -``` - - -WMI namespaces are hierarchical. Therefore, obtaining a list of all namespaces on a particular system requires performing a recursive query starting at the root namespace. - -WMI Providers expose information about Windows manageable objects. A provider retrieves data from a component, and passes that data through WMI to a management application, such as Windows PowerShell. Most WMI providers are dynamic providers, which means that they obtain the data dynamically when it is requested through the management application. - - -## FINDING WMI CLASSES -In a default installation of Windows 8, there are more than 1,100 WMI classes in Root\/Cimv2. With this many WMI classes, the challenge becomes identifying the appropriate WMI class to use to perform a specific task. Windows PowerShell 3.0 provides two ways to find WMI classes that are related to a specific topic. - -For example,to find WMI classes in the root\CIMV2 WMI namespace that are related to disks, you can use a query such as the one shown here. - - -``` -Get-WmiObject -List *disk* -``` - - -To find WMI classes that are related to memory, you might use a query such as the one shown here. - - -``` -Get-WmiObject -List *memory* -``` - - -The CIM cmdlets also provide the ability to discover WMI classes. To do this, use the Get-CIMClass cmdlet. The command shown here lists WMI classes related to video. - - -``` -Get-CimClass *video* -``` - - -Tab expansion works when changing WMI namespaces, and therefore use of tab expansion makes sub-WMI namespaces easily discoverable. In the following example, the Get-CimClass cmdlet lists WMI classes related to power settings. To find it, type the root\/CIMV2\/ WMI namespace, and then press type the root\/CIMV2\/ WMI namespace, and then press the Tab key several times until the power namespace appears. Here is the command: - - -``` -Get-CimClass *power* -Namespace root/cimv2/power -``` - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_WMI_Cmdlets.md b/reference/6/Microsoft.PowerShell.Core/About/about_WMI_Cmdlets.md deleted file mode 100644 index 08ee68185fcb..000000000000 --- a/reference/6/Microsoft.PowerShell.Core/About/about_WMI_Cmdlets.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -ms.date: 2017-12-01 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_WMI_Cmdlets ---- - -# About WMI Cmdlets - -## SHORT DESCRIPTION - -Provides background information about Windows Management Instrumentation (WMI) -and Windows PowerShell. - -## LONG DESCRIPTION - -This topic provides information about WMI technology, the WMI cmdlets for -Windows PowerShell, WMI-based remoting, WMI accelerators, and WMI -troubleshooting. This topic also provides links to more information about WMI. - -### ABOUT WMI - -Windows Management Instrumentation (WMI) is the Microsoft implementation of -Web-Based Enterprise Management (WBEM), which is an industry initiative to -develop a standard technology for accessing management information in an -enterprise environment. WMI uses the Common Information Model (CIM) industry -standard to represent systems, applications, networks, devices, and other -managed components. CIM is developed and maintained by the Distributed -Management Task Force (DMTF). You can use WMI to manage both local and remote -computers. For example, you can use WMI to do the following: - -- Start a process on a remote computer. -- Restart a computer remotely. -- Get a list of the applications that are installed on a local or remote - computer. -- Query the Windows event logs on a local or remote computer. - -### THE WMI CMDLETS FOR WINDOWS POWERSHELL - -Windows PowerShell implements WMI functionality through a set of cmdlets that -are available in Windows PowerShell by default. You can use these cmdlets to -complete the end-to-end tasks necessary to manage local and remote computers. - -The following WMI cmdlets are included. - -|Cmdlet |Description | -|-----------------|----------------------------------------------| -|Get-WmiObject |Gets instances of WMI classes or information | -| |about the available classes. | -|Invoke-WmiMethod |Calls WMI methods. | -|Register-WmiEvent|Subscribes to a WMI event. | -|Remove-WmiObject |Deletes WMI classes and instances. | -|Set-WmiInstance |Creates or modifies instances of WMI classes. | - -### SAMPLE COMMANDS -The following command displays the BIOS information for the local computer. - -```powershell -C:\PS> get-wmiobject win32_bios | format-list * -``` - -The following command displays information about the WinRM service for three -remote computers. - -```powershell -$wql = "select * from win32_service where name='WinRM'" -get-wmiobject -query $wql -computername server01, server01, server03 -``` - -The following more complex command exits all instances of a program. - -```powershell -C:\PS> notepad.exe -C:\PS> $wql = "select * from win32_process where name='notepad.exe'" -C:\PS> $np = get-wmiobject -query $wql -C:\PS> $np | remove-wmiobject -``` - -### WMI-BASED REMOTING - -While the ability to manage a local system through WMI is useful, it is the -remoting capabilities that make WMI a powerful administrative tool. WMI uses -Microsoft's Distributed Component Object Model (DCOM) to connect to and manage -systems. You might have to configure some systems to allow DCOM connections. -Firewall settings and locked-down DCOM permissions can block WMI's ability to -remotely manage systems. - -### WMI TYPE ACCELERATORS - -Windows PowerShell includes WMI type accelerators. These WMI type accelerators -(shortcuts) allow more direct access to a WMI objects than a non-type -accelerator approach would allow. - -The following type accelerators are supported with WMI: - -[WMISEARCHER] - A shortcut for searching for WMI objects. - -[WMICLASS] - A shortcut for accessing the static properties and methods of a class. - -[WMI] - A shortcut for getting a single instance of a class. - -[WMISEARCHER] is a type accelerator for a ManagementObjectSearcher. It can -take a string constructor to create a searcher that you can then do a GET() -on. - -For example: - -```powershell -PS> $s = [WmiSearcher]'Select * from Win32_Process where Handlecount > 1000' -PS> $s.Get() |sort handlecount |ft handlecount,__path,name -auto - -count __PATH name ------ ------ ---- -1105 \\SERVER01\root\cimv2:Win32_Process.Handle="3724" PowerShell... -1132 \\SERVER01\root\cimv2:Win32_Process.Handle="1388" winlogon.exe -1495 \\SERVER01\root\cimv2:Win32_Process.Handle="2852" iexplore.exe -1699 \\SERVER01\root\cimv2:Win32_Process.Handle="1204" OUTLOOK.EXE -1719 \\SERVER01\root\cimv2:Win32_Process.Handle="1912" iexplore.exe -2579 \\SERVER01\root\cimv2:Win32_Process.Handle="1768" svchost.exe -``` - -[WMICLASS] is a type accelerator for ManagementClass. This has a string -constructor that takes a local or absolute WMI path to a WMI class and returns -an object that is bound to that class. - -For example: - -```powershell -PS> $c = [WMICLASS]"root\cimv2:WIn32_Process" -PS> $c |fl * -Name : Win32_Process -__GENUS : 1 -__CLASS : Win32_Process -__SUPERCLASS : CIM_Process -__DYNASTY : CIM_ManagedSystemElement -__RELPATH : Win32_Process -__PROPERTY_COUNT : 45 -__DERIVATION : {CIM_Process, CIM_LogicalElement, - CIM_ManagedSystemElement} -__SERVER : SERVER01 -__NAMESPACE : ROOT\cimv2 -__PATH : \\SERVER01\ROOT\cimv2:Win32_Process -``` - -[WMI] is a type accelerator for ManagementObject. This has a string -constructor that takes a local or absolute WMI path to a WMI instance and -returns an object that is bound to that instance. - -For example: - -```powershell -PS> $p = [WMI]'\\SERVER01\root\cimv2:Win32_Process.Handle="1204"' -PS> $p.Name -OUTLOOK.EXE -``` - -### WMI TROUBLESHOOTING - -The following problems are the most common problems that might occur when you -try to connect to a remote computer. - -Problem 1: The remote computer is not online. - -If a computer is offline, you will not be able to connect to it by using WMI. -You may receive the following error message: - - Remote server machine does not exist or is unavailable - -If you receive this error message, verify that the computer is online. Try to -ping the remote computer. - -Problem 2: You do not have local administrator rights on the remote computer. - -To use WMI remotely, you must have local administrator rights on the remote -computer. If you do not, access to that computer will be denied. - -To verify namespace security: - -1. Click Start, right-click My Computer, and then click Manage. -2. In Computer Management, expand Services and Applications, right-click WMI - Control, and then click Properties. -3. In the WMI Control Properties dialog box, click the Security tab. - -Problem 3: A firewall is blocking access to the remote computer. - -WMI uses the DCOM (Distributed COM) and RPC (Remote Procedure Call) protocols -to traverse the network. By default, many firewalls block DCOM and RPC -traffic. If your firewall is blocking these protocols, your connection will -fail. For example, Windows Firewall in Microsoft Windows XP Service Pack 2 is -configured to automatically block all unsolicited network traffic, including -DCOM and WMI. In its default configuration, Windows Firewall rejects an -incoming WMI request, and you receive the following error message: - - Remote server machine does not exist or is unavailable - -### MORE INFORMATION ABOUT WMI - -For more information about WMI, see the following topics in the MSDN -(Microsoft Developer Network) library: - -About WMI: http://go.microsoft.com/fwlink/?LinkId=142212 - -WMI Troubleshooting: http://go.microsoft.com/fwlink/?LinkId=142213 - -And, see "Secrets of Windows Management Instrumentation - Troubleshooting and -Tips" in the Microsoft TechNet Script Center: - -http://go.microsoft.com/fwlink/?LinkId=142214 - - -## SEE ALSO - -Get-WmiObject - -Invoke-WmiMethod - -Register-WmiEvent - -Remove-WmiObject - -Set-WmiInstance - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_WQL.md b/reference/6/Microsoft.PowerShell.Core/About/about_WQL.md deleted file mode 100644 index 4413e4b4bf38..000000000000 --- a/reference/6/Microsoft.PowerShell.Core/About/about_WQL.md +++ /dev/null @@ -1,739 +0,0 @@ ---- -ms.date: 2017-06-09 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_WQL ---- - -# About WQL -## about_WQL - - - -# SHORT DESCRIPTION - -Describes WMI Query Language (WQL), which can be -used to get WMI objects in Windows PowerShell. - -# LONG DESCRIPTION - -WQL is the Windows Management Instrumentation (WMI) -query language, which is the language used to get -information from WMI. - -You are not required to use WQL to perform a WMI -query in Windows PowerShell. Instead, you can -use the parameters of the Get-WmiObject or -Get-CimInstance cmdlets. WQL queries are somewhat -faster than standard Get-WmiObject commands and -the improved performance is evident when the commands -run on hundreds of systems. However, be sure that -the time you spend to write a successful WQL query -doesn't outweigh the performance improvement. - -The basic WQL statements you need to use WQL are -Select, Where, and From. - -# WHEN TO USE WQL - - -When working with WMI, and especially with WQL, -do not forget that you are also using Windows -PowerShell. Often, if a WQL query does not work as -expected, it's easier to use a standard Windows -PowerShell command than to debug the WQL query. - -Unless you are returning massive amounts of data -from across bandwidth-constrained remote systems, -it is rarely productive to spend hours trying to -perfect a complicated and convoluted WQL query -when there is a perfectly acceptable Windows -cmdlet that does the same thing, if a bit more -slowly. - -# USING THE SELECT STATEMENT - - -A typical WMI query begins with a Select statement -that gets all properties or particular properties -of a WMI class. To select all properties of a WMI -class, use an asterisk (*). The From keyword -specifies the WMI class. - -A Select statement has the following format: - -Select from - -For example, the following Select statement selects -all properties (*) from the instances of the Win32_Bios -WMI class. - -Select * from Win32_Bios - -To select a particular property of a WMI class, -place the property name between the Select and -From keywords. - -The following query selects only the name of -the BIOS from the Win32_Bios WMI class. The -command saves the query in the $queryName -variable. - -Select Name from Win32_Bios - -To select more than one property, use commas to -separate the property names. The following WMI -query selects the name and the version of the -Win32_Bios WMI class. The command saves the -query in the $queryNameVersion variable. - -Select name, version from Win32_Bios - -# USING THE WQL QUERY - - -There are three ways to use WQL query in Windows -PowerShell command. - --- Use the Get-WmiObject cmdlet --- Use the Get-CimInstance cmdlet --- Use the [wmisearcher] type accelerator. - -# USING THE GET-WMIOBJECT CMDLET - -The most basic way to use the WQL query is to enclose -it in quotation marks (as a string) and then use the -query string as the value of the Query parameter of -the Get-WmiObject cmdlet, as shown in the following -example. - -PS C:> Get-WmiObject -Query "Select * from Win32_Bios" - -SMBIOSBIOSVersion : 8BET56WW (1.36 ) -Manufacturer : LENOVO -Name : Default System BIOS -SerialNumber : R9FPY3P -Version : LENOVO - 1360 - -You can also save the WQL statement in a variable -and then use the variable as the value of the Query -parameter, as shown in the following command. - -PS C:> $query = "Select * from Win32_Bios" -PS C:> Get-WmiObject -Query $query - -You can use either format with any WQL statement. -The following command uses the query in the -$queryName variable to get only the name and -version properties of the system BIOS. - -PS C:> $queryNameVersion = "Select Name, Version from Win32_Bios" -PS C:> Get-WmiObject -Query $queryNameVersion - -# __GENUS : 2 - -__CLASS : Win32_BIOS -# __SUPERCLASS : - -# __DYNASTY : - -# __RELPATH : - -# __PROPERTY_COUNT : 1 - -__DERIVATION : {} -# __SERVER : - -# __NAMESPACE : - -# __PATH : - -Name : Default System BIOS -Version : LENOVO - 1360 - -Remember that you can use the parameters of the -Get-WmiObject cmdlet to get the same result. For -example, the following command also gets the values -of the Name and Version properties of instances of -the Win32_Bios WMI class. - -PS C:> Get-WmiObject -Class Win32_Bios -Property Name, Version - -# __GENUS : 2 - -__CLASS : Win32_BIOS -# __SUPERCLASS : - -# __DYNASTY : - -# __RELPATH : - -# __PROPERTY_COUNT : 1 - -__DERIVATION : {} -# __SERVER : - -# __NAMESPACE : - -# __PATH : - -Name : Default System BIOS -Version : LENOVO - 1360 - -# USING THE GET-CIMINSTANCE CMDLET - - -Beginning in Windows PowerShell 3.0, you can use -the Get-CimInstance cmdlet to run WQL queries. - -Get-CimInstance gets instances of CIM-compliant -classes, including WMI classes. The CIM cmdlets, -introduced Windows PowerShell 3.0, perform the same -tasks as the WMI cmdlets. The CIM cmdlets comply -with WS-Management (WSMan) standards and with the -Common Information Model (CIM) standard, which enables -the cmdlets to use the same techniques to manage -Windows computers and computers that are running -other operating systems. - -The following command uses the Get-CimInstance -cmdlet to run a WQL query. - -Any WQL query that can be used with Get-WmiObject -can also be used with Get-CimInstance. - -PS C:> Get-CimInstance -Query "Select * from Win32_Bios" - -SMBIOSBIOSVersion : 8BET56WW (1.36 ) -Manufacturer : LENOVO -Name : Default System BIOS -SerialNumber : R9FPY3P -Version : LENOVO - 1360 - -Get-CimInstance returns a CimInstance object, instead of -the ManagementObject that Get-WmiObject returns, but -the objects are quite similar. - -PS C:> (Get-CimInstance -Query "Select * from Win32_Bios").GetType().FullName -Microsoft.Management.Infrastructure.CimInstance -PS C:> (Get-WmiObject -Query "Select * from Win32_Bios").GetType().FullName -System.Management.ManagementObject - -USING THE [wmisearcher] TYPE ACCELERATOR - -The [wmisearcher] type accelerator creates a -ManagementObjectSearcher object from a WQL -statement string. The ManagementObjectSearcher -object has many properties and methods, but the -most basic method is the Get method, which -invokes the specified WMI query and returns -the resulting objects. - -By using the [wmisearcher], you gain easy access -to the ManagementObjectSearcher .NET Framework class. -This lets you query WMI and to configure the way -the query is conducted. - -To use the [wmisearcher] type accelerator: - -1. Cast the WQL string into a ManagementObjectSearcher -object. -2. Call the Get method of the ManagementObjectSearcher -object. - -For example, the following command casts the "select -all" query, saves the result in the $bios variable, -and then calls the Get method of the ManagementObjectSearcher -object in the $bios variable. - -PS C:> $bios = [wmisearcher]"Select * from Win32_Bios" -PS C:> $bios.Get() - -SMBIOSBIOSVersion : 8BET56WW (1.36 ) -Manufacturer : LENOVO -Name : Default System BIOS -SerialNumber : R9FPY3P -Version : LENOVO - 1360 - -NOTE: Only selected object properties are displayed -by default. These properties are defined in the -Types.ps1xml file. - -You can use the [wmisearcher] type accelerator to -cast the query or the variable. In the following -example, the [wmisearcher] type accelerator is -used to cast the variable. The result is the same. - -PS C:> [wmisearcher]$bios = "Select * from Win32_Bios" -PS C:> $bios.Get() - -SMBIOSBIOSVersion : 8BET56WW (1.36 ) -Manufacturer : LENOVO -Name : Default System BIOS -SerialNumber : R9FPY3P -Version : LENOVO - 1360 - -When you use the [wmisearcher] type accelerator, it -changes the query string into a ManagementObjectSearcher -object, as shown in the following commands. - -PS C:> $a = "Select * from Win32_Bios" -PS C:> $a.GetType().FullName -System.String - -PS C:> $a = [wmisearcher]"Select * from Win32_Bios" -PS C:> $a.GetType().FullName -System.Management.ManagementObjectSearcher - -This command format works on any query. The following -command gets the value of the Name property of the -Win32_Bios WMI class. - -PS C:> $biosname = [wmisearcher]"Select Name from Win32_Bios" -PS C:> $biosname.Get() - -# __GENUS : 2 - -__CLASS : Win32_BIOS -# __SUPERCLASS : - -# __DYNASTY : - -# __RELPATH : - -# __PROPERTY_COUNT : 1 - -__DERIVATION : {} -# __SERVER : - -# __NAMESPACE : - -# __PATH : - -Name : Default System BIOS - -You can perform this operation in a single command, -although the command is a bit more difficult to -interpret. - -In this format, you use the [wmisearcher] type -accelerator to cast the WQL query string to a -ManagementObjectSearcher, and then call the Get -method on the object -- all in a single command. -The parentheses () that enclose the casted string -direct Windows PowerShell to cast the string before -calling the method. - -PS C:> ([wmisearcher]"Select name from Win32_Bios").Get() - -# __GENUS : 2 - -__CLASS : Win32_BIOS -# __SUPERCLASS : - -# __DYNASTY : - -# __RELPATH : - -# __PROPERTY_COUNT : 1 - -__DERIVATION : {} -# __SERVER : - -# __NAMESPACE : - -# __PATH : - -Name : Default System BIOS - -# USING THE BASIC WQL WHERE STATEMENT - - -A Where statement establishes conditions -for the data that a Select statement returns. - -The Where statement has the following format: - -where - -For example: - -where Name = 'Notepad.exe' - -The Where statement is used with the Select -statement, as shown in the following example. - -Select * from Win32_Process where Name = 'Notepad.exe' - -When using the Where statement, the property name -and value must be accurate. - -For example, the following command gets the Notepad -processes on the local computer. - -PS C:> Get-WmiObject -Query "Select * from Win32_Process where name = 'Notepad.exe'" - -However, the following command fails, because the -process name includes the ".exe" file name -extension. - -PS C:> Get-WmiObject -Query "Select * from Win32_Process where name = 'Notepad'" - -# WHERE STATEMENT COMPARISON OPERATORS - -The following operators are valid in a -WQL Where statement. - -Operator Description ------------------------ -= Equal -!= Not equal -<> Not equal -< Less than -> Greater than -<= Less than or equal ->= Greater than or equal -LIKE Wildcard match -IS Evaluates null -ISNOT Evaluates not null -ISA Evaluates a member of a WMI class - -There are other operators, but these are the ones -used for making comparisons. - -For example, the following query selects the Name -and Priority properties from processes in the -Win32_Process class where the process priority -is greater than or equal to 11. The Get-WmiObject -cmdlet runs the query. - -$highPriority = "Select Name, Priority from Win32_Process where Priority >= 11" -Get-WmiObject -Query $highPriority - -# USING THE WQL OPERATORS IN THE FILTER PARAMETER - - -The WQL operators can also be used in the value -of the Filter parameter of the Get-WmiObject or -Get-CimInstance cmdlets, as well as in the value -of the Query parameters of these cmdlets. - -For example, the following command gets the Name -and ProcessID properties of the last five processes -that have ProcessID values greater than 1004. The -command uses the Filter parameter to specify the -ProcessID condition. - -PS C:> Get-WmiObject -Class Win32_Process ` --Property Name, ProcessID -Filter "ProcessID >= 1004" | -Sort ProcessID | Select Name, ProcessID -Last 5 - -Name ProcessID ----- --------- -SROSVC.exe 4220 -# WINWORD.EXE 4664 - -TscHelp.exe 4744 -SnagIt32.exe 4748 -WmiPrvSE.exe 5056 - -# USING THE LIKE OPERATOR - -The Like operator lets you use wildcard characters -to filter the results of a WQL query. - -Like Operator Description --------------------------------------------------- -[] Character in a range [a-f] or a set -of characters [abcdef]. The items in -a set do not need to be consecutive or -listed in alphabetical order. - -^ Character not in a range [^a-f] or -not in a set [^abcdef]. The items in -a set do not need to be consecutive or -listed in alphabetical order. - -% A string of zero or more characters - -_ One character. -(underscore) NOTE: To use a literal underscore -in a query string, enclose it in -square brackets [_]. - -When the Like operator is used without any wildcard -characters or range operators, it behaves like the -equality operator (=) and returns objects only -when they are an exact match for the pattern. - -You can combine the range operation with the percent -wildcard character to create simple, yet powerful -filters. - -# LIKE OPERATOR EXAMPLES - - -EXAMPLE 1: [] -The following commands start Notepad and then -search for an instance of the Win32_Process -class that has a name that starts with a letter -between "H" and "N" (case-insensitive). - -The query should return any process from Hotpad.exe -through Notepad.exe. - -PS C:> Notepad # Starts Notepad -PS C:> $query = "Select * from win32_Process where Name LIKE '[H-N]otepad.exe'" -PS C:> Get-WmiObject -Query $query | Select Name, ProcessID - -Name ProcessID ----- --------- -notepad.exe 1740 - -EXAMPLE 2: [] and % -The following commands select all process -that have a name that begins with a letter between -A and P (case-insensitive) followed by zero or more -letters in any combination. - -The Get-WmiObject cmdlet runs the query, the -Select-Object cmdlet gets the Name and ProcessID -properties, and the Sort-Object cmdlet sorts the -results in alphabetical order by name. - -PS C:> $query = "Select * from win32_Process where name LIKE '[A-P]%'" -PS C:> Get-WmiObject -Query $query | -Select-Object -Property Name, ProcessID | -Sort-Object -Property Name - -EXAMPLE 3: Not in Range (^) -The following command gets processes whose names -do not begin with any of the following letters: -# A, S, W, P, R, C, U, N - -and followed zero or more letters. - -PS C:> $query = "Select * from win32_Process where name LIKE '[^ASWPRCUN]%'" -PS C:> Get-WmiObject -Query $query | -Select-Object -Property Name, ProcessID | -Sort-Object -Property Name - -EXAMPLE 4: Any characters -- or none (%) -The following commands get processes that have -names that begin with "calc". The % symbol in -WQL is equivalent to the asterisk (*) symbol in -regular expressions. - -PS C:> $query = "Select * from win32_Process where Name LIKE 'calc%'" -PS C:> Get-WmiObject -Query $query | Select-Object -Property Name, ProcessID - -Name ProcessID ----- --------- -calc.exe 4424 - -EXAMPLE 5: One character (_) -The following commands get processes that -have names that have the following pattern, -"c_lc.exe" where the underscore character -represents any one character. This pattern -matches any name from calc.exe through -czlc.exe, or c9lc.exe, but does not match -names in which the "c" and "l" are separated -by more than one character. - -PS C:> $query = "Select * from Win32_Process where Name LIKE 'c_lc.exe'" -PS C:> Get-WmiObject -Query $query | Select-Object -Property Name, ProcessID - -Name ProcessID ----- --------- -calc.exe 4424 - -EXAMPLE 6: Exact match -The following commands get processes named -WLIDSVC.exe. Even though the query uses the -Like keyword, it requires an exact match, -because the value does not include any -wildcard characters. - -$query = "Select * from win32_Process where name LIKE 'WLIDSVC.exe'" -Get-WmiObject -Query $query | Select-Object -Property Name, ProcessID - -Name ProcessID ----- --------- -WLIDSVC.exe 84 - -# USING THE OR OPERATOR - -To specify multiple independent conditions, use the Or -keyword. The Or keyword appears in the Where clause. It -performs an inclusive OR operation on two (or more) -conditions and returns items that meet any of the -conditions. - -The Or operator has the following format: - -Where or ... - -For example, the following commands get all instances -of the Win32_Process WMI class but returns them -only if the process name is winword.exe or excel.exe. - -PS C:> $q = "Select * from Win32_Process where Name = 'winword.exe' or Name = 'excel.exe'" -PS C:> Get-WmiObject -Query $q - -The Or statement can be used with more than two -conditions. In the following query, the Or statement -gets Winword.exe, Excel.exe, or Powershell.exe. - -$q = "Select * from Win32_Process where Name = 'winword.exe' or Name = 'excel.exe' or Name = 'powershell.exe'" - -# USING THE AND OPERATOR - -To specify multiple related conditions, use the And -keyword. The And keyword appears in the Where clause. It -returns items that meet all of the conditions. - -The And operator has the following format: - -Where and ... - -For example, the following commands get processes -that have a name of "Winword.exe" and the process -ID of 6512. - -Note that the commands use the Get-CimInstance cmdlet. - -PS C:> $q = "Select * from Win32_Process where Name = 'winword.exe' and ProcessID =6512" -PS C:> Get-CimInstance -Query $q - -ProcessId Name HandleCount WorkingSetSize VirtualSize ---------- ---- ----------- -------------- ----------- -# 6512 WINWORD.EXE 768 117170176 633028608 - - -All operators, including the Like operators are -valid with the Or and And operators. And, you can -combine the Or and And operators in a single query -with parentheses that tell Windows PowerShell which -clauses to process first. - -This command uses the Windows PowerShell continuation -character (`) divide the command into two lines. - -PS C:> $q = "Select * from Win32_Process ` -where (Name = 'winword.exe' or Name = 'excel.exe') and HandleCount > 700" - -PS C:> Get-CimInstance -Query $q -ProcessId Name HandleCount WorkingSetSize VirtualSize ---------- ---- ----------- -------------- ----------- -# 6512 WINWORD.EXE 797 117268480 634425344 - -# 9610 EXCEL.EXE 727 38858752 323227648 - - -# SEARCHING FOR NULL VALUES - -Searching for null values in WMI is challenging, -because it can lead to unpredictable results. Null -is not zero and it is not equivalent or to an empty -string. Some WMI class properties are initialized and -others are not, so a search for null might not work -for all properties. - -To search for null values, use the Is operator with -a value of "null". - -For example, the following commands get processes -that have a null value for the IntallDate property. -The commands return many processes. - -PS C:> $q = "Select * from Win32_Process where InstallDate is null" -PS C:> Get-WmiObject -Query $q - -In contrast, the following command, gets user -accounts that have a null value for the Description -property. This command does not return any user -accounts, even though most user accounts do not have -any value for the Description property. - -PS C:> $q = "Select * from Win32_UserAccount where Description is null" -PS C:> Get-WmiObject -Query $q - -To find the user accounts that have no value for -the Description property, use the equality operator -to get an empty string. To represent the empty string, -use two consecutive single quotation marks. - -$q = "Select * from Win32_UserAccount where Description = '' " - -# USING TRUE OR FALSE - -To get Boolean values in the properties of WMI -objects, use True and False. They are not case -sensitive. - -The following WQL query returns only local user -accounts from a domain joined computer. - -PS C:> $q = "Select * from Win32_UserAccount where LocalAccount = True" -PS C:> Get-CimInstance -Query $q - -To find domain accounts, use a value of False, -as shown in the following example. - -PS C:> $q = "Select * from Win32_UserAccount where LocalAccount = False" -PS C:> Get-CimInstance -Query $q - -# USING THE ESCAPE CHARACTER - -WQL uses the backslash () as its escape -character. This is different from Windows -PowerShell, which uses the backtick -character (`). - -Quotation marks, and the characters used for -quotation marks, often need to be escaped so -that they are not misinterpreted. - -To find a user whose name includes a single quotation -mark, use a backslash to escape the single quotation -mark, as shown in the following command. - -PS C:> $q = "Select * from Win32_UserAccount where Name = 'Tim O\'Brian'" -PS C:> Get-CimInstance -Query $q -Name Caption AccountType SID Domain ----- ------- ----------- --- ------ -Tim O'Brian FABRIKAM\TimO 512 S-1-5-21-1457... FABRIKAM - -In some case, the backslash also needs to be -escaped. For example, the following commands -generate an Invalid Query error due to the -backslash in the Caption value. - -PS C:> $q = "Select * from Win32_UserAccount where Caption = 'Fabrikam\TimO'" -PS C:> Get-CimInstance -Query $q -Get-CimInstance : Invalid query -At line:1 char:1 -+ Get-CimInstance -Query $q -# +!INCLUDE[]~~~~~~~~~~~ - -+ CategoryInfo : InvalidArgument: (:) [Get-CimInstance], CimException -+ FullyQualifiedErrorId : HRESULT 0x80041017,Microsoft.Management.Infrastructure.CimCmdlets - -To escape the backslash, use a second backslash -character, as shown in the following command. - -PS C:> $q = "Select * from Win32_UserAccount where Caption = 'Fabrikam\TimO'" -PS C:> Get-CimInstance -Query $q - -# SEE ALSO - -[about_Special_Characters](about_Special_Characters.md) - -[about_Quoting_Rules](about_Quoting_Rules.md) - -[about_WMI](about_WMI.md) - -[about_WMI_Cmdlets](about_WMI_Cmdlets.md) - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_WS-Management_Cmdlets.md b/reference/6/Microsoft.PowerShell.Core/About/about_WS-Management_Cmdlets.md deleted file mode 100644 index c33d88dcf883..000000000000 --- a/reference/6/Microsoft.PowerShell.Core/About/about_WS-Management_Cmdlets.md +++ /dev/null @@ -1,195 +0,0 @@ ---- -ms.date: 2017-06-09 -schema: 2.0.0 -locale: en-us -keywords: powershell,cmdlet -title: about_WS Management_Cmdlets ---- - -# About WS-Management Cmdlets -## about_WS-Management_Cmdlets - - -# SHORT DESCRIPTION - -Provides an overview of Web Services for Management (WS-Management) as -background for using the WS-Management cmdlets in Windows PowerShell. - -# LONG DESCRIPTION - -This topic provides an overview of Web Services for Management -(WS-Management) as background for using the WS-Management cmdlets in -Windows PowerShell. This topic also provides links to more information -about WS-Management. The Microsoft implementation of WS-Management is also -known as Windows Remote Management (WinRM). - -About WS-Management - -Windows Remote Management is the Microsoft implementation -of the WS-Management protocol, a standard SOAP-based, firewall-friendly -protocol that allows hardware and operating systems from different -vendors to interoperate. The WS-Management protocol specification -provides a common way for systems to access and exchange management -information across an information technology (IT) infrastructure. -WS-Management and Intelligent Platform Management Interface (IPMI), -along with the Event Collector, are components of the Windows Hardware -Management features. - -The WS-Management protocol is based on the following standard Web service -specifications: HTTPS, SOAP over HTTP (WS-I profile), SOAP 1.2, -WS-Addressing, WS-Transfer, WS-Enumeration, and WS-Eventing. - -WS-Management and WMI - -WS-Management can be used to retrieve data exposed by Windows Management -Instrumentation (WMI). You can obtain WMI data with scripts or -applications that use the WS-Management Scripting API or through the -WinRM command-line tool. WS-Management supports most of the familiar WMI -classes and operations, including embedded objects. WS-Management can -leverage WMI to collect data about resources or to manage resources on a -Windows-based computers. That means that you can obtain data -about objects such as disks, network adapters, services, or processes -in your enterprise through the existing set of WMI classes. You can also -access the hardware data that is available from the standard WMI IPMI -provider. - -WS-Management Windows PowerShell Provider (WSMan) - -The WSMan provider provides a hierarchical view into the -available WS-Management configuration settings. The provider allows you -to explore and set the various WS-Management configuration options. - -WS-Management Configuration - -If WS-Management is not installed and configured, Windows PowerShell -remoting is not available, the WS-Management cmdlets do not run, -WS-Management scripts do not run, and the WSMan provider cannot -perform data operations. The WS-Management command-line tool, WinRM, -and event forwarding also depend on the WS-Management configuration. - -WS-Management Cmdlets - -WS-Management functionality is implemented in Windows PowerShell through -a module that contains a set of cmdlets and the WSMan provider. -You can use these cmdlets to complete the end-to-end tasks necessary -to manage WS-Management settings on local and remote computers. - -The following WS-Management cmdlets are available. - -Connection Cmdlets - --- Connect-WSMan: Connects the local computer to the WS-Management -(WinRM) service on a remote computer. - --- Disconnect-WSMan: Disconnects the local computer from the WS-Management -(WinRM) service on a remote computer. - -Management-Data Cmdlets - --- Get-WSManInstance: Displays management information for a resource -instance that is specified by a resource URI. - --- Invoke-WSManAction: Invokes an action on the target object that -is specified by the resource URI and by the selectors. - --- New-WSManInstance: Creates a new management resource instance. - --- Remove-WSManInstance: Deletes a management resource instance. - --- Set-WSManInstance: Modifies the management information that is -related to a resource. - -Setup and Configuration Cmdlets - --- Set-WSManQuickConfig: Configures the local computer for remote -management. You can use the Set-WSManQuickConfig cmdlet to configure -WS-Management to allow remote connections to the WS-Management (WinRM) -service. The Set-WSManQuickConfig cmdlet performs the following -operations: - -- It determines whether the WS-Management (WinRM) service is running. -If the WinRM service is not running, the Set-WSManQuickConfig cmdlet -starts the service. - -- It sets the WS-Management (WinRM) service startup type to automatic. - -- It creates a listener that accepts requests from any IP address. -The default transport protocol is HTTP. - -- It enables a firewall exception for WS-Management traffic. - -Note: To run this cmdlet in Windows Vista, Windows Server 2008, and -later versions of Windows, you must start Windows PowerShell -with the "Run as administrator" option. - --- Test-WSMan: Verifies that WS-Management is installed and configured. -The Test-WSMan cmdlet tests whether the WS-Management (WinRM) -service is running and configured on a local or remote computer. - --- Disable-WSManCredSSP: Disables CredSSP authentication on a client -computer. - --- Enable-WSManCredSSP: Enables CredSSP authentication on a client -computer. - --- Get-WSManCredSSP: Gets the CredSSP-related configuration for a -client computer. - -WS-Management-Specific Cmdlets - --- New-WSManSessionOption: Creates a WSManSessionOption object to use as -input to one or more parameters of a WS-Management cmdlet. - -Additional WS-Management Information - -For more information about WS-Management, see the following topics in the -MSDN (Microsoft Developer Network) library. - -"Windows Remote Management" -http://go.microsoft.com/fwlink/?LinkId=142321 - -"About Windows Remote Management" -http://go.microsoft.com/fwlink/?LinkId=142322 - -"Installation and Configuration for Windows Remote Management" -http://go.microsoft.com/fwlink/?LinkId=142323 - -"Windows Remote Management Architecture" -http://go.microsoft.com/fwlink/?LinkId=142324 - -"WS-Management Protocol" -http://go.microsoft.com/fwlink/?LinkId=142325 - -"Windows Remote Management and WMI" -http://go.microsoft.com/fwlink/?LinkId=142326 - -"Resource URIs" -http://go.microsoft.com/fwlink/?LinkId=142327 - -"Remote Hardware Management" -http://go.microsoft.com/fwlink/?LinkId=142328 - -"Events" -http://go.microsoft.com/fwlink/?LinkId=142329 - -# SEE ALSO - -Online version: http://go.microsoft.com/fwlink/?LinkId=142331 -Connect-WSMan -Disable-WSManCredSSP -Disconnect-WSMan -Enable-WSManCredSSP -Get-WSManCredSSP -Get-WSManInstance -Invoke-WSManAction -New-WSManInstance -Remove-WSManInstance -Set-WSManInstance -Set-WSManQuickConfig -Set-WSManSessionOption -Test-WSMan - -# KEYWORDS - -about_WSMAN about_WinRM - diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_hidden.md b/reference/6/Microsoft.PowerShell.Core/About/about_hidden.md index e64ac4f500a6..50b1758d40d5 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_hidden.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_hidden.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-04 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -27,17 +27,17 @@ Hidden members are not displayed by using tab completion or IntelliSense, unless the completion occurs in the class that defines the hidden member. A new attribute, System.Management.Automation.HiddenAttribute, has been added, -so that C# code can have the same semantics within Windows PowerShell. +so that C\# code can have the same semantics within PowerShell. The Hidden keyword is useful for creating properties and methods within a class that you do not necessarily want other users of the class to see, or readily be able to edit. The Hidden keyword has no effect on how you can view or make changes to -members of a class. Like all language keywords in Windows PowerShell, Hidden -is not case-sensitive, and hidden members are still public. +members of a class. Like all language keywords in PowerShell, Hidden is not +case-sensitive, and hidden members are still public. -Hidden, along with custom classes, was introduced in Windows PowerShell 5.0. +Hidden, along with custom classes, was introduced in PowerShell 5.0. ## EXAMPLE @@ -46,7 +46,7 @@ definition. The Car class method, Drive, has a property, rides, that does not need to be viewed or changed (it merely tallies the number of times that Drive is called on the Car class, a metric that is not important to users of the class; consider, for example, that when you are buying a car, you do not ask -the seller on how many drives the car has been taken). +the seller on how many drives the car has been taken. Because there is little need for users of the class to change this property, we can hide the property from Get-Member and automatic completion results by @@ -79,17 +79,17 @@ class Car ``` Now, create a new instance of the Car class, and save it in a variable, -$TestCar. +\$TestCar. ```powershell $TestCar = [Car]::new() ``` After you create the new instance, pipe the contents of the $TestCar variable -to Get\-Member. Observe that the rides property is not among the members -listed in the Get\-Member command results. +to Get-Member. Observe that the rides property is not among the members listed +in the Get-Member command results. -```powershell +```output PS C:\Windows\system32> $TestCar | Get-Member TypeName: Car @@ -104,13 +104,14 @@ ToString Method string ToString() Color Property string Color {get;set;} Distance Property int Distance {get;set;} ModelYear Property string ModelYear {get;set;} + ``` -Now, try running Get\-Member again, but this time, add the –Force parameter. +Now, try running Get-Member again, but this time, add the –Force parameter. Note that the results contain the hidden rides property, among other members that are hidden by default. -```powershell +```output PS C:\Windows\system32> $TestCar | Get-Member -Force TypeName: Car @@ -139,11 +140,15 @@ Color Property string Color {get;set;} Distance Property int Distance {get;set;} ModelYear Property string ModelYear {get;set;} rides Property int rides {get;set;} + ``` ## SEE ALSO -- [about_Classes](about_Classes.md) -- [about_Language_Keywords](about_Language_Keywords.md) -- [about_Wildcards](about_Wildcards.md) -- [Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) +[about_Classes](about_Classes.md) + +[about_Language_Keywords](about_Language_Keywords.md) + +[about_Wildcards](about_Wildcards.md) + +[Get-Member](../../Microsoft.PowerShell.Utility/Get-Member.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_logical_operators.md b/reference/6/Microsoft.PowerShell.Core/About/about_logical_operators.md index cafeedc3d3f5..7d9280a26f85 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_logical_operators.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_logical_operators.md @@ -1,5 +1,5 @@ --- -ms.date: 2017-06-09 +ms.date: 2018-01-03 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -14,13 +14,13 @@ Describes the operators that connect statements in PowerShell. ## LONG DESCRIPTION -The PowerShell logical operators connect expressions and statements, -allowing you to use a single expression to test for multiple conditions. +The PowerShell logical operators connect expressions and statements, allowing +you to use a single expression to test for multiple conditions. -For example, the following statement uses the and operator and the or -operator to connect three conditional statements. The statement is true -only when the value of $a is greater than the value of $b, and either $a or -$b is less than 20. +For example, the following statement uses the and operator and the or operator +to connect three conditional statements. The statement is true only when the +value of $a is greater than the value of $b, and either $a or $b is less than +20. ```powershell ($a -gt $b) -and (($a -lt 20) -or ($b -lt 20)) @@ -28,38 +28,43 @@ $b is less than 20. PowerShell supports the following logical operators. -|Operator|Description|Example| -|---|---|---| -|`-and`|Logical and. TRUE only when both statements are TRUE.|`(1 -eq 1) -and (1 -eq 2)`
`False`| -|`-or`|Logical or. TRUE when either or both statements are TRUE.|`(1 -eq 1) -or (1 -eq 2)`
`True`| -|`-xor`|Logical exclusive or. TRUE only when one of the statements is TRUE and the other is FALSE.|`(1 -eq 1) -xor (2 -eq 2)`
`False`| -|`-not`|Logical not. Negates the statement that follows it.|`-not (1 -eq 1)`
`False`| -|`!`|Logical not. Negates the statement that follows it. (Same as -not)|`!(1 -eq 1)`
`False`| +|Operator|Description |Example | +|--------|-----------------------------------|--------------------------| +|`-and` |Logical AND. TRUE when both |`(1 -eq 1) -and (1 -eq 2)`| +| |statements are TRUE. |`False` | +|`-or` |Logical OR. TRUE when either |`(1 -eq 1) -or (1 -eq 2)` | +| |statement is TRUE. |`True` | +|`-xor` |Logical EXCLUSIVE OR. TRUE when |`(1 -eq 1) -xor (2 -eq 2) | +| |only one statement is TRUE |`False` | +|`-not` |Logical not. Negates the statement |`-not (1 -eq 1)` | +| |that follows. |`False` | +|`!` |Same as `-not` |`!(1 -eq 1)` | +| | |`False` | Note: - The previous examples also use the equal to comparison operator `-eq`. For - more information, see about_Comparison_Operators. The examples also use - the Boolean values of integers. The integer 0 has a value of FALSE. All - other integers have a value of TRUE. +The previous examples also use the equal to comparison operator `-eq`. For +more information, see +[about_Comparison_Operators](about_Comparison_Operators.md). The examples also +use the Boolean values of integers. The integer 0 has a value of FALSE. All +other integers have a value of TRUE. - The syntax of the logical operators is as follows: +The syntax of the logical operators is as follows: -```powershell +``` {-AND | -OR | -XOR} {! | -NOT} ``` - Statements that use the logical operators return Boolean (TRUE or FALSE) - values. +Statements that use the logical operators return Boolean (TRUE or FALSE) +values. - The PowerShell logical operators evaluate only the statements required to - determine the truth value of the statement. If the left operand in a - statement that contains the and operator is FALSE, the right operand is - not evaluated. If the left operand in a statement that contains the or - statement is TRUE, the right operand is not evaluated. As a result, you - can use these statements in the same way that you would use the If - statement. +The PowerShell logical operators evaluate only the statements required to +determine the truth value of the statement. If the left operand in a statement +that contains the and operator is FALSE, the right operand is not evaluated. +If the left operand in a statement that contains the or statement is TRUE, the +right operand is not evaluated. As a result, you can use these statements in +the same way that you would use the If statement. ## SEE ALSO diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_psconsolehostreadline.md b/reference/6/Microsoft.PowerShell.Core/About/about_psconsolehostreadline.md new file mode 100644 index 000000000000..ea1e83939845 --- /dev/null +++ b/reference/6/Microsoft.PowerShell.Core/About/about_psconsolehostreadline.md @@ -0,0 +1,55 @@ +--- +ms.date: 2018-01-04 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_PSConsoleHostReadLine +--- + +# about_PSConsoleHostReadLine + +## SHORT DESCRIPTION + +Explains how to create a customize how PowerShell reads input at the console +prompt. + +## LONG DESCRIPTION + +Starting in Windows PowerShell V3, you can write a function named +PSConsoleHostReadLine that overrides the default way that console input is +processed. + +### EXAMPLES + +The following example launches Notepad and gets input from a text File that +the user creates: + +```powershell +function PSConsoleHostReadLine +{ + $inputFile = Join-Path $env:TEMP PSConsoleHostReadLine + Set-Content $inputFile "PS > " + + # Notepad opens. Enter your command in it, save the file, and then exit. + notepad $inputFile | Out-Null + $userInput = Get-Content $inputFile + $resultingCommand = $userInput.Replace("PS >", "") + $resultingCommand +} +``` + +### REMARKS + +By default, PowerShell reads input from the console in what is known as +"Cooked Mode" -- in which the Windows console subsystem handles all the +keypresses, F7 menus, and other input. When you press Enter or Tab, Windows +PowerShell gets the text that you have typed up to that point. There is no way +for it to know that you pressed Ctrl-R, Ctrl-A, Ctrl-E, or any other keys +before pressing Enter or Tab. In Windows PowerShell version 3, the +PSConsoleHostReadLine function solves this issue. When you define a function +named PSConsoleHostReadline in the Windows PowerShell console host, Windows +PowerShell calls that function instead of the "Cooked Mode" input mechanism. + +### SEE ALSO + +[about_Prompts](about_Prompts.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_psreadline.md b/reference/6/Microsoft.PowerShell.Core/About/about_psreadline.md new file mode 100644 index 000000000000..c21c0d7a2995 --- /dev/null +++ b/reference/6/Microsoft.PowerShell.Core/About/about_psreadline.md @@ -0,0 +1,674 @@ +--- +ms.date: 2018-01-04 +schema: 2.0.0 +locale: en-us +keywords: powershell,cmdlet +title: about_PSReadline +--- + +# about_PSReadline + +## SHORT DESCRIPTION + +PSReadline provides an improved command line editing experience in the +PowerShell console. + +## LONG DESCRIPTION + +PSReadline, introduced in PowerShell 5.0, provides a powerful command line +editing experience for the PowerShell console. It provides: + +- Syntax coloring of the command line +- A visual indication of syntax errors +- A better multi-line experience (both editing and history) +- Customizable key bindings +- Cmd and Emacs modes +- Many configuration options +- Bash style completion (optional in Cmd mode, default in Emacs mode) +- Emacs yank/kill ring +- PowerShell token based "word" movement and kill + +The following functions are available in the class +[PSConsoleUtilities.PSConsoleReadLine]: + +## Cursor movement + +- EndOfLine (Cmd: Emacs: or ) + + If the input has multiple lines, move to the end of the current line, or if + already at the end of the line, move to the end of the input. If the input + has a single line, move to the end of the input. + +- BeginningOfLine (Cmd: Emacs: or ) + + If the input has multiple lines, move to the start of the current line, or + if already at the start of the line, move to the start of the input. If the + input has a single line, move to the start of the input. + +- NextLine (Cmd: unbound Emacs: unbound) + + Move the cursor to the next line if the input has multiple lines. + +- PreviousLine (Cmd: unbound Emacs: unbound) + + Move the cursor to the previous line if the input has multiple lines. + +- ForwardChar (Cmd: Emacs: or ) + + Move the cursor one character to the right. This might move the cursor to + the next line of multi-line input. + +- BackwardChar (Cmd: Emacs: or ) + + Move the cursor one character to the left. This might move the cursor to the + previous line of multi-line input. + +- ForwardWord (Cmd: unbound Emacs: ) + + Move the cursor forward to the end of the current word, or if between words, + to the end of the next word. You can set word delimiter characters with: + + ```powershell + Set-PSReadlineOption -WordDelimiters + ``` + +- NextWord (Cmd: Emacs: unbound) + + Move the cursor forward to the start of the next word. You can set word + delimiter characters with: + + ```powershell + Set-PSReadlineOption -WordDelimiters + ``` + +- BackwardWord (Cmd: Emacs: ) + + Move the cursor back to the start of the current word, or if between words, + the start of the previous word. You can set word delimiter characters with: + + ```powershell + Set-PSReadlineOption -WordDelimiters + ``` + +- ShellForwardWord (Cmd: unbound Emacs: unbound) + + Like ForwardWord except word boundaries are defined by PowerShell token + boundaries. + +- ShellNextWord (Cmd: unbound Emacs: unbound) + + Like NextWord except word boundaries are defined by PowerShell token + boundaries. + +- ShellBackwardWord (Cmd: unbound Emacs: unbound) + + Like BackwardWord except word boundaries are defined by PowerShell token + boundaries. + +- GotoBrace (Cmd: Emacs: unbound) + + Go to the matching parenthesis, curly brace, or square bracket. + +- AddLine (Cmd: Emacs: ) + + The continuation prompt is displayed on the next line and PSReadline waits + for keys to edit the current input. This is useful to enter multi-line input + as a single command even when a single line is complete input by itself. + +## Basic editing + +- CancelLine (Cmd: unbound Emacs: unbound) + + Cancel all editing to the line, leave the line of input on the screen but + return from PSReadline without executing the input. + +- RevertLine (Cmd: Emacs: ) + + Reverts all of the input since the last input was accepted and run. This is + equivalent to using the Undo command until there is nothing left to undo. + +- BackwardDeleteChar (Cmd: Emacs: or ) + + Delete the character before the cursor. + +- DeleteChar (Cmd: Emacs: ) + + Delete the character under the cursor. + +- DeleteCharOrExit (Cmd: unbound Emacs: ) + + Like DeleteChar, unless the line is empty, in which case exit the process. + +- AcceptLine (Cmd: Emacs: or ) + + Attempt to execute the current input. If the current input is incomplete + (for example, there is a missing closing parenthesis, bracket, or quote), + then the continuation prompt is displayed on the next line, and PSReadline + waits for keys to edit the current input. + +- AcceptAndGetNext (Cmd: unbound Emacs: ) + + Like AcceptLine, but after the line completes, start editing the next line + from history. + +- ValidateAndAcceptLine (Cmd: unbound Emacs: unbound) + + Like AcceptLine but performs additional validation including: + + * Checks for additional parse errors + * Validates that command names are all found + * If you are running PowerShell 4.0 or newer, validates the parameters and + arguments + + If there are any errors, the error message is displayed and not accepted nor + added to the history unless you either correct the command line or execute + AcceptLine or ValidateAndAcceptLine again while the error message is + displayed. + +- BackwardDeleteLine (Cmd: Emacs: unbound) + + Delete the text from the start of the input to the cursor. + +- ForwardDeleteLine (Cmd: Emacs: unbound) + + Delete the text from the cursor to the end of the input. + +- SelectBackwardChar (Cmd: Emacs: ) + + Adjust the current selection to include the previous character. + +- SelectForwardChar (Cmd: Emacs: ) + + Adjust the current selection to include the next character. + +- SelectBackwardWord (Cmd: Emacs: ) + + Adjust the current selection to include the previous word. + +- SelectForwardWord (Cmd: unbound Emacs: ) + + Adjust the current selection to include the next word using ForwardWord. + +- SelectNextWord (Cmd: Emacs: unbound) + + Adjust the current selection to include the next word using NextWord. + +- SelectShellForwardWord (Cmd: unbound Emacs: unbound) + + Adjust the current selection to include the next word using + ShellForwardWord. + +- SelectShellNextWord (Cmd: unbound Emacs: unbound) + + Adjust the current selection to include the next word using ShellNextWord. + +- SelectShellBackwardWord (Cmd: unbound Emacs: unbound) + + Adjust the current selection to include the previous word using + ShellBackwardWord. + +- SelectBackwardsLine (Cmd: Emacs: ) + + Adjust the current selection to include from the cursor to the start of the + line. + +- SelectLine (Cmd: Emacs: ) + + Adjust the current selection to include from the cursor to the end of the + line. + +- SelectAll (Cmd: Emacs: unbound) + + Select the entire line. Moves the cursor to the end of the line. + +- SelfInsert (Cmd: , , ... Emacs: , , ...) + + Insert the key entered. + +- Redo (Cmd: Emacs: unbound) + + Redo an insertion or deletion that was undone by Undo. + +- Undo (Cmd: Emacs: ) + + Undo a previous insertion or deletion. + +## History + +- ClearHistory (Cmd: Alt+F7 Emacs: unbound) + + Clears history in PSReadline. This does not affect PowerShell + history. + +- PreviousHistory (Cmd: Emacs: or ) + + Replace the current input with the previous item from PSReadline history. + +- NextHistory (Cmd: Emacs: or ) + + Replace the current input with the next item from PSReadline history. + +- ForwardSearchHistory (Cmd: Emacs: ) + + Search forward from the current history line interactively. + +- ReverseSearchHistory (Cmd: Emacs: ) + + Search backward from the current history line interactively. + +- HistorySearchBackward (Cmd: Emacs: unbound) + + Replace the current input with the previous item from PSReadline history + that matches the characters between the start and the input and the cursor. + +- HistorySearchForward (Cmd: Emacs: unbound) + + Replace the current input with the next item from PSReadline history that + matches the characters between the start and the input and the cursor. + +- BeginningOfHistory (Cmd: unbound Emacs: ) + + Replace the current input with the last item from PSReadline history. + +- EndOfHistory (Cmd: unbound Emacs: >) + + Replace the current input with the last item in PSReadline history, which is + the possibly empty input that was entered before any history commands. + +## Tab Completion + +- TabCompleteNext (Cmd: Emacs: unbound) + + Attempt to complete the text surrounding the cursor with the next + available completion. + +- TabCompletePrevious (Cmd: Emacs: unbound) + + Attempt to complete the text surrounding the cursor with the next + previous completion. + +- Complete (Cmd: unbound Emacs: ) + + Attempt to perform completion on the text surrounding the cursor. If there + are multiple possible completions, the longest unambiguous prefix is used + for completion. If you are trying to complete the longest unambiguous + completion, a list of possible completions is displayed. + +- MenuComplete (Cmd: Emacs: ) + + Attempt to perform completion on the text surrounding the cursor. If there + are multiple possible completions, a list of possible completions is + displayed, and you can select the correct completion by using the arrow + keys, or Tab/Shift+Tab. Escape and Ctrl+G cancel the menu selection, and + revert the line to the state before invoking MenuComplete. + +- PossibleCompletions (Cmd: unbound Emacs: ) + + Display the list of possible completions. + +- SetMark (Cmd: unbound Emacs: ) + + Mark the current location of the cursor for use in a subsequent editing + command. + +- ExchangePointAndMark (Cmd: unbound Emacs: ) + + The cursor is placed at the location of the mark and the mark is moved + to the location of the cursor. + +## Kill/Yank + +Kill and Yank operate on a clipboard in the PSReadline module. There is a ring +buffer called the kill ring - killed text is added to the kill ring up and +yank will copy text from the most recent kill. YankPop cycles through items in +the kill ring. When the kill ring is full, new items replace the oldest items. +A kill operation that is immediately preceded by another kill operation +appends the previous kill, instead of adding a new item or replacing an item +in the kill ring. This is how you can cut a part of a line, for example, with +multiple KillWord operations, then yank them back elsewhere as a single yank. + +- KillLine (Cmd: unbound Emacs: ) + + Clear the input from the cursor to the end of the line. The cleared text is + placed in the kill ring. + +- BackwardKillLine (Cmd: unbound Emacs: or ) + + Clear the input from the start of the input to the cursor. The cleared text + is placed in the kill ring. + +- KillWord (Cmd: unbound Emacs: ) + + Clear the input from the cursor to the end of the current word. If the + cursor is between words, the input is cleared from the cursor to the end of + the next word. The cleared text is placed in the kill ring. + +- BackwardKillWord (Cmd: unbound Emacs: ) + + Clear the input from the start of the current word to the cursor. If the + cursor is between words, the input is cleared from the start of the previous + word to the cursor. The cleared text is placed in the kill ring. + +- ShellKillWord (Cmd: unbound Emacs: unbound) + + Like KillWord, except word boundaries are defined by PowerShell + token boundaries. + +- ShellBackwardKillWord (Cmd: unbound Emacs: unbound) + + Like BackwardKillWord, except word boundaries are defined by PowerShell + token boundaries. + +- UnixWordRubout (Cmd: unbound Emacs: ) + + Like BackwardKillWord, except word boundaries are defined by white space. + +- KillRegion (Cmd: unbound Emacs: unbound) + + Kill the text between the cursor and the mark. + +- Copy (Cmd: Emacs: unbound) + + Copy selected region to the system clipboard. If no region is selected, copy + the whole line. + +- CopyOrCancelLine (Cmd: Emacs: ) + + Either copy selected text to the clipboard, or if no text is selected, + cancel editing the line with CancelLine. + +- Cut (Cmd: Emacs: unbound) + + Delete selected region placing deleted text in the system clipboard. + +- Yank (Cmd: unbound Emacs: ) + + Add the most-recently killed text to the input. + +- YankPop (Cmd: unbound Emacs: ) + + If the previous operation was Yank or YankPop, replace the previously-yanked + text with the next killed text from the kill ring. + +- ClearKillRing (Cmd: unbound Emacs: unbound) + + The contents of the kill ring are cleared. + +- Paste (Cmd: Emacs: unbound) + + This is similar to Yank, but uses the system clipboard instead of the kill + ring. + +- YankLastArg (Cmd: Emacs: , ) + + Insert the last argument from the previous command in history. Repeated + operations replace the last inserted argument with the last argument from + the previous command (so Alt+. Alt+. will insert the last argument of the + second to last history line). + + With an argument, the first time YankLastArg behaves like YankNthArg. A + negative argument on subsequent YankLastArg calls changes the direction + while going through history. For example, if you press Alt+. one too many + times, you can type Alt+- Alt+. to reverse the direction. + + Arguments are based on PowerShell tokens. + +- YankNthArg (Cmd: unbound Emacs: ) + + Insert the first argument (not the command name) of the previous command in + history. + + With an argument, insert the nth argument where 0 is typically the command. + Negative arguments start from the end. + + Arguments are based on PowerShell tokens. + +## Miscellaneous + +- Abort (Cmd: unbound Emacs: ) + + Abort the current action; for example, stop interactive history search. Does + not cancel input like CancelLine. + +- CharacterSearch (Cmd: Emacs: ) + + Read a key and search forwards for that character. With an argument, search + forwards for the nth occurrence of that argument. With a negative argument, + searches backwards. + +- CharacterSearchBackward (Cmd: Emacs: ) + + Like CharacterSearch, but searches backwards. With a negative argument, + searches forwards. + +- ClearScreen (Cmd: Emacs: ) + + Clears the screen and displays the current prompt and input at the top of + the screen. + +- DigitArgument (Cmd: unbound Emacs: ,,) + + Used to pass numeric arguments to functions like CharacterSearch or + YankNthArg. Alt+- toggles the argument to be negative/non-negative. To enter + 80 '*' characters, you could type Alt+8 Alt+0 *. + +- CaptureScreen (Cmd: unbound Emacs: unbound) + + Copies selected lines to the clipboard in both text and RTF formats. Use + up/down arrow keys to the first line to select, then + Shift+UpArrow/Shift+DownArrow to select multiple lines. After selecting, + press Enter to copy the text. Escape/Ctrl+C/Ctrl+G cancel the operation, so + nothing is copied to the clipboard. + +- InvokePrompt (Cmd: unbound Emacs: unbound) + + Erases the current prompt and calls the prompt function to redisplay the + prompt. Useful for custom key handlers that change state, such as changing + the current directory. + +- WhatIsKey (Cmd: Emacs: ) + + Read a key or chord and display the key binding. + +- ShowKeyBindings (Cmd: Emacs: ) + + Show all of the currently-bound keys. + +- ScrollDisplayUp (Cmd: Emacs: ) + + Scroll the display up one screen. + +- ScrollDisplayUpLine (Cmd: Emacs: ) + + Scroll the display up one line. + +- ScrollDisplayDown (Cmd: Emacs: ) + + Scroll the display down one screen. + +- ScrollDisplayDownLine (Cmd: Emacs: ) + + Scroll the display down one line. + +- ScrollDisplayTop (Cmd: unbound Emacs: ) + + Scroll the display to the top. + +- ScrollDisplayToCursor (Cmd: unbound Emacs: ) + + Scroll the display to the cursor. + +## Custom Key Bindings + +PSReadline supports custom key bindings using the cmdlet +Set-PSReadlineKeyHandler. Most custom key bindings call one of the above +functions, for example: + +```powershell +Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward +``` + +You can bind a ScriptBlock to a key. The ScriptBlock can do virtually anything +you want. Some useful examples include: + +* edit the command line +* opening a new window (e.g. help) +* change directories without changing the command line + +The ScriptBlock is passed two arguments: + +* $key - A [ConsoleKeyInfo] that is the key that triggered the custom binding. + If you bind the same ScriptBlock to multiple keys and need to perform + different actions depending on the key, you can check $key. Many custom + bindings ignore this argument. +* $arg - An arbitrary argument. Most often, this would be an integer argument + that the user passes from the key bindings DigitArgument. If your binding + doesn't accept arguments, it's reasonable to ignore this argument. + +Let's take a look at an example that adds a command line to history without +executing it. This is useful when you realize you forgot to do something, but +don't want to re-enter the command line you've already entered. + +```powershell +Set-PSReadlineKeyHandler -Key Alt+w ` + -BriefDescription SaveInHistory ` + -LongDescription "Save current line in history but do not execute" ` + -ScriptBlock { + param($key, $arg) # The arguments are ignored in this example + + # GetBufferState gives us the command line (with the cursor position) + $line = $null + $cursor = $null + [PSConsoleUtilities.PSConsoleReadLine]::GetBufferState([ref]$line, + [ref]$cursor) + + # AddToHistory saves the line in history, but does not execute the line. + [PSConsoleUtilities.PSConsoleReadLine]::AddToHistory($line) + + # RevertLine is like pressing Escape. + [PSConsoleUtilities.PSConsoleReadLine]::RevertLine() +} +``` + +You can see many more examples in the file SamplePSReadlineProfile.ps1 which +is installed in the PSReadline module folder. + +Most key bindings will want to take advantage of some helper functions for +editing the command line those APIs are documented in the next section. + +## Custom Key Binding Support APIs + +The following functions are public in PSConsoleUtilities.PSConsoleReadline, +but cannot be directly bound to a key. Most are useful in custom key bindings. + +- void AddToHistory(string command) + + Add a command line to history without executing it. + +- void ClearKillRing() + + Clear the kill ring. This is mostly used for testing. + +- void Delete(int start, int length) + + Delete length characters from start. This operation supports undo and redo. + +void Ding() + + Perform the Ding action based on the user’s preference. + +- void GetBufferState([ref] string input, [ref] int cursor) +- void GetBufferState([ref] Ast ast, [ref] Token[] tokens, [ref] ParseError[] + parseErrors, [ref] int cursor) + + These two functions retrieve useful information about the current state of + the input buffer. The first is more commonly used for simple cases. The + second is used if your binding is doing something more advanced with the + Ast. + +- IEnumerable[PSConsoleUtilities.KeyHandler] GetKeyHandlers(bool includeBound, + bool includeUnbound) + + This function is used by Get-PSReadlineKeyHandler and probably isn't useful + in a custom key binding. + +- PSConsoleUtilities.PSConsoleReadlineOptions GetOptions() + + This function is used by Get-PSReadlineOption and probably isn't too useful + in a custom key binding. + +- void GetSelectionState([ref] int start, [ref] int length) + + If there is no selection on the command line, -1 is returned in both start + and length. If there is a selection on the command line, the start and + length of the selection are returned. + +- void Insert(char c) +- void Insert(string s) + + Insert a character or string at the cursor. This operation supports undo and + redo. + +- string ReadLine(runspace remoteRunspace, + System.Management.Automation.EngineIntrinsics engineIntrinsics) + + This is the main entry point to PSReadline. It does not support recursion, + so is not useful in a custom key binding. + +- void RemoveKeyHandler(string[] key) + + This function is used by Remove-PSReadlineKeyHandler and probably isn't too + useful in a custom key binding. + +- void Replace(int start, int length, string replacement) + + Replace some of the input. This operation supports undo and redo. This is + preferred over Delete followed by Insert because it is treated as a single + action for undo. + +- void SetCursorPosition(int cursor) + + Move the cursor to the given offset. Cursor movement is not tracked for + undo. + +- void SetOptions(PSConsoleUtilities.SetPSReadlineOption options) + + This function is a helper method used by the cmdlet Set-PSReadlineOption, + but might be useful to a custom key binding that wants to temporarily change + a setting. + +- bool TryGetArgAsInt(System.Object arg, [ref] int numericArg, + int defaultNumericArg) + + This helper method is used for custom bindings that honor DigitArgument. A + typical call looks like: + + ```powershell + [int]$numericArg = 0 + [PSConsoleUtilities.PSConsoleReadLine]::TryGetArgAsInt($arg, + [ref]$numericArg, 1) + ``` +## POWERSHELL COMPATIBILITY + +PSReadline requires PowerShell 3.0 or newer, and the console host. It +does not work in PowerShell ISE. + +## FEEDBACK AND CONTRIBUTING TO PSREADLINE + +Feel free to submit a pull request or submit feedback on the PSReadline +GitHub page (https://github.com/lzybkr/PSReadLine). + +## SEE ALSO + +PSReadline is heavily influenced by the GNU Readline library: +http://tiswww.case.edu/php/chet/readline/rltop.html + +[Get-PSReadlineKeyHandler](../../PSReadline/Get-PSReadlineKeyHandler.md) + +[Get-PSReadlineOption](../../PSReadline/Get-PSReadlineOption.md) + +[Remove-PSReadlineKeyHandler](../../PSReadline/Remove-PSReadlineKeyHandler.md) + +[Set-PSReadlineKeyHandler](../../PSReadline/Set-PSReadlineKeyHandler.md) + +[Set-PSReadlineOption](../../PSReadline/Set-PSReadlineOption.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_pwsh.md b/reference/6/Microsoft.PowerShell.Core/About/about_pwsh.md index 593cc726bc25..1e766879d561 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_pwsh.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_pwsh.md @@ -7,20 +7,19 @@ title: about_PowerShell_exe --- # About pwsh -## about_pwsh +## SHORT DESCRIPTION -# SHORT DESCRIPTION - -Explains how to use the pwsh command-line tool. Displays -the syntax and describes the command-line switches. +Explains how to use the pwsh command-line tool. Displays the syntax and +describes the command-line switches. pwsh starts a PowerShell session. -# LONG DESCRIPTION +## LONG DESCRIPTION -# SYNTAX +## SYNTAX +``` pwsh[.exe] [-Version] [-EncodedCommand ] @@ -36,109 +35,116 @@ pwsh[.exe] [-Command { - | [-args ] | [] } ] pwsh[.exe] -Help | -? | /? +``` + +### PARAMETERS + +#### -Version + +Displays the version of PowerShell. Additional parameters are ignored. + +#### -EncodedCommand + +Accepts a base-64-encoded string version of a command. Use this parameter to +submit commands to PowerShell that require complex quotation marks or curly +braces. + +#### -ExecutionPolicy + +Sets the default execution policy for the current session and saves it in the +$env:PSExecutionPolicyPreference environment variable. This parameter does not +change the PowerShell execution policy that is set in the registry. + +#### -File [] + +Runs the specified script in the local scope ("dot-sourced"), so that the +functions and variables that the script creates are available in the current +session. Enter the script file path and any parameters. File must be the last +parameter in the command, because all characters typed after the File +parameter name are interpreted as the script file path followed by the script +parameters. + +You can include the parameters of a script, and parameter values, in the value +of the File parameter. For example: -File .\\Get-Script.ps1 -Domain Central + +Typically, the switch parameters of a script are either included or omitted. +For example, the following command uses the All parameter of the +Get-Script.ps1 script file: -File .\\Get-Script.ps1 -All + +In rare cases, you might need to provide a Boolean value for a switch +parameter. To provide a Boolean value for a switch parameter in the value of +the File parameter, enclose the parameter name and value in curly braces, such +as the following: -File .\\Get-Script.ps1 {-All:$False}. + +#### -InputFormat {Text | XML} + +Describes the format of data sent to PowerShell. Valid values are "Text" (text +strings) or "XML" (serialized CLIXML format). + +#### -NoExit -# PARAMETERS - --Version -Displays the version of PowerShell. Additional parameters -are ignored. - --EncodedCommand -Accepts a base-64-encoded string version of a command. -Use this parameter to submit commands to PowerShell -that require complex quotation marks or curly braces. - --ExecutionPolicy -Sets the default execution policy for the current session -and saves it in the $env:PSExecutionPolicyPreference environment -variable. This parameter does not change the PowerShell -execution policy that is set in the registry. - --File [] -Runs the specified script in the local scope ("dot-sourced"), -so that the functions and variables that the script creates -are available in the current session. Enter the script file -path and any parameters. File must be the last parameter in -the command, because all characters typed after the File -parameter name are interpreted as the script file path followed -by the script parameters. - -You can include the parameters of a script, and parameter -values, in the value of the File parameter. For example: --File .\Get-Script.ps1 -Domain Central - -Typically, the switch parameters of a script are either -included or omitted. For example, the following command -uses the All parameter of the Get-Script.ps1 script file: --File .\Get-Script.ps1 -All - -In rare cases, you might need to provide a Boolean value -for a switch parameter. To provide a Boolean value for a -switch parameter in the value of the File parameter, -enclose the parameter name and value in curly braces, -such as the following: --File .\Get-Script.ps1 {-All:$False}. - --InputFormat {Text | XML} -Describes the format of data sent to PowerShell. Valid -values are "Text" (text strings) or "XML" (serialized CLIXML format). - --NoExit Does not exit after running startup commands. --NoLogo +#### -NoLogo + Hides the copyright banner at startup. --NonInteractive +#### -NonInteractive + Does not present an interactive prompt to the user. --NoProfile +#### -NoProfile + Does not load the PowerShell profile. --OutputFormat {Text | XML} -Determines how output from PowerShell is formatted. -Valid values are "Text" (text strings) or "XML" (serialized -CLIXML format). +#### -OutputFormat {Text | XML} + +Determines how output from PowerShell is formatted. Valid values are "Text" +(text strings) or "XML" (serialized CLIXML format). --WindowStyle -Sets the window style for the session. Valid values are Normal, -Minimized, Maximized and Hidden. +#### -WindowStyle --Command -Executes the specified commands (and any parameters) as though -they were typed at the PowerShell command prompt, and -then exits, unless the NoExit parameter is specified. +Sets the window style for the session. Valid values are Normal, Minimized, +Maximized and Hidden. -The value of Command can be "-", a string. or a script block. If -the value of Command is "-", the command text is read from standard -input. +#### -Command -Script blocks must be enclosed in braces ({}). You can specify a -script block only when running pwsh in PowerShell. -The results of the script are returned to the parent shell as -deserialized XML objects, not live objects. +Executes the specified commands (and any parameters) as though they were typed +at the PowerShell command prompt, and then exits, unless the NoExit parameter +is specified. -If the value of Command is a string, Command must be the last -parameter in the command , because any characters typed after -the command are interpreted as the command arguments. +The value of Command can be "-", a string. or a script block. If the value of +Command is "-", the command text is read from standard input. -To write a string that runs a PowerShell command, use the -format: +Script blocks must be enclosed in braces ({}). You can specify a script block +only when running pwsh in PowerShell. The results of the script are returned +to the parent shell as deserialized XML objects, not live objects. + +If the value of Command is a string, Command must be the last parameter in the +command , because any characters typed after the command are interpreted as +the command arguments. + +To write a string that runs a PowerShell command, use the format: + +``` "& {}" -where the quotation marks indicate a string and the invoke operator -(&) causes the command to be executed. +``` --Help, -?, /? -Displays help for pwsh. If you are typing a pwsh -command in PowerShell, prepend the command parameters with a -hyphen (-), not a forward slash (/). You can use either a hyphen or -forward slash in Cmd.exe. +where the quotation marks indicate a string and the invoke operator (&) causes +the command to be executed. -# EXAMPLES +#### -Help, -?, /? +Displays help for pwsh. If you are typing a pwsh command in PowerShell, +prepend the command parameters with a hyphen (-), not a forward slash (/). You +can use either a hyphen or forward slash in Cmd.exe. + +## EXAMPLES + +```powershell pwsh -Version pwsh -Command {Get-Command -Name Get-Command} pwsh -Command "& {Get-Command -Name Get-Command}" - +```