diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Functions.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Functions.md index a90c198cdd4a..9425374767e4 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Functions.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Functions.md @@ -29,7 +29,10 @@ positional, switch, or dynamic parameters. Function parameters can be read from the command line or from the pipeline. Functions can return values that can be displayed, assigned to variables, or -passed to other functions or cmdlets. +passed to other functions or cmdlets. You can also specify a return value using +the `return` keyword. The `return` keyword does not affect or suppress other +output returned from your function. However, the `return` keyword exits the +function at that line. For more information, see [about_Return](about_Return.md). The function's statement list can contain different types of statement lists with the keywords `Begin`, `Process`, and `End`. These statement lists diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Return.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Return.md index 2ec83cbd52e3..f6139e7bb186 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Return.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Return.md @@ -7,73 +7,83 @@ title: about_Return --- # About Return -## SHORT DESCRIPTION +## Short description Exits the current scope, which can be a function, script, or script block. -## LONG DESCRIPTION +## 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. +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. +`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. +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 +### 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 +The `return` keyword can appear alone, or it can be followed by a value or expression, as follows: -``` +```powershell return return $a return (2 + $a) ``` +### Examples -### EXAMPLES +The following example uses the `return` keyword to exit a function at a +specific point if a conditional is met. Odd numbers are not multiplied +because the return statement exits before that statement can execute. -The following example uses the Return keyword to exit a function at a specific -point if a conditional is met: - -``` -function ScreenPassword($instance) +```powershell +function MultiplyEven { - if (!($instance.screensaversecure)) {return $instance.name} - + param($number) + + if ($number % 2) { return "$number is not even" } + $number * 2 } -foreach ($a in @(get-wmiobject win32_desktop)) { ScreenPassword($a) } +1..10 | ForEach-Object {MultiplyEven -Number $_} ``` -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. +```output +1 is not even +4 +3 is not even +8 +5 is not even +12 +7 is not even +16 +9 is not even +20 +``` -In PowerShell, values can be returned even if the Return keyword is not used. +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: +statements return the value of the `$a` variable: -``` +```powershell $a return ``` -The following statement also returns the value of $a: +The following statement also returns the value of `$a`: -``` +```powershell return $a ``` @@ -88,28 +98,104 @@ function calculation { $value += 73 return $value } -``` - -Running this function and assigning the result to a variable has the following -effect: -```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: +it is assigned to the `$a` variable, as in the following example: -```output +``` 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. +by the function and assigned to the `$a` variable. + +### Return values and the Pipeline + +When you return a collection from your script block or function, PowerShell +automatically unrolls the members and passes them one at a time through the +pipeline. This is due to PowerShell's one-at-a-time processing. For more +information, see [about_pipelines](about_pipelines.md). + +This concept is illustrated by the following sample function that returns an +array of numbers. The output from the function is piped to the `Measure-Object` +cmdlet which counts the number of objects in the pipeline. + +```powershell +function Test-Return +{ + $array = 1,2,3 + return $array +} +Test-Return | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` -## SEE ALSO +To force a script block or function to return collection as a single +object to the pipeline, use one of the following two methods: + +- Unary array expression + + Utilizing a unary expression you can send your return value down the pipeline + as a single object as illustrated by the following example. + + ```powershell + function Test-Return + { + $array = 1,2,3 + return (, $array) + } + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + +- `Write-Output` with **NoEnumerate** parameter. + + You can also use the `Write-Output` cmdlet with the **NoEnumerate** + parameter. The example below uses the `Measure-Object` cmdlet to count the + objects sent to the pipeline from the sample function by the `return` + keyword. + + ```powershell + function Test-Return + { + $array = 1, 2, 3 + return Write-Output -NoEnumerate $array + } + + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + +## See also [about_Language_Keywords](about_Language_Keywords.md) @@ -117,4 +203,4 @@ by the function and assigned to the \$a variable. [about_Scopes](about_Scopes.md) -[about_Script_Blocks](about_Script_Blocks.md) \ No newline at end of file +[about_Script_Blocks](about_Script_Blocks.md) diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md index 4d83aedaa530..8b48ed60b8e3 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md @@ -28,6 +28,11 @@ the following syntax: A script block returns the output of all the commands in the script block, either as a single object or as an array. +You can also specify a return value using the `return` keyword. The `return` +keyword does not affect or suppress other output returned from your script +block. However, the `return` keyword exits the script block at that line. For +more information, see [about_Return](about_Return.md). + Like functions, a script block can include parameters. Use the Param keyword to assign named parameters, as shown in the following syntax: diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_Switch.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_Switch.md index 7e42ec071000..21140924c54f 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_Switch.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_Switch.md @@ -166,13 +166,11 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one |Parameter |Description | |------------|----------------------------------------------------------| -|**Wildcard**|Indicates that the condition is a wildcard string. If you | -| |you use **Wildcard**, **Regex** and **Exact** are ignored. | -| |Also, if the match clause is not a string, the parameter is| +|**Wildcard**|Indicates that the condition is a wildcard string. | +| |If the match clause is not a string, the parameter is| | |ignored. | |**Exact** |Indicates that the match clause, if it is a string, must | -| |match exactly. **Regex** and **Wildcard** are ignored. | -| |Also, if the match clause is not a string, this parameter | +| |match exactly. If the match clause is not a string, this parameter | | |is ignored. | |**CaseSensitive**|Performs a case-sensitive match. If the match clause is not| | |a string, this parameter is ignored. | @@ -181,9 +179,15 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one | |used. Each line of the file is read and evaluated by the | | |`Switch` statement. | |**Regex** |Performs regular expression matching of the value to the | -| |condition. **Wildcard** and **Exact** are ignored. Also, if the| +| |condition. If the| | |match clause is not a string, this parameter is ignored. | +> [!NOTE] +> When specifying conflicting values, like **Regex** and **Wildcard**, the last +> parameter specified takes precedence, and all conflicting parameters are ignored. +> Multiple instances of parameters are also permitted. However, only the +> last parameter used is effective. + In this example, there is no matching case so there is no output. ```powershell @@ -197,6 +201,27 @@ switch ("fourteen") } ``` +By adding the `Default` clause, you can perform an action when no other +conditions succeed. + +```powershell +switch ("fourteen") +{ + 1 {"It is one."; Break} + 2 {"It is two."; Break} + 3 {"It is three."; Break} + 4 {"It is four."; Break} + "fo*" {"That's too many."} + Default { + "No matches" + } +} +``` + +```Output +No matches +``` + For the word "fourteen" to match a case you must use the `-Wildcard` or `-Regex` parameter. @@ -231,28 +256,67 @@ switch -Regex ($target) user@contoso.com is an email address ``` -Multiple instances of **Regex**, **Wildcard**, or **Exact** are permitted. -However, only the last parameter used is effective. +A `Switch` statement condition may be either: + +- An expression whose value is compared to the input value +- A script block which should return `$true` if a condition is met. The + script block receives the current object to compare in the `$_` + automatic variable and is evaluated in its own scope. + +The action for each condition is independent of the actions in other +conditions. + +The following example demonstrates the use of script blocks as `Switch` +statement conditions. + +```powershell +switch ("Test") +{ + {$_ -is [String]} { + "Found a string" + } + "Test" { + "This executes as well" + } +} +``` + +```Output +Found a string +This executes as well +``` If the value matches multiple conditions, the action for each condition is executed. To change this behavior, use the `Break` or `Continue` keywords. -The Break keyword stops processing and exits the Switch statement. +The `Break` keyword stops processing and exits the `Switch` statement. The `Continue` keyword stops processing the current value, but continues processing any subsequent values. -If the condition is an expression or a script block, it is evaluated just -before it is compared to the value. The value is assigned to the `$_` -automatic variable and is available in the expression. The match succeeds -if the expression is true or matches the value. The expression is evaluated -in its own scope. +The following example processes an array of numbers and displays if they are +odd or even. Negative numbers are skipped with the `Continue` keyword. If a +non-number is encountered, execution is terminated with the `Break` keyword. -The `Default` keyword specifies a condition that is evaluated only when no -other conditions match the value. +```powershell +switch (1,4,-1,3,"Hello",2,1) +{ + {$_ -lt 0} { Continue } + {$_ -isnot [Int32]} { Break } + {$_ % 2} { + "$_ is Odd" + } + {-not ($_ % 2)} { + "$_ is Even" + } +} +``` -The action for each condition is independent of the actions in other -conditions. +```Output +1 is Odd +4 is Even +3 is Odd +``` ## SEE ALSO diff --git a/reference/3.0/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/3.0/Microsoft.PowerShell.Core/About/about_pipelines.md index 695d1b545b34..793c3f98cda3 100644 --- a/reference/3.0/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/3.0/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -49,7 +49,7 @@ Get-Process notepad | Stop-Process The first command uses the `Get-Process` cmdlet to get an object representing the Notepad process. It uses a pipeline operator (`|`) to send the process object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice -that the `Stop-Process` command does not have a Name or ID parameter to +that the `Stop-Process` command does not have a **Name** or **ID** parameter to specify the process, because the specified process is submitted through the pipeline. @@ -120,8 +120,8 @@ tmp3.txt 114000 ## Using Pipelines The PowerShell cmdlets were designed to be used in pipelines. For example, you -can usually pipe the results of a Get cmdlet to an action cmdlet (such as a -Set, Start, Stop, or Rename cmdlet) for the same noun. +can usually pipe the results of a **Get** cmdlet to an action cmdlet (such as a +**Set**, **Start**, **Stop**, or **Rename** cmdlet) for the same noun. For example, you can pipe any service from the `Get-Service` cmdlet to the `Start-Service` or `Stop-Service` cmdlets (although disabled services cannot @@ -136,12 +136,12 @@ Get-Service wmi | Start-Service ``` The cmdlets that get and set objects of the PowerShell providers, such as the -Item and ItemProperty cmdlets, are also designed to be used in pipelines. +**Item** and **ItemProperty** cmdlets, are also designed to be used in pipelines. For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. -This command adds a new registry entry, NoOfEmployees, with a value of 8124, -to the MyCompany registry key. +This command adds a new registry entry, **NoOfEmployees**, with a value of 8124, +to the **MyCompany** registry key. For example, @@ -168,7 +168,7 @@ Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and `Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out cmdlets, such as `Out-Printer`. -For example, you can pipe the Winlogon process to the `Format-List` cmdlet to +For example, you can pipe the "Winlogon" process to the `Format-List` cmdlet to display all of the properties of the process in a list. For example, @@ -190,7 +190,7 @@ To do so, the PowerShell "parameter binding" component, which associates input objects with cmdlet parameters, tries to find a parameter that meets the following criteria: -- The parameter must accept input from a pipeline (not all do) +- The parameter must accept input from a pipeline (not all do). - The parameter must accept the type of object being sent or a type that the object can be converted to. - The parameter must not already be used in the command. @@ -224,7 +224,7 @@ Get-Service | Format-Table -Property name, dependentservices ``` is much like saving the service objects in a variable and using the -InputObject parameter of `Format-Table` to submit the service object. +**InputObject** parameter of `Format-Table` to submit the service object. For example, @@ -253,8 +253,45 @@ cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the process objects, and their properties and methods. -NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the -same type, it displays only one object type. +PowerShell automatically enumerates any type that implements the `IEnumerable` +interface and sends the members through the pipeline one at a time. The +exception is `[hashtable]`, which requires a call to the `GetEnumerator()` +method. + +In the example below, an array and a hashtable are piped to the `Measure-Object` +cmdlet, which counts the number of objects received from the pipeline. The array +has multiple members, and the hashtable has multiple key-value pairs. Only the +array is enumerated one at a time. + +```powershell +@(1,2,3) | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +```powershell +@{"One"=1;"Two"=2} | Measure-Object +``` + +```Output +Count : 1 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +> [!NOTE] +> `Get-Member` eliminates duplicates, so if the objects are all of the +> same type, it displays only one object type. In this case, `Get-Member` displays the properties and methods of each process object, that is, a System.Diagnostics.Process object. @@ -276,10 +313,10 @@ NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then -`Get-Member` receives an array of System.Diagnostics.Process objects as a +However, if you use the **InputObject** parameter of `Get-Member`, then +`Get-Member` receives an array of **System.Diagnostics.Process** objects as a single unit, and it displays the properties of an array of objects. (Note the -array symbol ([]) after the System.Object type name.) +array symbol (`[]`) after the **System.Object** type name.) For example, @@ -299,8 +336,8 @@ Clone Method System.Object Clone() ``` This result might not be what you intended, but after you understand it, you -can use it. For example, an array of process objects has a Count property that -you can use to count the number of processes on the computer. +can use it. For example, an array of process objects has a **Count** property +that you can use to count the number of processes on the computer. For example, @@ -372,7 +409,7 @@ This means that you can send objects (PsObjects) through the pipeline to the Cmdlets parameters can accept pipeline input in one of two different ways: -- ByValue: Parameters that accept input "by value" can accept piped objects +- **ByValue**: Parameters that accept input "by value" can accept piped objects that have the same .NET type as their parameter value or objects that can be converted to that type. @@ -380,7 +417,7 @@ Cmdlets parameters can accept pipeline input in one of two different ways: value. It can accept string objects or objects that can be converted to strings. -- ByPropertyName: Parameters that accept input "by property name" can accept +- **ByPropertyName**: Parameters that accept input "by property name" can accept piped objects only when a property of the object has the same name as the parameter. @@ -428,7 +465,7 @@ To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of PowerShell. The following command traces the Parameter Binding component while the command is processing. It uses the `-PSHost` parameter to display the results at the console and the `-filepath` command to send them to -the debug.txt file for later reference. +the `debug.txt` file for later reference. For example, @@ -486,7 +523,7 @@ Get-Help Move-ItemProperty -Parameter Destination ``` The results show that **Destination** takes pipeline input only "by property -name". That is, the piped object must have a property named Destination. +name". That is, the piped object must have a property named **Destination**. ``` -Destination @@ -509,8 +546,8 @@ For example, Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` -The output shows that the item is a Microsoft.Win32.RegistryKey that does not -have a Destination property. That explains why the command failed. +The output shows that the item is a **Microsoft.Win32.RegistryKey** that does +not have a **Destination** property. That explains why the command failed. To fix the command, we must specify the destination in the `Move-ItemProperty` cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name @@ -532,7 +569,8 @@ For example, Get-ItemProperty HKLM:\software\mycompany\sales ``` -The results show that the Product registry entry was moved to the Sales key. +The results show that the **Product** registry entry was moved to the **Sales** +key. ```Output PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa @@ -553,4 +591,4 @@ Product : 18 [about_command_syntax](about_command_syntax.md) -[about_foreach](about_foreach.md) \ No newline at end of file +[about_foreach](about_foreach.md) diff --git a/reference/3.0/Microsoft.PowerShell.Management/Copy-Item.md b/reference/3.0/Microsoft.PowerShell.Management/Copy-Item.md index cc909ac97974..0562bd721964 100644 --- a/reference/3.0/Microsoft.PowerShell.Management/Copy-Item.md +++ b/reference/3.0/Microsoft.PowerShell.Management/Copy-Item.md @@ -1,5 +1,5 @@ --- -ms.date: 10/18/2018 +ms.date: 5/30/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -36,9 +36,9 @@ Copy-Item -LiteralPath [[-Destination] ] [-Container] [-Force The `Copy-Item` cmdlet copies an item from one location to another location in the same namespace. For instance, it can copy a file to a folder, but it cannot copy a file to a certificate drive. -This cmdlet does not cut or delete the items being copied. -The particular items that the cmdlet can copy depend on the PowerShell provider that exposes the item. -For instance, it can copy files and directories in a file system drive and registry keys and entries in the registry drive. +This cmdlet does not cut or delete the items being copied. The particular items that the cmdlet can +copy depend on the PowerShell provider that exposes the item. For instance, it can copy files and +directories in a file system drive and registry keys and entries in the registry drive. This cmdlet can copy and rename items in the same command. To rename an item, enter the new name in the value of the **Destination** parameter. @@ -48,7 +48,7 @@ To rename an item and not copy it, use the `Rename-Item` cmdlet. ### Example 1: Copy a file to the specified directory -This command copies the "mar1604.log.txt" file to the "C:\Presentation" directory. +This command copies the `mar1604.log.txt` file to the `C:\Presentation` directory. The command does not delete the original file. ```powershell @@ -58,17 +58,19 @@ Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination "C:\Presentation" ### Example 2: Copy the contents of a directory to another directory This command copies the entire contents of the "Logfiles" directory into the "Drawings" directory. -If the "LogFiles" directory contains files in subdirectories, those subdirectories are copied with their file trees intact. -The **Container** parameter is set to "true" by default. -This preserves the directory structure. ```powershell Copy-Item "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse ``` +If the "LogFiles" directory contains files in subdirectories, those subdirectories are copied with +their file trees intact. The **Container** parameter is set to "true" by default. + +This preserves the directory structure. + ### Example 3: Copy the contents of a directory to another directory and create the destination directory if it does not exist -This command copies the contents of the "C:\Logfiles" directory to the "C:\Drawings\Logs" directory. +This command copies the contents of the `C:\Logfiles` directory to the `C:\Drawings\Logs` directory. It creates the "\Logs" subdirectory if it does not already exist. ```powershell @@ -77,8 +79,10 @@ Copy-Item C:\Logfiles -Destination C:\Drawings\Logs -Recurse ### Example 4: Copy a file to the specified directory and rename the file -This command uses the `Copy-Item` cmdlet to copy the "Get-Widget.ps1" script from the "\\\\Server01\Share" directory to the "\\\\Server12\ScriptArchive" directory. -As part of the copy operation, the command also changes the item name from "Get-Widget.ps1" to "Get-Widget.ps1.txt", so it can be attached to email messages. +This command uses the `Copy-Item` cmdlet to copy the `Get-Widget.ps1` script from the +`\\Server01\Share` directory to the `\\Server12\ScriptArchive` directory. +As part of the copy operation, the command also changes the item name from `Get-Widget.ps1` to +`Get-Widget.ps1.txt`, so it can be attached to email messages. ```powershell Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchive\Get-Widget.ps1.txt" @@ -86,16 +90,28 @@ Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchi ## PARAMETERS -### -Credential +### -Container -Specifies a user account that has permission to perform this action. -The default is the current user. +Indicates that this cmdlet preserves container objects during the copy operation. -Type a user name, such as "User01" or "Domain01\User01", or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. -If you type a user name, you are prompted for a password. +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: True +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Credential -> [!WARNING] -> This parameter is not supported by any providers installed with Windows PowerShell. +> [!NOTE] +> This parameter is not supported by any providers installed with PowerShell. +> To impersonate another user, or elevate your credentials when running this cmdlet, +> use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: PSCredential @@ -112,7 +128,9 @@ Accept wildcard characters: False ### -Destination Specifies the path to the new location. -To rename a copied item, include the new name in the value. +The default is the current directory. + +To rename the item being copied, specify a new name in the value of the **Destination** parameter. ```yaml Type: String @@ -128,10 +146,11 @@ Accept wildcard characters: False ### -Exclude -Specifies, as a string array, an item or items that this cmdlet excludes from the operation. -The value of this parameter qualifies the **Path** parameter. -Enter a path element or pattern, such as "*.txt". -Wildcard characters are permitted. +Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value +of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as +`*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the +command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character +specifies the contents of the `C:\Windows` directory. ```yaml Type: String[] @@ -147,11 +166,11 @@ Accept wildcard characters: True ### -Filter -Specifies a filter in the format or language of the provider. -The value of this parameter qualifies the **Path** parameter. - -The syntax of the filter, including the use of wildcard characters, depends on the provider. -Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. +Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) +provider is the only installed PowerShell provider that supports the use of filters. You can find +the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). +Filters are more efficient than other parameters, because the provider applies them when the cmdlet +gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: String @@ -167,7 +186,8 @@ Accept wildcard characters: True ### -Force -Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a read-only file or alias. +Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a +read-only file or alias. ```yaml Type: SwitchParameter @@ -176,17 +196,18 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include -Specifies, as a string array, an item or items that this cmdlet includes in the operation. -The value of this parameter qualifies the **Path** parameter. -Enter a path element or pattern, such as "*.txt". -Wildcard characters are permitted. +Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value +of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as +`"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the +command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character +specifies the contents of the `C:\Windows` directory. ```yaml Type: String[] @@ -197,16 +218,17 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -LiteralPath -Specifies a path to the item. -Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it is typed. -No characters are interpreted as wildcards. -If the path includes escape characters, enclose it in single quotation marks. -Single quotation marks tell PowerShell not to interpret any characters as escape sequences. +Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is +typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose +it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters +as escape sequences. + +For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: String[] @@ -232,7 +254,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -240,6 +262,7 @@ Accept wildcard characters: False ### -Path Specifies, as a string array, the path to the items to copy. +Wildcard characters are permitted. ```yaml Type: String[] @@ -250,7 +273,7 @@ Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -Recurse @@ -264,7 +287,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Functions.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Functions.md index a90c198cdd4a..9425374767e4 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Functions.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Functions.md @@ -29,7 +29,10 @@ positional, switch, or dynamic parameters. Function parameters can be read from the command line or from the pipeline. Functions can return values that can be displayed, assigned to variables, or -passed to other functions or cmdlets. +passed to other functions or cmdlets. You can also specify a return value using +the `return` keyword. The `return` keyword does not affect or suppress other +output returned from your function. However, the `return` keyword exits the +function at that line. For more information, see [about_Return](about_Return.md). The function's statement list can contain different types of statement lists with the keywords `Begin`, `Process`, and `End`. These statement lists diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Return.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Return.md index 15fd437fe0a9..b14d6fa46044 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Return.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Return.md @@ -5,76 +5,85 @@ locale: en-us keywords: powershell,cmdlet title: about_Return --- - # About Return -## SHORT DESCRIPTION +## Short description Exits the current scope, which can be a function, script, or script block. -## LONG DESCRIPTION +## 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. +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. +`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. +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 +### 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 +The `return` keyword can appear alone, or it can be followed by a value or expression, as follows: -``` +```powershell return return $a return (2 + $a) ``` +### Examples -### 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. Odd numbers are not multiplied +because the return statement exits before that statement can execute. -``` -function ScreenPassword($instance) +```powershell +function MultiplyEven { - if (!($instance.screensaversecure)) {return $instance.name} - + param($number) + + if ($number % 2) { return "$number is not even" } + $number * 2 } -foreach ($a in @(get-wmiobject win32_desktop)) { ScreenPassword($a) } +1..10 | ForEach-Object {MultiplyEven -Number $_} ``` -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. +```output +1 is not even +4 +3 is not even +8 +5 is not even +12 +7 is not even +16 +9 is not even +20 +``` -In PowerShell, values can be returned even if the Return keyword is not used. +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: +statements return the value of the `$a` variable: -``` +```powershell $a return ``` -The following statement also returns the value of $a: +The following statement also returns the value of `$a`: -``` +```powershell return $a ``` @@ -89,28 +98,104 @@ function calculation { $value += 73 return $value } -``` -Running this function and assigning the result to a variable has the following -effect: - -```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: +it is assigned to the `$a` variable, as in the following example: -```output -C:\PS> $a +``` +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. +by the function and assigned to the `$a` variable. + +### Return values and the Pipeline + +When you return a collection from your script block or function, PowerShell +automatically unrolls the members and passes them one at a time through the +pipeline. This is due to PowerShell's one-at-a-time processing. For more +information, see [about_pipelines](about_pipelines.md). + +This concept is illustrated by the following sample function that returns an +array of numbers. The output from the function is piped to the `Measure-Object` +cmdlet which counts the number of objects in the pipeline. + +```powershell +function Test-Return +{ + $array = 1,2,3 + return $array +} +Test-Return | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` -## SEE ALSO +To force a script block or function to return collection as a single +object to the pipeline, use one of the following two methods: + +- Unary array expression + + Utilizing a unary expression you can send your return value down the pipeline + as a single object as illustrated by the following example. + + ```powershell + function Test-Return + { + $array = 1,2,3 + return (, $array) + } + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + +- `Write-Output` with **NoEnumerate** parameter. + + You can also use the `Write-Output` cmdlet with the **NoEnumerate** + parameter. The example below uses the `Measure-Object` cmdlet to count the + objects sent to the pipeline from the sample function by the `return` + keyword. + + ```powershell + function Test-Return + { + $array = 1, 2, 3 + return Write-Output -NoEnumerate $array + } + + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + +## See also [about_Language_Keywords](about_Language_Keywords.md) diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md index 3dadff9759bb..8b48ed60b8e3 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md @@ -8,6 +8,7 @@ title: about_Script_Blocks # About Script Blocks ## Short description + Defines what a script block is and explains how to use script blocks in the PowerShell programming language. @@ -27,6 +28,11 @@ the following syntax: A script block returns the output of all the commands in the script block, either as a single object or as an array. +You can also specify a return value using the `return` keyword. The `return` +keyword does not affect or suppress other output returned from your script +block. However, the `return` keyword exits the script block at that line. For +more information, see [about_Return](about_Return.md). + Like functions, a script block can include parameters. Use the Param keyword to assign named parameters, as shown in the following syntax: diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_Switch.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_Switch.md index 7e42ec071000..21140924c54f 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_Switch.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_Switch.md @@ -166,13 +166,11 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one |Parameter |Description | |------------|----------------------------------------------------------| -|**Wildcard**|Indicates that the condition is a wildcard string. If you | -| |you use **Wildcard**, **Regex** and **Exact** are ignored. | -| |Also, if the match clause is not a string, the parameter is| +|**Wildcard**|Indicates that the condition is a wildcard string. | +| |If the match clause is not a string, the parameter is| | |ignored. | |**Exact** |Indicates that the match clause, if it is a string, must | -| |match exactly. **Regex** and **Wildcard** are ignored. | -| |Also, if the match clause is not a string, this parameter | +| |match exactly. If the match clause is not a string, this parameter | | |is ignored. | |**CaseSensitive**|Performs a case-sensitive match. If the match clause is not| | |a string, this parameter is ignored. | @@ -181,9 +179,15 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one | |used. Each line of the file is read and evaluated by the | | |`Switch` statement. | |**Regex** |Performs regular expression matching of the value to the | -| |condition. **Wildcard** and **Exact** are ignored. Also, if the| +| |condition. If the| | |match clause is not a string, this parameter is ignored. | +> [!NOTE] +> When specifying conflicting values, like **Regex** and **Wildcard**, the last +> parameter specified takes precedence, and all conflicting parameters are ignored. +> Multiple instances of parameters are also permitted. However, only the +> last parameter used is effective. + In this example, there is no matching case so there is no output. ```powershell @@ -197,6 +201,27 @@ switch ("fourteen") } ``` +By adding the `Default` clause, you can perform an action when no other +conditions succeed. + +```powershell +switch ("fourteen") +{ + 1 {"It is one."; Break} + 2 {"It is two."; Break} + 3 {"It is three."; Break} + 4 {"It is four."; Break} + "fo*" {"That's too many."} + Default { + "No matches" + } +} +``` + +```Output +No matches +``` + For the word "fourteen" to match a case you must use the `-Wildcard` or `-Regex` parameter. @@ -231,28 +256,67 @@ switch -Regex ($target) user@contoso.com is an email address ``` -Multiple instances of **Regex**, **Wildcard**, or **Exact** are permitted. -However, only the last parameter used is effective. +A `Switch` statement condition may be either: + +- An expression whose value is compared to the input value +- A script block which should return `$true` if a condition is met. The + script block receives the current object to compare in the `$_` + automatic variable and is evaluated in its own scope. + +The action for each condition is independent of the actions in other +conditions. + +The following example demonstrates the use of script blocks as `Switch` +statement conditions. + +```powershell +switch ("Test") +{ + {$_ -is [String]} { + "Found a string" + } + "Test" { + "This executes as well" + } +} +``` + +```Output +Found a string +This executes as well +``` If the value matches multiple conditions, the action for each condition is executed. To change this behavior, use the `Break` or `Continue` keywords. -The Break keyword stops processing and exits the Switch statement. +The `Break` keyword stops processing and exits the `Switch` statement. The `Continue` keyword stops processing the current value, but continues processing any subsequent values. -If the condition is an expression or a script block, it is evaluated just -before it is compared to the value. The value is assigned to the `$_` -automatic variable and is available in the expression. The match succeeds -if the expression is true or matches the value. The expression is evaluated -in its own scope. +The following example processes an array of numbers and displays if they are +odd or even. Negative numbers are skipped with the `Continue` keyword. If a +non-number is encountered, execution is terminated with the `Break` keyword. -The `Default` keyword specifies a condition that is evaluated only when no -other conditions match the value. +```powershell +switch (1,4,-1,3,"Hello",2,1) +{ + {$_ -lt 0} { Continue } + {$_ -isnot [Int32]} { Break } + {$_ % 2} { + "$_ is Odd" + } + {-not ($_ % 2)} { + "$_ is Even" + } +} +``` -The action for each condition is independent of the actions in other -conditions. +```Output +1 is Odd +4 is Even +3 is Odd +``` ## SEE ALSO diff --git a/reference/4.0/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/4.0/Microsoft.PowerShell.Core/About/about_pipelines.md index 1e43cd547d40..1fe7bb51eed0 100644 --- a/reference/4.0/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/4.0/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -5,7 +5,6 @@ locale: en-us keywords: powershell,cmdlet title: about_pipelines --- - # About Pipelines ## Short Description @@ -42,6 +41,7 @@ Here is a simple example. The following command gets the Notepad process and then stops it. For example, + ```powershell Get-Process notepad | Stop-Process ``` @@ -49,7 +49,7 @@ Get-Process notepad | Stop-Process The first command uses the `Get-Process` cmdlet to get an object representing the Notepad process. It uses a pipeline operator (`|`) to send the process object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice -that the `Stop-Process` command does not have a Name or ID parameter to +that the `Stop-Process` command does not have a **Name** or **ID** parameter to specify the process, because the specified process is submitted through the pipeline. @@ -120,8 +120,8 @@ tmp3.txt 114000 ## Using Pipelines The PowerShell cmdlets were designed to be used in pipelines. For example, you -can usually pipe the results of a Get cmdlet to an action cmdlet (such as a -Set, Start, Stop, or Rename cmdlet) for the same noun. +can usually pipe the results of a **Get** cmdlet to an action cmdlet (such as a +**Set**, **Start**, **Stop**, or **Rename** cmdlet) for the same noun. For example, you can pipe any service from the `Get-Service` cmdlet to the `Start-Service` or `Stop-Service` cmdlets (although disabled services cannot @@ -130,19 +130,21 @@ be restarted in this way). This command pipeline starts the WMI service on the computer: For example, + ```powershell Get-Service wmi | Start-Service ``` The cmdlets that get and set objects of the PowerShell providers, such as the -Item and ItemProperty cmdlets, are also designed to be used in pipelines. +**Item** and **ItemProperty** cmdlets, are also designed to be used in pipelines. For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. -This command adds a new registry entry, NoOfEmployees, with a value of 8124, -to the MyCompany registry key. +This command adds a new registry entry, **NoOfEmployees**, with a value of 8124, +to the **MyCompany** registry key. For example, + ```powershell Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 @@ -166,7 +168,7 @@ Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and `Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out cmdlets, such as `Out-Printer`. -For example, you can pipe the Winlogon process to the `Format-List` cmdlet to +For example, you can pipe the "Winlogon" process to the `Format-List` cmdlet to display all of the properties of the process in a list. For example, @@ -188,7 +190,7 @@ To do so, the PowerShell "parameter binding" component, which associates input objects with cmdlet parameters, tries to find a parameter that meets the following criteria: -- The parameter must accept input from a pipeline (not all do) +- The parameter must accept input from a pipeline (not all do). - The parameter must accept the type of object being sent or a type that the object can be converted to. - The parameter must not already be used in the command. @@ -222,7 +224,7 @@ Get-Service | Format-Table -Property name, dependentservices ``` is much like saving the service objects in a variable and using the -InputObject parameter of `Format-Table` to submit the service object. +**InputObject** parameter of `Format-Table` to submit the service object. For example, @@ -251,8 +253,45 @@ cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the process objects, and their properties and methods. -NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the -same type, it displays only one object type. +PowerShell automatically enumerates any type that implements the `IEnumerable` +interface and sends the members through the pipeline one at a time. The +exception is `[hashtable]`, which requires a call to the `GetEnumerator()` +method. + +In the example below, an array and a hashtable are piped to the `Measure-Object` +cmdlet, which counts the number of objects received from the pipeline. The array +has multiple members, and the hashtable has multiple key-value pairs. Only the +array is enumerated one at a time. + +```powershell +@(1,2,3) | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +```powershell +@{"One"=1;"Two"=2} | Measure-Object +``` + +```Output +Count : 1 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +> [!NOTE] +> `Get-Member` eliminates duplicates, so if the objects are all of the +> same type, it displays only one object type. In this case, `Get-Member` displays the properties and methods of each process object, that is, a System.Diagnostics.Process object. @@ -274,10 +313,10 @@ NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then -`Get-Member` receives an array of System.Diagnostics.Process objects as a +However, if you use the **InputObject** parameter of `Get-Member`, then +`Get-Member` receives an array of **System.Diagnostics.Process** objects as a single unit, and it displays the properties of an array of objects. (Note the -array symbol ([]) after the System.Object type name.) +array symbol (`[]`) after the **System.Object** type name.) For example, @@ -297,8 +336,8 @@ Clone Method System.Object Clone() ``` This result might not be what you intended, but after you understand it, you -can use it. For example, an array of process objects has a Count property that -you can use to count the number of processes on the computer. +can use it. For example, an array of process objects has a **Count** property +that you can use to count the number of processes on the computer. For example, @@ -370,7 +409,7 @@ This means that you can send objects (PsObjects) through the pipeline to the Cmdlets parameters can accept pipeline input in one of two different ways: -- ByValue: Parameters that accept input "by value" can accept piped objects +- **ByValue**: Parameters that accept input "by value" can accept piped objects that have the same .NET type as their parameter value or objects that can be converted to that type. @@ -378,7 +417,7 @@ Cmdlets parameters can accept pipeline input in one of two different ways: value. It can accept string objects or objects that can be converted to strings. -- ByPropertyName: Parameters that accept input "by property name" can accept +- **ByPropertyName**: Parameters that accept input "by property name" can accept piped objects only when a property of the object has the same name as the parameter. @@ -426,7 +465,7 @@ To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of PowerShell. The following command traces the Parameter Binding component while the command is processing. It uses the `-PSHost` parameter to display the results at the console and the `-filepath` command to send them to -the debug.txt file for later reference. +the `debug.txt` file for later reference. For example, @@ -484,7 +523,7 @@ Get-Help Move-ItemProperty -Parameter Destination ``` The results show that **Destination** takes pipeline input only "by property -name". That is, the piped object must have a property named Destination. +name". That is, the piped object must have a property named **Destination**. ``` -Destination @@ -507,8 +546,8 @@ For example, Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` -The output shows that the item is a Microsoft.Win32.RegistryKey that does not -have a Destination property. That explains why the command failed. +The output shows that the item is a **Microsoft.Win32.RegistryKey** that does +not have a **Destination** property. That explains why the command failed. To fix the command, we must specify the destination in the `Move-ItemProperty` cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name @@ -519,17 +558,19 @@ For example, ```powershell Get-Item -Path HKLM:\software\mycompany\design | -Move-ItemProperty -Dest HKLM:\software\mycompany\sales -Name product +Move-ItemProperty -Destination HKLM:\software\mycompany\sales -Name product ``` To verify that the command worked, use a `Get-ItemProperty` command: For example, + ```powershell -Get-Itemproperty HKLM:\software\mycompany\sales +Get-ItemProperty HKLM:\software\mycompany\sales ``` -The results show that the Product registry entry was moved to the Sales key. +The results show that the **Product** registry entry was moved to the **Sales** +key. ```Output PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa diff --git a/reference/4.0/Microsoft.PowerShell.Management/Copy-Item.md b/reference/4.0/Microsoft.PowerShell.Management/Copy-Item.md index a503fe8d0370..fb97e7998bdf 100644 --- a/reference/4.0/Microsoft.PowerShell.Management/Copy-Item.md +++ b/reference/4.0/Microsoft.PowerShell.Management/Copy-Item.md @@ -1,5 +1,5 @@ --- -ms.date: 10/18/2018 +ms.date: 5/30/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -36,9 +36,9 @@ Copy-Item -LiteralPath [[-Destination] ] [-Container] [-Force The `Copy-Item` cmdlet copies an item from one location to another location in the same namespace. For instance, it can copy a file to a folder, but it cannot copy a file to a certificate drive. -This cmdlet does not cut or delete the items being copied. -The particular items that the cmdlet can copy depend on the PowerShell provider that exposes the item. -For instance, it can copy files and directories in a file system drive and registry keys and entries in the registry drive. +This cmdlet does not cut or delete the items being copied. The particular items that the cmdlet can +copy depend on the PowerShell provider that exposes the item. For instance, it can copy files and +directories in a file system drive and registry keys and entries in the registry drive. This cmdlet can copy and rename items in the same command. To rename an item, enter the new name in the value of the **Destination** parameter. @@ -48,7 +48,7 @@ To rename an item and not copy it, use the `Rename-Item` cmdlet. ### Example 1: Copy a file to the specified directory -This command copies the "mar1604.log.txt" file to the "C:\Presentation" directory. +This command copies the `mar1604.log.txt` file to the `C:\Presentation` directory. The command does not delete the original file. ```powershell @@ -58,17 +58,19 @@ Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination "C:\Presentation" ### Example 2: Copy the contents of a directory to another directory This command copies the entire contents of the "Logfiles" directory into the "Drawings" directory. -If the "LogFiles" directory contains files in subdirectories, those subdirectories are copied with their file trees intact. -The **Container** parameter is set to "true" by default. -This preserves the directory structure. ```powershell Copy-Item "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse ``` +If the "LogFiles" directory contains files in subdirectories, those subdirectories are copied with +their file trees intact. The **Container** parameter is set to "true" by default. + +This preserves the directory structure. + ### Example 3: Copy the contents of a directory to another directory and create the destination directory if it does not exist -This command copies the contents of the "C:\Logfiles" directory to the "C:\Drawings\Logs" directory. +This command copies the contents of the `C:\Logfiles` directory to the `C:\Drawings\Logs` directory. It creates the "\Logs" subdirectory if it does not already exist. ```powershell @@ -77,8 +79,10 @@ Copy-Item C:\Logfiles -Destination C:\Drawings\Logs -Recurse ### Example 4: Copy a file to the specified directory and rename the file -This command uses the `Copy-Item` cmdlet to copy the "Get-Widget.ps1" script from the "\\\\Server01\Share" directory to the "\\\\Server12\ScriptArchive" directory. -As part of the copy operation, the command also changes the item name from "Get-Widget.ps1" to "Get-Widget.ps1.txt", so it can be attached to email messages. +This command uses the `Copy-Item` cmdlet to copy the `Get-Widget.ps1` script from the +`\\Server01\Share` directory to the `\\Server12\ScriptArchive` directory. +As part of the copy operation, the command also changes the item name from `Get-Widget.ps1` to +`Get-Widget.ps1.txt`, so it can be attached to email messages. ```powershell Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchive\Get-Widget.ps1.txt" @@ -86,14 +90,10 @@ Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchi ### -Credential -Specifies a user account that has permission to perform this action. -The default is the current user. - -Type a user name, such as "User01" or "Domain01\User01", or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. -If you type a user name, you are prompted for a password. - -> [!WARNING] -> This parameter is not supported by any providers installed with Windows PowerShell. +> [!NOTE] +> This parameter is not supported by any providers installed with PowerShell. +> To impersonate another user, or elevate your credentials when running this cmdlet, +> use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: PSCredential @@ -110,7 +110,9 @@ Accept wildcard characters: False ### -Destination Specifies the path to the new location. -To rename a copied item, include the new name in the value. +The default is the current directory. + +To rename the item being copied, specify a new name in the value of the **Destination** parameter. ```yaml Type: String @@ -126,10 +128,11 @@ Accept wildcard characters: False ### -Exclude -Specifies, as a string array, an item or items that this cmdlet excludes from the operation. -The value of this parameter qualifies the **Path** parameter. -Enter a path element or pattern, such as "*.txt". -Wildcard characters are permitted. +Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value +of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as +`*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the +command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character +specifies the contents of the `C:\Windows` directory. ```yaml Type: String[] @@ -145,11 +148,11 @@ Accept wildcard characters: True ### -Filter -Specifies a filter in the format or language of the provider. -The value of this parameter qualifies the **Path** parameter. - -The syntax of the filter, including the use of wildcard characters, depends on the provider. -Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. +Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) +provider is the only installed PowerShell provider that supports the use of filters. You can find +the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). +Filters are more efficient than other parameters, because the provider applies them when the cmdlet +gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: String @@ -165,7 +168,8 @@ Accept wildcard characters: True ### -Force -Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a read-only file or alias. +Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a +read-only file or alias. ```yaml Type: SwitchParameter @@ -174,17 +178,18 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include -Specifies, as a string array, an item or items that this cmdlet includes in the operation. -The value of this parameter qualifies the **Path** parameter. -Enter a path element or pattern, such as "*.txt". -Wildcard characters are permitted. +Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value +of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as +`"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the +command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character +specifies the contents of the `C:\Windows` directory. ```yaml Type: String[] @@ -195,16 +200,17 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -LiteralPath -Specifies a path to the item. -Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it is typed. -No characters are interpreted as wildcards. -If the path includes escape characters, enclose it in single quotation marks. -Single quotation marks tell PowerShell not to interpret any characters as escape sequences. +Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is +typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose +it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters +as escape sequences. + +For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: String[] @@ -230,7 +236,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -238,6 +244,7 @@ Accept wildcard characters: False ### -Path Specifies, as a string array, the path to the items to copy. +Wildcard characters are permitted. ```yaml Type: String[] @@ -248,7 +255,7 @@ Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -Recurse @@ -262,7 +269,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -320,7 +327,10 @@ Accept wildcard characters: False ### CommonParameters -This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). +This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, +`-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, +`-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see +[about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS @@ -332,8 +342,8 @@ You can pipe a string that contains a path to this cmdlet. ### None or an object representing the copied item. -When you use the *PassThru* parameter, this cmdlet returns an object that represents the copied item. -Otherwise, this cmdlet does not generate any output. +When you use the *PassThru* parameter, this cmdlet returns an object that represents the copied +item. Otherwise, this cmdlet does not generate any output. ## NOTES diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Functions.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Functions.md index a90c198cdd4a..9425374767e4 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Functions.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Functions.md @@ -29,7 +29,10 @@ positional, switch, or dynamic parameters. Function parameters can be read from the command line or from the pipeline. Functions can return values that can be displayed, assigned to variables, or -passed to other functions or cmdlets. +passed to other functions or cmdlets. You can also specify a return value using +the `return` keyword. The `return` keyword does not affect or suppress other +output returned from your function. However, the `return` keyword exits the +function at that line. For more information, see [about_Return](about_Return.md). The function's statement list can contain different types of statement lists with the keywords `Begin`, `Process`, and `End`. These statement lists diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Return.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Return.md index 8276ef332218..d984c4a351ce 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Return.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Return.md @@ -8,6 +8,7 @@ title: about_Return # About Return ## Short description + Exits the current scope, which can be a function, script, or script block. ## Long description @@ -109,14 +110,17 @@ $a = calculation 14 ``` The "Please wait. Working on calculation..." string is not displayed. Instead, -it is assigned to the `$a` variable. +it is assigned to the `$a` variable, as in the following example: -```output -C:\PS> $a +``` +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. + If you would like to display a message within your function, beginning in PowerShell 5.0, you can use the `Information` stream. The code below corrects the above example using the `Write-Information` cmdlet with a @@ -140,6 +144,87 @@ C:\PS> $a 87 ``` +### Return values and the Pipeline + +When you return a collection from your script block or function, PowerShell +automatically unrolls the members and passes them one at a time through the +pipeline. This is due to PowerShell's one-at-a-time processing. For more +information, see [about_pipelines](about_pipelines.md). + +This concept is illustrated by the following sample function that returns an +array of numbers. The output from the function is piped to the `Measure-Object` +cmdlet which counts the number of objects in the pipeline. + +```powershell +function Test-Return +{ + $array = 1,2,3 + return $array +} +Test-Return | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +To force a script block or function to return collection as a single +object to the pipeline, use one of the following two methods: + +- Unary array expression + + Utilizing a unary expression you can send your return value down the pipeline + as a single object as illustrated by the following example. + + ```powershell + function Test-Return + { + $array = 1,2,3 + return (, $array) + } + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + +- `Write-Output` with **NoEnumerate** parameter. + + You can also use the `Write-Output` cmdlet with the **NoEnumerate** + parameter. The example below uses the `Measure-Object` cmdlet to count the + objects sent to the pipeline from the sample function by the `return` + keyword. + + ```powershell + function Test-Return + { + $array = 1, 2, 3 + return Write-Output -NoEnumerate $array + } + + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + ## See also [about_Language_Keywords](about_Language_Keywords.md) @@ -152,4 +237,4 @@ C:\PS> $a [Write-Information](../../Microsoft.PowerShell.Utility/Write-Information.md) -[about_Script_Blocks](about_Script_Blocks.md) \ No newline at end of file +[about_Script_Blocks](about_Script_Blocks.md) diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md index 7728f9ba5405..973338103c5a 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Script_Blocks.md @@ -8,6 +8,7 @@ title: about_Script_Blocks # About Script Blocks ## Short description + Defines what a script block is and explains how to use script blocks in the PowerShell programming language. @@ -27,6 +28,11 @@ the following syntax: A script block returns the output of all the commands in the script block, either as a single object or as an array. +You can also specify a return value using the `return` keyword. The `return` +keyword does not affect or suppress other output returned from your script +block. However, the `return` keyword exits the script block at that line. For +more information, see [about_Return](about_Return.md). + Like functions, a script block can include parameters. Use the Param keyword to assign named parameters, as shown in the following syntax: diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_Switch.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_Switch.md index 7e42ec071000..21140924c54f 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_Switch.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_Switch.md @@ -166,13 +166,11 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one |Parameter |Description | |------------|----------------------------------------------------------| -|**Wildcard**|Indicates that the condition is a wildcard string. If you | -| |you use **Wildcard**, **Regex** and **Exact** are ignored. | -| |Also, if the match clause is not a string, the parameter is| +|**Wildcard**|Indicates that the condition is a wildcard string. | +| |If the match clause is not a string, the parameter is| | |ignored. | |**Exact** |Indicates that the match clause, if it is a string, must | -| |match exactly. **Regex** and **Wildcard** are ignored. | -| |Also, if the match clause is not a string, this parameter | +| |match exactly. If the match clause is not a string, this parameter | | |is ignored. | |**CaseSensitive**|Performs a case-sensitive match. If the match clause is not| | |a string, this parameter is ignored. | @@ -181,9 +179,15 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one | |used. Each line of the file is read and evaluated by the | | |`Switch` statement. | |**Regex** |Performs regular expression matching of the value to the | -| |condition. **Wildcard** and **Exact** are ignored. Also, if the| +| |condition. If the| | |match clause is not a string, this parameter is ignored. | +> [!NOTE] +> When specifying conflicting values, like **Regex** and **Wildcard**, the last +> parameter specified takes precedence, and all conflicting parameters are ignored. +> Multiple instances of parameters are also permitted. However, only the +> last parameter used is effective. + In this example, there is no matching case so there is no output. ```powershell @@ -197,6 +201,27 @@ switch ("fourteen") } ``` +By adding the `Default` clause, you can perform an action when no other +conditions succeed. + +```powershell +switch ("fourteen") +{ + 1 {"It is one."; Break} + 2 {"It is two."; Break} + 3 {"It is three."; Break} + 4 {"It is four."; Break} + "fo*" {"That's too many."} + Default { + "No matches" + } +} +``` + +```Output +No matches +``` + For the word "fourteen" to match a case you must use the `-Wildcard` or `-Regex` parameter. @@ -231,28 +256,67 @@ switch -Regex ($target) user@contoso.com is an email address ``` -Multiple instances of **Regex**, **Wildcard**, or **Exact** are permitted. -However, only the last parameter used is effective. +A `Switch` statement condition may be either: + +- An expression whose value is compared to the input value +- A script block which should return `$true` if a condition is met. The + script block receives the current object to compare in the `$_` + automatic variable and is evaluated in its own scope. + +The action for each condition is independent of the actions in other +conditions. + +The following example demonstrates the use of script blocks as `Switch` +statement conditions. + +```powershell +switch ("Test") +{ + {$_ -is [String]} { + "Found a string" + } + "Test" { + "This executes as well" + } +} +``` + +```Output +Found a string +This executes as well +``` If the value matches multiple conditions, the action for each condition is executed. To change this behavior, use the `Break` or `Continue` keywords. -The Break keyword stops processing and exits the Switch statement. +The `Break` keyword stops processing and exits the `Switch` statement. The `Continue` keyword stops processing the current value, but continues processing any subsequent values. -If the condition is an expression or a script block, it is evaluated just -before it is compared to the value. The value is assigned to the `$_` -automatic variable and is available in the expression. The match succeeds -if the expression is true or matches the value. The expression is evaluated -in its own scope. +The following example processes an array of numbers and displays if they are +odd or even. Negative numbers are skipped with the `Continue` keyword. If a +non-number is encountered, execution is terminated with the `Break` keyword. -The `Default` keyword specifies a condition that is evaluated only when no -other conditions match the value. +```powershell +switch (1,4,-1,3,"Hello",2,1) +{ + {$_ -lt 0} { Continue } + {$_ -isnot [Int32]} { Break } + {$_ % 2} { + "$_ is Odd" + } + {-not ($_ % 2)} { + "$_ is Even" + } +} +``` -The action for each condition is independent of the actions in other -conditions. +```Output +1 is Odd +4 is Even +3 is Odd +``` ## SEE ALSO diff --git a/reference/5.0/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/5.0/Microsoft.PowerShell.Core/About/about_pipelines.md index 165b448c6cb3..1fe7bb51eed0 100644 --- a/reference/5.0/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/5.0/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -8,6 +8,7 @@ title: about_pipelines # About Pipelines ## Short Description + Combining commands into pipelines in the PowerShell ## Long Description @@ -40,6 +41,7 @@ Here is a simple example. The following command gets the Notepad process and then stops it. For example, + ```powershell Get-Process notepad | Stop-Process ``` @@ -47,7 +49,7 @@ Get-Process notepad | Stop-Process The first command uses the `Get-Process` cmdlet to get an object representing the Notepad process. It uses a pipeline operator (`|`) to send the process object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice -that the `Stop-Process` command does not have a Name or ID parameter to +that the `Stop-Process` command does not have a **Name** or **ID** parameter to specify the process, because the specified process is submitted through the pipeline. @@ -118,8 +120,8 @@ tmp3.txt 114000 ## Using Pipelines The PowerShell cmdlets were designed to be used in pipelines. For example, you -can usually pipe the results of a Get cmdlet to an action cmdlet (such as a -Set, Start, Stop, or Rename cmdlet) for the same noun. +can usually pipe the results of a **Get** cmdlet to an action cmdlet (such as a +**Set**, **Start**, **Stop**, or **Rename** cmdlet) for the same noun. For example, you can pipe any service from the `Get-Service` cmdlet to the `Start-Service` or `Stop-Service` cmdlets (although disabled services cannot @@ -128,19 +130,21 @@ be restarted in this way). This command pipeline starts the WMI service on the computer: For example, + ```powershell Get-Service wmi | Start-Service ``` The cmdlets that get and set objects of the PowerShell providers, such as the -Item and ItemProperty cmdlets, are also designed to be used in pipelines. +**Item** and **ItemProperty** cmdlets, are also designed to be used in pipelines. For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. -This command adds a new registry entry, NoOfEmployees, with a value of 8124, -to the MyCompany registry key. +This command adds a new registry entry, **NoOfEmployees**, with a value of 8124, +to the **MyCompany** registry key. For example, + ```powershell Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 @@ -164,7 +168,7 @@ Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and `Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out cmdlets, such as `Out-Printer`. -For example, you can pipe the Winlogon process to the `Format-List` cmdlet to +For example, you can pipe the "Winlogon" process to the `Format-List` cmdlet to display all of the properties of the process in a list. For example, @@ -186,7 +190,7 @@ To do so, the PowerShell "parameter binding" component, which associates input objects with cmdlet parameters, tries to find a parameter that meets the following criteria: -- The parameter must accept input from a pipeline (not all do) +- The parameter must accept input from a pipeline (not all do). - The parameter must accept the type of object being sent or a type that the object can be converted to. - The parameter must not already be used in the command. @@ -220,7 +224,7 @@ Get-Service | Format-Table -Property name, dependentservices ``` is much like saving the service objects in a variable and using the -InputObject parameter of `Format-Table` to submit the service object. +**InputObject** parameter of `Format-Table` to submit the service object. For example, @@ -249,8 +253,45 @@ cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the process objects, and their properties and methods. -NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the -same type, it displays only one object type. +PowerShell automatically enumerates any type that implements the `IEnumerable` +interface and sends the members through the pipeline one at a time. The +exception is `[hashtable]`, which requires a call to the `GetEnumerator()` +method. + +In the example below, an array and a hashtable are piped to the `Measure-Object` +cmdlet, which counts the number of objects received from the pipeline. The array +has multiple members, and the hashtable has multiple key-value pairs. Only the +array is enumerated one at a time. + +```powershell +@(1,2,3) | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +```powershell +@{"One"=1;"Two"=2} | Measure-Object +``` + +```Output +Count : 1 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +> [!NOTE] +> `Get-Member` eliminates duplicates, so if the objects are all of the +> same type, it displays only one object type. In this case, `Get-Member` displays the properties and methods of each process object, that is, a System.Diagnostics.Process object. @@ -272,10 +313,10 @@ NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then -`Get-Member` receives an array of System.Diagnostics.Process objects as a +However, if you use the **InputObject** parameter of `Get-Member`, then +`Get-Member` receives an array of **System.Diagnostics.Process** objects as a single unit, and it displays the properties of an array of objects. (Note the -array symbol ([]) after the System.Object type name.) +array symbol (`[]`) after the **System.Object** type name.) For example, @@ -295,8 +336,8 @@ Clone Method System.Object Clone() ``` This result might not be what you intended, but after you understand it, you -can use it. For example, an array of process objects has a Count property that -you can use to count the number of processes on the computer. +can use it. For example, an array of process objects has a **Count** property +that you can use to count the number of processes on the computer. For example, @@ -368,7 +409,7 @@ This means that you can send objects (PsObjects) through the pipeline to the Cmdlets parameters can accept pipeline input in one of two different ways: -- ByValue: Parameters that accept input "by value" can accept piped objects +- **ByValue**: Parameters that accept input "by value" can accept piped objects that have the same .NET type as their parameter value or objects that can be converted to that type. @@ -376,7 +417,7 @@ Cmdlets parameters can accept pipeline input in one of two different ways: value. It can accept string objects or objects that can be converted to strings. -- ByPropertyName: Parameters that accept input "by property name" can accept +- **ByPropertyName**: Parameters that accept input "by property name" can accept piped objects only when a property of the object has the same name as the parameter. @@ -424,7 +465,7 @@ To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of PowerShell. The following command traces the Parameter Binding component while the command is processing. It uses the `-PSHost` parameter to display the results at the console and the `-filepath` command to send them to -the debug.txt file for later reference. +the `debug.txt` file for later reference. For example, @@ -482,7 +523,7 @@ Get-Help Move-ItemProperty -Parameter Destination ``` The results show that **Destination** takes pipeline input only "by property -name". That is, the piped object must have a property named Destination. +name". That is, the piped object must have a property named **Destination**. ``` -Destination @@ -505,8 +546,8 @@ For example, Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` -The output shows that the item is a Microsoft.Win32.RegistryKey that does not -have a Destination property. That explains why the command failed. +The output shows that the item is a **Microsoft.Win32.RegistryKey** that does +not have a **Destination** property. That explains why the command failed. To fix the command, we must specify the destination in the `Move-ItemProperty` cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name @@ -517,17 +558,19 @@ For example, ```powershell Get-Item -Path HKLM:\software\mycompany\design | -Move-ItemProperty -Dest HKLM:\software\mycompany\sales -Name product +Move-ItemProperty -Destination HKLM:\software\mycompany\sales -Name product ``` To verify that the command worked, use a `Get-ItemProperty` command: For example, + ```powershell -Get-Itemproperty HKLM:\software\mycompany\sales +Get-ItemProperty HKLM:\software\mycompany\sales ``` -The results show that the Product registry entry was moved to the Sales key. +The results show that the **Product** registry entry was moved to the **Sales** +key. ```Output PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa diff --git a/reference/5.0/Microsoft.PowerShell.Management/Copy-Item.md b/reference/5.0/Microsoft.PowerShell.Management/Copy-Item.md index be8e685bea57..361d12cb6a87 100644 --- a/reference/5.0/Microsoft.PowerShell.Management/Copy-Item.md +++ b/reference/5.0/Microsoft.PowerShell.Management/Copy-Item.md @@ -1,5 +1,5 @@ --- -ms.date: 10/18/2018 +ms.date: 5/30/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -35,9 +35,9 @@ Copy-Item -LiteralPath [[-Destination] ] [-Container] [-Force The `Copy-Item` cmdlet copies an item from one location to another location in the same namespace. For instance, it can copy a file to a folder, but it cannot copy a file to a certificate drive. -This cmdlet does not cut or delete the items being copied. -The particular items that the cmdlet can copy depend on the PowerShell provider that exposes the item. -For instance, it can copy files and directories in a file system drive and registry keys and entries in the registry drive. +This cmdlet does not cut or delete the items being copied. The particular items that the cmdlet can +copy depend on the PowerShell provider that exposes the item. For instance, it can copy files and +directories in a file system drive and registry keys and entries in the registry drive. This cmdlet can copy and rename items in the same command. To rename an item, enter the new name in the value of the **Destination** parameter. @@ -47,7 +47,7 @@ To rename an item and not copy it, use the `Rename-Item` cmdlet. ### Example 1: Copy a file to the specified directory -This command copies the "mar1604.log.txt" file to the "C:\Presentation" directory. +This command copies the `mar1604.log.txt` file to the `C:\Presentation` directory. The command does not delete the original file. ```powershell @@ -57,17 +57,19 @@ Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination "C:\Presentation" ### Example 2: Copy the contents of a directory to another directory This command copies the entire contents of the "Logfiles" directory into the "Drawings" directory. -If the "LogFiles" directory contains files in subdirectories, those subdirectories are copied with their file trees intact. -The **Container** parameter is set to "true" by default. -This preserves the directory structure. ```powershell Copy-Item "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse ``` +If the "LogFiles" directory contains files in subdirectories, those subdirectories are copied with +their file trees intact. The **Container** parameter is set to "true" by default. + +This preserves the directory structure. + ### Example 3: Copy the contents of a directory to another directory and create the destination directory if it does not exist -This command copies the contents of the "C:\Logfiles" directory to the "C:\Drawings\Logs" directory. +This command copies the contents of the `C:\Logfiles` directory to the `C:\Drawings\Logs` directory. It creates the "\Logs" subdirectory if it does not already exist. ```powershell @@ -76,8 +78,10 @@ Copy-Item C:\Logfiles -Destination C:\Drawings\Logs -Recurse ### Example 4: Copy a file to the specified directory and rename the file -This command uses the `Copy-Item` cmdlet to copy the "Get-Widget.ps1" script from the "\\\\Server01\Share" directory to the "\\\\Server12\ScriptArchive" directory. -As part of the copy operation, the command also changes the item name from "Get-Widget.ps1" to "Get-Widget.ps1.txt", so it can be attached to email messages. +This command uses the `Copy-Item` cmdlet to copy the `Get-Widget.ps1` script from the +`\\Server01\Share` directory to the `\\Server12\ScriptArchive` directory. +As part of the copy operation, the command also changes the item name from `Get-Widget.ps1` to +`Get-Widget.ps1.txt`, so it can be attached to email messages. ```powershell Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchive\Get-Widget.ps1.txt" @@ -85,10 +89,12 @@ Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchi ### Example 5: Copy a file to a remote computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFu" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy "test.log" from the "D:\Folder001" folder to the "C:\Folder001_Copy" folder on the remote computer using the session information stored in the `$Session` variable. -This command does not delete the original file. +The second command uses the `Copy-Item` cmdlet to copy `test.log` from the `D:\Folder001` folder to +the `C:\Folder001_Copy` folder on the remote computer using the session information stored in the +`$Session` variable. This command does not delete the original file. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul" @@ -97,10 +103,12 @@ Copy-Item "D:\Folder001\test.log" -Destination "C:\Folder001_Copy\" -ToSession $ ### Example 6: Copy the entire contents of a folder to a remote computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +`Contoso\PattiFul` and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy the entire contents from the "D:\Folder002" folder to the "C:\Folder002_Copy" directory on the remote computer using the session information stored in the `$Session` variable. -The subfolders are copied with their file trees intact. +The second command uses the `Copy-Item` cmdlet to copy the entire contents from the `D:\Folder002` +folder to the `C:\Folder002_Copy` directory on the remote computer using the session information +stored in the `$Session` variable. The subfolders are copied with their file trees intact. ```powershell $Session = New-PSSession -ComputerName "Server02" -Credential "Contoso\PattiFul" @@ -109,11 +117,14 @@ Copy-Item "D:\Folder002\" -Destination "C:\Folder002_Copy\" -ToSession $Session ### Example 7: Recursively copy the entire contents of a folder to a remote computer -The first command creates a session to the remote computer named Server01 with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named Server01 with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy the entire contents from the "D:\Folder003" folder to the "C:\Folder003_Copy" directory on the remote computer using the session information stored in the `$Session` variable. -The subfolders are copied with their file trees intact. -Since this command uses the **Recurse** parameter, the operation creates the "Folder003_Copy" folder if it does not already exist. +The second command uses the `Copy-Item` cmdlet to copy the entire contents from the `D:\Folder003` +folder to the `C:\Folder003_Copy` directory on the remote computer using the session information +stored in the `$Session` variable. The subfolders are copied with their file trees intact. +Since this command uses the **Recurse** parameter, the operation creates the "Folder003_Copy" folder +if it does not already exist. ```powershell $Session = New-PSSession -ComputerName "Server04" -Credential "Contoso\PattiFul" @@ -122,10 +133,14 @@ Copy-Item "D:\Folder003\" -Destination "C:\Folder003_Copy\" -ToSession $Session ### Example 8: Copy a file to a remote computer and then rename the file -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy "scriptingexample.ps1" from the "D:\Folder004" folder to the "C:\Folder004_Copy" folder on the remote computer using the session information stored in the `$Session` variable. -As part of the copy operation, the command also changes the item name from "scriptingexample.ps1" to "scriptingexample_copy.ps1", so it can be attached to email messages. +The second command uses the `Copy-Item` cmdlet to copy `scriptingexample.ps1` from the +`D:\Folder004` folder to the "C:\Folder004_Copy" folder on the remote computer using the session +information stored in the `$Session` variable. +As part of the copy operation, the command also changes the item name from `scriptingexample.ps1` to +`scriptingexample_copy.ps1`, so it can be attached to email messages. This command does not delete the original file. ```powershell @@ -135,10 +150,12 @@ Copy-Item "D:\Folder004\scriptingexample.ps1" -Destination "C:\Folder004_Copy\sc ### Example 9: Copy a remote file to the local computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy test.log from the remote "C:\MyRemoteData\" to the local "D:\MyLocalData" folder using the session information stored in the `$Session` variable. -This command does not delete the original file. +The second command uses the `Copy-Item` cmdlet to copy test.log from the remote `C:\MyRemoteData\` +to the local `D:\MyLocalData` folder using the session information stored in the `$Session` +variable. This command does not delete the original file. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul" @@ -147,10 +164,14 @@ Copy-Item "C:\MyRemoteData\test.log" -Destination "D:\MyLocalData\" -FromSession ### Example 10: Copy the entire contents of a remote folder to the local computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy the entire contents from the remote "C:\MyRemoteData\scripts" folder to the local "D:\MyLocalData" folder using the session information stored in the `$Session` variable. -If the scripts folder contains files in subfolders, those subfolders are copied with their file trees intact. +The second command uses the `Copy-Item` cmdlet to copy the entire contents from the remote +`C:\MyRemoteData\scripts` folder to the local `D:\MyLocalData` folder using the session information +stored in the `$Session` variable. +If the scripts folder contains files in subfolders, those subfolders are copied with their file +trees intact. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul" @@ -159,10 +180,15 @@ Copy-Item "C:\MyRemoteData\scripts" -Destination "D:\MyLocalData\" -FromSession ### Example 11: Recursively copy the entire contents of a remote folder to the local computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy the entire contents from the remote "C:\MyRemoteData\scripts" folder to the local "D:\MyLocalData\scripts" folder using the session information stored in the `$Session` variable. -Since this command uses the **Recurse** parameter, the operation creates the scripts folder if it does not already exist. If the scripts folder contains files in subfolders, those subfolders are copied with their file trees intact. +The second command uses the `Copy-Item` cmdlet to copy the entire contents from the remote +`C:\MyRemoteData\scripts` folder to the local `D:\MyLocalData\scripts` folder using the session +information stored in the `$Session` variable. +Since this command uses the **Recurse** parameter, the operation creates the scripts folder if it +does not already exist. If the scripts folder contains files in subfolders, those subfolders are +copied with their file trees intact. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul" @@ -198,21 +224,17 @@ Aliases: Required: False Position: Named -Default value: None +Default value: True Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential -Specifies a user account that has permission to perform this action. -The default is the current user. - -Type a user name, such as "User01" or "Domain01\User01", or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. -If you type a user name, you are prompted for a password. - -> [!WARNING] -> This parameter is not supported by any providers installed with Windows PowerShell. +> [!NOTE] +> This parameter is not supported by any providers installed with PowerShell. +> To impersonate another user, or elevate your credentials when running this cmdlet, +> use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: PSCredential @@ -229,7 +251,9 @@ Accept wildcard characters: False ### -Destination Specifies the path to the new location. -To rename a copied item, include the new name in the value. +The default is the current directory. + +To rename the item being copied, specify a new name in the value of the **Destination** parameter. ```yaml Type: String @@ -245,10 +269,11 @@ Accept wildcard characters: False ### -Exclude -Specifies, as a string array, an item or items that this cmdlet excludes from the operation. -The value of this parameter qualifies the **Path** parameter. -Enter a path element or pattern, such as "*.txt". -Wildcard characters are permitted. +Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value +of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as +`*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the +command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character +specifies the contents of the `C:\Windows` directory. ```yaml Type: String[] @@ -264,11 +289,11 @@ Accept wildcard characters: True ### -Filter -Specifies a filter in the format or language of the provider. -The value of this parameter qualifies the **Path** parameter. - -The syntax of the filter, including the use of wildcard characters, depends on the provider. -Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. +Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) +provider is the only installed PowerShell provider that supports the use of filters. You can find +the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). +Filters are more efficient than other parameters, because the provider applies them when the cmdlet +gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: String @@ -284,7 +309,8 @@ Accept wildcard characters: True ### -Force -Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a read-only file or alias. +Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a +read-only file or alias. ```yaml Type: SwitchParameter @@ -293,7 +319,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -301,7 +327,8 @@ Accept wildcard characters: False ### -FromSession Specifies the **PSSession** object from which a remote file is being copied. -When you use this parameter, the *Path* and *LiteralPath* parameters refer to the local path on the remote machine. +When you use this parameter, the *Path* and *LiteralPath* parameters refer to the local path on the +remote machine. ```yaml Type: PSSession @@ -317,10 +344,11 @@ Accept wildcard characters: False ### -Include -Specifies, as a string array, an item or items that this cmdlet includes in the operation. -The value of this parameter qualifies the **Path** parameter. -Enter a path element or pattern, such as "*.txt". -Wildcard characters are permitted. +Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value +of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as +`"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the +command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character +specifies the contents of the `C:\Windows` directory. ```yaml Type: String[] @@ -331,16 +359,17 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -LiteralPath -Specifies a path to the item. -Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it is typed. -No characters are interpreted as wildcards. -If the path includes escape characters, enclose it in single quotation marks. -Single quotation marks tell PowerShell not to interpret any characters as escape sequences. +Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is +typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose +it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters +as escape sequences. + +For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: String[] @@ -366,7 +395,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -374,6 +403,7 @@ Accept wildcard characters: False ### -Path Specifies, as a string array, the path to the items to copy. +Wildcard characters are permitted. ```yaml Type: String[] @@ -384,7 +414,7 @@ Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -Recurse @@ -398,7 +428,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -406,7 +436,8 @@ Accept wildcard characters: False ### -ToSession Specifies the **PSSession** object to which a remote file is being copied. -When you use this parameter, the *Path* and *LiteralPath* parameters refer to the local path on the remote machine. +When you use this parameter, the **Path** and **LiteralPath** parameters refer to the local path on the +remote machine. ```yaml Type: PSSession @@ -457,7 +488,10 @@ Accept wildcard characters: False ### CommonParameters -This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). +This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, +`-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, +`-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see +[about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS @@ -469,8 +503,8 @@ You can pipe a string that contains a path to this cmdlet. ### None or an object representing the copied item. -When you use the *PassThru* parameter, this cmdlet returns an object that represents the copied item. -Otherwise, this cmdlet does not generate any output. +When you use the *PassThru* parameter, this cmdlet returns an object that represents the copied +item. Otherwise, this cmdlet does not generate any output. ## NOTES diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Functions.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Functions.md index a90c198cdd4a..9425374767e4 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Functions.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Functions.md @@ -29,7 +29,10 @@ positional, switch, or dynamic parameters. Function parameters can be read from the command line or from the pipeline. Functions can return values that can be displayed, assigned to variables, or -passed to other functions or cmdlets. +passed to other functions or cmdlets. You can also specify a return value using +the `return` keyword. The `return` keyword does not affect or suppress other +output returned from your function. However, the `return` keyword exits the +function at that line. For more information, see [about_Return](about_Return.md). The function's statement list can contain different types of statement lists with the keywords `Begin`, `Process`, and `End`. These statement lists diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Return.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Return.md index 7570142b646f..55d9b5f6455c 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Return.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Return.md @@ -110,14 +110,17 @@ $a = calculation 14 ``` The "Please wait. Working on calculation..." string is not displayed. Instead, -it is assigned to the `$a` variable. +it is assigned to the `$a` variable, as in the following example: -```output -C:\PS> $a +``` +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. + If you would like to display a message within your function, beginning in PowerShell 5.0, you can use the `Information` stream. The code below corrects the above example using the `Write-Information` cmdlet with a @@ -141,6 +144,87 @@ C:\PS> $a 87 ``` +### Return values and the Pipeline + +When you return a collection from your script block or function, PowerShell +automatically unrolls the members and passes them one at a time through the +pipeline. This is due to PowerShell's one-at-a-time processing. For more +information, see [about_pipelines](about_pipelines.md). + +This concept is illustrated by the following sample function that returns an +array of numbers. The output from the function is piped to the `Measure-Object` +cmdlet which counts the number of objects in the pipeline. + +```powershell +function Test-Return +{ + $array = 1,2,3 + return $array +} +Test-Return | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +To force a script block or function to return collection as a single +object to the pipeline, use one of the following two methods: + +- Unary array expression + + Utilizing a unary expression you can send your return value down the pipeline + as a single object as illustrated by the following example. + + ```powershell + function Test-Return + { + $array = 1,2,3 + return (, $array) + } + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + +- `Write-Output` with **NoEnumerate** parameter. + + You can also use the `Write-Output` cmdlet with the **NoEnumerate** + parameter. The example below uses the `Measure-Object` cmdlet to count the + objects sent to the pipeline from the sample function by the `return` + keyword. + + ```powershell + function Test-Return + { + $array = 1, 2, 3 + return Write-Output -NoEnumerate $array + } + + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + ## See also [about_Language_Keywords](about_Language_Keywords.md) diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Script_Blocks.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Script_Blocks.md index 7728f9ba5405..973338103c5a 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Script_Blocks.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Script_Blocks.md @@ -8,6 +8,7 @@ title: about_Script_Blocks # About Script Blocks ## Short description + Defines what a script block is and explains how to use script blocks in the PowerShell programming language. @@ -27,6 +28,11 @@ the following syntax: A script block returns the output of all the commands in the script block, either as a single object or as an array. +You can also specify a return value using the `return` keyword. The `return` +keyword does not affect or suppress other output returned from your script +block. However, the `return` keyword exits the script block at that line. For +more information, see [about_Return](about_Return.md). + Like functions, a script block can include parameters. Use the Param keyword to assign named parameters, as shown in the following syntax: diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Switch.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Switch.md index 7e42ec071000..21140924c54f 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Switch.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Switch.md @@ -166,13 +166,11 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one |Parameter |Description | |------------|----------------------------------------------------------| -|**Wildcard**|Indicates that the condition is a wildcard string. If you | -| |you use **Wildcard**, **Regex** and **Exact** are ignored. | -| |Also, if the match clause is not a string, the parameter is| +|**Wildcard**|Indicates that the condition is a wildcard string. | +| |If the match clause is not a string, the parameter is| | |ignored. | |**Exact** |Indicates that the match clause, if it is a string, must | -| |match exactly. **Regex** and **Wildcard** are ignored. | -| |Also, if the match clause is not a string, this parameter | +| |match exactly. If the match clause is not a string, this parameter | | |is ignored. | |**CaseSensitive**|Performs a case-sensitive match. If the match clause is not| | |a string, this parameter is ignored. | @@ -181,9 +179,15 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one | |used. Each line of the file is read and evaluated by the | | |`Switch` statement. | |**Regex** |Performs regular expression matching of the value to the | -| |condition. **Wildcard** and **Exact** are ignored. Also, if the| +| |condition. If the| | |match clause is not a string, this parameter is ignored. | +> [!NOTE] +> When specifying conflicting values, like **Regex** and **Wildcard**, the last +> parameter specified takes precedence, and all conflicting parameters are ignored. +> Multiple instances of parameters are also permitted. However, only the +> last parameter used is effective. + In this example, there is no matching case so there is no output. ```powershell @@ -197,6 +201,27 @@ switch ("fourteen") } ``` +By adding the `Default` clause, you can perform an action when no other +conditions succeed. + +```powershell +switch ("fourteen") +{ + 1 {"It is one."; Break} + 2 {"It is two."; Break} + 3 {"It is three."; Break} + 4 {"It is four."; Break} + "fo*" {"That's too many."} + Default { + "No matches" + } +} +``` + +```Output +No matches +``` + For the word "fourteen" to match a case you must use the `-Wildcard` or `-Regex` parameter. @@ -231,28 +256,67 @@ switch -Regex ($target) user@contoso.com is an email address ``` -Multiple instances of **Regex**, **Wildcard**, or **Exact** are permitted. -However, only the last parameter used is effective. +A `Switch` statement condition may be either: + +- An expression whose value is compared to the input value +- A script block which should return `$true` if a condition is met. The + script block receives the current object to compare in the `$_` + automatic variable and is evaluated in its own scope. + +The action for each condition is independent of the actions in other +conditions. + +The following example demonstrates the use of script blocks as `Switch` +statement conditions. + +```powershell +switch ("Test") +{ + {$_ -is [String]} { + "Found a string" + } + "Test" { + "This executes as well" + } +} +``` + +```Output +Found a string +This executes as well +``` If the value matches multiple conditions, the action for each condition is executed. To change this behavior, use the `Break` or `Continue` keywords. -The Break keyword stops processing and exits the Switch statement. +The `Break` keyword stops processing and exits the `Switch` statement. The `Continue` keyword stops processing the current value, but continues processing any subsequent values. -If the condition is an expression or a script block, it is evaluated just -before it is compared to the value. The value is assigned to the `$_` -automatic variable and is available in the expression. The match succeeds -if the expression is true or matches the value. The expression is evaluated -in its own scope. +The following example processes an array of numbers and displays if they are +odd or even. Negative numbers are skipped with the `Continue` keyword. If a +non-number is encountered, execution is terminated with the `Break` keyword. -The `Default` keyword specifies a condition that is evaluated only when no -other conditions match the value. +```powershell +switch (1,4,-1,3,"Hello",2,1) +{ + {$_ -lt 0} { Continue } + {$_ -isnot [Int32]} { Break } + {$_ % 2} { + "$_ is Odd" + } + {-not ($_ % 2)} { + "$_ is Even" + } +} +``` -The action for each condition is independent of the actions in other -conditions. +```Output +1 is Odd +4 is Even +3 is Odd +``` ## SEE ALSO diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_pipelines.md index 1e43cd547d40..1fe7bb51eed0 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -5,7 +5,6 @@ locale: en-us keywords: powershell,cmdlet title: about_pipelines --- - # About Pipelines ## Short Description @@ -42,6 +41,7 @@ Here is a simple example. The following command gets the Notepad process and then stops it. For example, + ```powershell Get-Process notepad | Stop-Process ``` @@ -49,7 +49,7 @@ Get-Process notepad | Stop-Process The first command uses the `Get-Process` cmdlet to get an object representing the Notepad process. It uses a pipeline operator (`|`) to send the process object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice -that the `Stop-Process` command does not have a Name or ID parameter to +that the `Stop-Process` command does not have a **Name** or **ID** parameter to specify the process, because the specified process is submitted through the pipeline. @@ -120,8 +120,8 @@ tmp3.txt 114000 ## Using Pipelines The PowerShell cmdlets were designed to be used in pipelines. For example, you -can usually pipe the results of a Get cmdlet to an action cmdlet (such as a -Set, Start, Stop, or Rename cmdlet) for the same noun. +can usually pipe the results of a **Get** cmdlet to an action cmdlet (such as a +**Set**, **Start**, **Stop**, or **Rename** cmdlet) for the same noun. For example, you can pipe any service from the `Get-Service` cmdlet to the `Start-Service` or `Stop-Service` cmdlets (although disabled services cannot @@ -130,19 +130,21 @@ be restarted in this way). This command pipeline starts the WMI service on the computer: For example, + ```powershell Get-Service wmi | Start-Service ``` The cmdlets that get and set objects of the PowerShell providers, such as the -Item and ItemProperty cmdlets, are also designed to be used in pipelines. +**Item** and **ItemProperty** cmdlets, are also designed to be used in pipelines. For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. -This command adds a new registry entry, NoOfEmployees, with a value of 8124, -to the MyCompany registry key. +This command adds a new registry entry, **NoOfEmployees**, with a value of 8124, +to the **MyCompany** registry key. For example, + ```powershell Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 @@ -166,7 +168,7 @@ Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and `Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out cmdlets, such as `Out-Printer`. -For example, you can pipe the Winlogon process to the `Format-List` cmdlet to +For example, you can pipe the "Winlogon" process to the `Format-List` cmdlet to display all of the properties of the process in a list. For example, @@ -188,7 +190,7 @@ To do so, the PowerShell "parameter binding" component, which associates input objects with cmdlet parameters, tries to find a parameter that meets the following criteria: -- The parameter must accept input from a pipeline (not all do) +- The parameter must accept input from a pipeline (not all do). - The parameter must accept the type of object being sent or a type that the object can be converted to. - The parameter must not already be used in the command. @@ -222,7 +224,7 @@ Get-Service | Format-Table -Property name, dependentservices ``` is much like saving the service objects in a variable and using the -InputObject parameter of `Format-Table` to submit the service object. +**InputObject** parameter of `Format-Table` to submit the service object. For example, @@ -251,8 +253,45 @@ cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the process objects, and their properties and methods. -NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the -same type, it displays only one object type. +PowerShell automatically enumerates any type that implements the `IEnumerable` +interface and sends the members through the pipeline one at a time. The +exception is `[hashtable]`, which requires a call to the `GetEnumerator()` +method. + +In the example below, an array and a hashtable are piped to the `Measure-Object` +cmdlet, which counts the number of objects received from the pipeline. The array +has multiple members, and the hashtable has multiple key-value pairs. Only the +array is enumerated one at a time. + +```powershell +@(1,2,3) | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +```powershell +@{"One"=1;"Two"=2} | Measure-Object +``` + +```Output +Count : 1 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +> [!NOTE] +> `Get-Member` eliminates duplicates, so if the objects are all of the +> same type, it displays only one object type. In this case, `Get-Member` displays the properties and methods of each process object, that is, a System.Diagnostics.Process object. @@ -274,10 +313,10 @@ NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then -`Get-Member` receives an array of System.Diagnostics.Process objects as a +However, if you use the **InputObject** parameter of `Get-Member`, then +`Get-Member` receives an array of **System.Diagnostics.Process** objects as a single unit, and it displays the properties of an array of objects. (Note the -array symbol ([]) after the System.Object type name.) +array symbol (`[]`) after the **System.Object** type name.) For example, @@ -297,8 +336,8 @@ Clone Method System.Object Clone() ``` This result might not be what you intended, but after you understand it, you -can use it. For example, an array of process objects has a Count property that -you can use to count the number of processes on the computer. +can use it. For example, an array of process objects has a **Count** property +that you can use to count the number of processes on the computer. For example, @@ -370,7 +409,7 @@ This means that you can send objects (PsObjects) through the pipeline to the Cmdlets parameters can accept pipeline input in one of two different ways: -- ByValue: Parameters that accept input "by value" can accept piped objects +- **ByValue**: Parameters that accept input "by value" can accept piped objects that have the same .NET type as their parameter value or objects that can be converted to that type. @@ -378,7 +417,7 @@ Cmdlets parameters can accept pipeline input in one of two different ways: value. It can accept string objects or objects that can be converted to strings. -- ByPropertyName: Parameters that accept input "by property name" can accept +- **ByPropertyName**: Parameters that accept input "by property name" can accept piped objects only when a property of the object has the same name as the parameter. @@ -426,7 +465,7 @@ To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of PowerShell. The following command traces the Parameter Binding component while the command is processing. It uses the `-PSHost` parameter to display the results at the console and the `-filepath` command to send them to -the debug.txt file for later reference. +the `debug.txt` file for later reference. For example, @@ -484,7 +523,7 @@ Get-Help Move-ItemProperty -Parameter Destination ``` The results show that **Destination** takes pipeline input only "by property -name". That is, the piped object must have a property named Destination. +name". That is, the piped object must have a property named **Destination**. ``` -Destination @@ -507,8 +546,8 @@ For example, Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` -The output shows that the item is a Microsoft.Win32.RegistryKey that does not -have a Destination property. That explains why the command failed. +The output shows that the item is a **Microsoft.Win32.RegistryKey** that does +not have a **Destination** property. That explains why the command failed. To fix the command, we must specify the destination in the `Move-ItemProperty` cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name @@ -519,17 +558,19 @@ For example, ```powershell Get-Item -Path HKLM:\software\mycompany\design | -Move-ItemProperty -Dest HKLM:\software\mycompany\sales -Name product +Move-ItemProperty -Destination HKLM:\software\mycompany\sales -Name product ``` To verify that the command worked, use a `Get-ItemProperty` command: For example, + ```powershell -Get-Itemproperty HKLM:\software\mycompany\sales +Get-ItemProperty HKLM:\software\mycompany\sales ``` -The results show that the Product registry entry was moved to the Sales key. +The results show that the **Product** registry entry was moved to the **Sales** +key. ```Output PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa diff --git a/reference/5.1/Microsoft.PowerShell.Management/Copy-Item.md b/reference/5.1/Microsoft.PowerShell.Management/Copy-Item.md index b675117cb8ae..8945f1483a11 100644 --- a/reference/5.1/Microsoft.PowerShell.Management/Copy-Item.md +++ b/reference/5.1/Microsoft.PowerShell.Management/Copy-Item.md @@ -1,5 +1,5 @@ --- -ms.date: 10/18/2018 +ms.date: 5/30/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -36,9 +36,9 @@ Copy-Item -LiteralPath [[-Destination] ] [-Container] [-Force The `Copy-Item` cmdlet copies an item from one location to another location in the same namespace. For instance, it can copy a file to a folder, but it cannot copy a file to a certificate drive. -This cmdlet does not cut or delete the items being copied. -The particular items that the cmdlet can copy depend on the PowerShell provider that exposes the item. -For instance, it can copy files and directories in a file system drive and registry keys and entries in the registry drive. +This cmdlet does not cut or delete the items being copied. The particular items that the cmdlet can +copy depend on the PowerShell provider that exposes the item. For instance, it can copy files and +directories in a file system drive and registry keys and entries in the registry drive. This cmdlet can copy and rename items in the same command. To rename an item, enter the new name in the value of the **Destination** parameter. @@ -48,7 +48,7 @@ To rename an item and not copy it, use the `Rename-Item` cmdlet. ### Example 1: Copy a file to the specified directory -This command copies the "mar1604.log.txt" file to the "C:\Presentation" directory. +This command copies the `mar1604.log.txt` file to the `C:\Presentation` directory. The command does not delete the original file. ```powershell @@ -58,17 +58,19 @@ Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination "C:\Presentation" ### Example 2: Copy the contents of a directory to another directory This command copies the entire contents of the "Logfiles" directory into the "Drawings" directory. -If the "LogFiles" directory contains files in subdirectories, those subdirectories are copied with their file trees intact. -The **Container** parameter is set to "true" by default. -This preserves the directory structure. ```powershell Copy-Item "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse ``` +If the "LogFiles" directory contains files in subdirectories, those subdirectories are copied with +their file trees intact. The **Container** parameter is set to "true" by default. + +This preserves the directory structure. + ### Example 3: Copy the contents of a directory to another directory and create the destination directory if it does not exist -This command copies the contents of the "C:\Logfiles" directory to the "C:\Drawings\Logs" directory. +This command copies the contents of the `C:\Logfiles` directory to the `C:\Drawings\Logs` directory. It creates the "\Logs" subdirectory if it does not already exist. ```powershell @@ -77,8 +79,10 @@ Copy-Item C:\Logfiles -Destination C:\Drawings\Logs -Recurse ### Example 4: Copy a file to the specified directory and rename the file -This command uses the `Copy-Item` cmdlet to copy the "Get-Widget.ps1" script from the "\\\\Server01\Share" directory to the "\\\\Server12\ScriptArchive" directory. -As part of the copy operation, the command also changes the item name from "Get-Widget.ps1" to "Get-Widget.ps1.txt", so it can be attached to email messages. +This command uses the `Copy-Item` cmdlet to copy the `Get-Widget.ps1` script from the +`\\Server01\Share` directory to the `\\Server12\ScriptArchive` directory. +As part of the copy operation, the command also changes the item name from `Get-Widget.ps1` to +`Get-Widget.ps1.txt`, so it can be attached to email messages. ```powershell Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchive\Get-Widget.ps1.txt" @@ -86,10 +90,12 @@ Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchi ### Example 5: Copy a file to a remote computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFu" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy "test.log" from the "D:\Folder001" folder to the "C:\Folder001_Copy" folder on the remote computer using the session information stored in the `$Session` variable. -This command does not delete the original file. +The second command uses the `Copy-Item` cmdlet to copy `test.log` from the `D:\Folder001` folder to +the `C:\Folder001_Copy` folder on the remote computer using the session information stored in the +`$Session` variable. This command does not delete the original file. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul" @@ -98,10 +104,12 @@ Copy-Item "D:\Folder001\test.log" -Destination "C:\Folder001_Copy\" -ToSession $ ### Example 6: Copy the entire contents of a folder to a remote computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +`Contoso\PattiFul` and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy the entire contents from the "D:\Folder002" folder to the "C:\Folder002_Copy" directory on the remote computer using the session information stored in the `$Session` variable. -The subfolders are copied with their file trees intact. +The second command uses the `Copy-Item` cmdlet to copy the entire contents from the `D:\Folder002` +folder to the `C:\Folder002_Copy` directory on the remote computer using the session information +stored in the `$Session` variable. The subfolders are copied with their file trees intact. ```powershell $Session = New-PSSession -ComputerName "Server02" -Credential "Contoso\PattiFul" @@ -110,11 +118,14 @@ Copy-Item "D:\Folder002\" -Destination "C:\Folder002_Copy\" -ToSession $Session ### Example 7: Recursively copy the entire contents of a folder to a remote computer -The first command creates a session to the remote computer named Server01 with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named Server01 with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy the entire contents from the "D:\Folder003" folder to the "C:\Folder003_Copy" directory on the remote computer using the session information stored in the `$Session` variable. -The subfolders are copied with their file trees intact. -Since this command uses the **Recurse** parameter, the operation creates the "Folder003_Copy" folder if it does not already exist. +The second command uses the `Copy-Item` cmdlet to copy the entire contents from the `D:\Folder003` +folder to the `C:\Folder003_Copy` directory on the remote computer using the session information +stored in the `$Session` variable. The subfolders are copied with their file trees intact. +Since this command uses the **Recurse** parameter, the operation creates the "Folder003_Copy" folder +if it does not already exist. ```powershell $Session = New-PSSession -ComputerName "Server04" -Credential "Contoso\PattiFul" @@ -123,10 +134,14 @@ Copy-Item "D:\Folder003\" -Destination "C:\Folder003_Copy\" -ToSession $Session ### Example 8: Copy a file to a remote computer and then rename the file -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy "scriptingexample.ps1" from the "D:\Folder004" folder to the "C:\Folder004_Copy" folder on the remote computer using the session information stored in the `$Session` variable. -As part of the copy operation, the command also changes the item name from "scriptingexample.ps1" to "scriptingexample_copy.ps1", so it can be attached to email messages. +The second command uses the `Copy-Item` cmdlet to copy `scriptingexample.ps1` from the +`D:\Folder004` folder to the "C:\Folder004_Copy" folder on the remote computer using the session +information stored in the `$Session` variable. +As part of the copy operation, the command also changes the item name from `scriptingexample.ps1` to +`scriptingexample_copy.ps1`, so it can be attached to email messages. This command does not delete the original file. ```powershell @@ -136,10 +151,12 @@ Copy-Item "D:\Folder004\scriptingexample.ps1" -Destination "C:\Folder004_Copy\sc ### Example 9: Copy a remote file to the local computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy test.log from the remote "C:\MyRemoteData\" to the local "D:\MyLocalData" folder using the session information stored in the `$Session` variable. -This command does not delete the original file. +The second command uses the `Copy-Item` cmdlet to copy test.log from the remote `C:\MyRemoteData\` +to the local `D:\MyLocalData` folder using the session information stored in the `$Session` +variable. This command does not delete the original file. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul" @@ -148,10 +165,14 @@ Copy-Item "C:\MyRemoteData\test.log" -Destination "D:\MyLocalData\" -FromSession ### Example 10: Copy the entire contents of a remote folder to the local computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy the entire contents from the remote "C:\MyRemoteData\scripts" folder to the local "D:\MyLocalData" folder using the session information stored in the `$Session` variable. -If the scripts folder contains files in subfolders, those subfolders are copied with their file trees intact. +The second command uses the `Copy-Item` cmdlet to copy the entire contents from the remote +`C:\MyRemoteData\scripts` folder to the local `D:\MyLocalData` folder using the session information +stored in the `$Session` variable. +If the scripts folder contains files in subfolders, those subfolders are copied with their file +trees intact. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul" @@ -160,10 +181,15 @@ Copy-Item "C:\MyRemoteData\scripts" -Destination "D:\MyLocalData\" -FromSession ### Example 11: Recursively copy the entire contents of a remote folder to the local computer -The first command creates a session to the remote computer named "Server01" with the credential of "Contoso\PattiFul" and stores the results in the variable named `$Session`. +The first command creates a session to the remote computer named "Server01" with the credential of +"Contoso\PattiFul" and stores the results in the variable named `$Session`. -The second command uses the `Copy-Item` cmdlet to copy the entire contents from the remote "C:\MyRemoteData\scripts" folder to the local "D:\MyLocalData\scripts" folder using the session information stored in the `$Session` variable. -Since this command uses the **Recurse** parameter, the operation creates the scripts folder if it does not already exist. If the scripts folder contains files in subfolders, those subfolders are copied with their file trees intact. +The second command uses the `Copy-Item` cmdlet to copy the entire contents from the remote +`C:\MyRemoteData\scripts` folder to the local `D:\MyLocalData\scripts` folder using the session +information stored in the `$Session` variable. +Since this command uses the **Recurse** parameter, the operation creates the scripts folder if it +does not already exist. If the scripts folder contains files in subfolders, those subfolders are +copied with their file trees intact. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\PattiFul" @@ -183,21 +209,17 @@ Aliases: Required: False Position: Named -Default value: None +Default value: True Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential -Specifies a user account that has permission to perform this action. -The default is the current user. - -Type a user name, such as "User01" or "Domain01\User01", or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. -If you type a user name, you are prompted for a password. - -> [!WARNING] -> This parameter is not supported by any providers installed with Windows PowerShell. +> [!NOTE] +> This parameter is not supported by any providers installed with PowerShell. +> To impersonate another user, or elevate your credentials when running this cmdlet, +> use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: PSCredential @@ -214,7 +236,9 @@ Accept wildcard characters: False ### -Destination Specifies the path to the new location. -To rename a copied item, include the new name in the value. +The default is the current directory. + +To rename the item being copied, specify a new name in the value of the **Destination** parameter. ```yaml Type: String @@ -230,10 +254,11 @@ Accept wildcard characters: False ### -Exclude -Specifies, as a string array, an item or items that this cmdlet excludes from the operation. -The value of this parameter qualifies the **Path** parameter. -Enter a path element or pattern, such as "*.txt". -Wildcard characters are permitted. +Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value +of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as +`*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the +command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character +specifies the contents of the `C:\Windows` directory. ```yaml Type: String[] @@ -249,11 +274,11 @@ Accept wildcard characters: True ### -Filter -Specifies a filter in the format or language of the provider. -The value of this parameter qualifies the **Path** parameter. - -The syntax of the filter, including the use of wildcard characters, depends on the provider. -Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. +Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) +provider is the only installed PowerShell provider that supports the use of filters. You can find +the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). +Filters are more efficient than other parameters, because the provider applies them when the cmdlet +gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: String @@ -269,7 +294,8 @@ Accept wildcard characters: True ### -Force -Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a read-only file or alias. +Indicates that this cmdlet copies items that cannot otherwise be changed, such as copying over a +read-only file or alias. ```yaml Type: SwitchParameter @@ -278,7 +304,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -286,7 +312,8 @@ Accept wildcard characters: False ### -FromSession Specifies the **PSSession** object from which a remote file is being copied. -When you use this parameter, the *Path* and *LiteralPath* parameters refer to the local path on the remote machine. +When you use this parameter, the *Path* and *LiteralPath* parameters refer to the local path on the +remote machine. ```yaml Type: PSSession @@ -302,10 +329,11 @@ Accept wildcard characters: False ### -Include -Specifies, as a string array, an item or items that this cmdlet includes in the operation. -The value of this parameter qualifies the **Path** parameter. -Enter a path element or pattern, such as "*.txt". -Wildcard characters are permitted. +Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value +of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as +`"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the +command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character +specifies the contents of the `C:\Windows` directory. ```yaml Type: String[] @@ -316,16 +344,17 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -LiteralPath -Specifies a path to the item. -Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it is typed. -No characters are interpreted as wildcards. -If the path includes escape characters, enclose it in single quotation marks. -Single quotation marks tell PowerShell not to interpret any characters as escape sequences. +Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is +typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose +it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters +as escape sequences. + +For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: String[] @@ -351,7 +380,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -359,6 +388,7 @@ Accept wildcard characters: False ### -Path Specifies, as a string array, the path to the items to copy. +Wildcard characters are permitted. ```yaml Type: String[] @@ -369,7 +399,7 @@ Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -Recurse @@ -383,7 +413,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -391,7 +421,8 @@ Accept wildcard characters: False ### -ToSession Specifies the **PSSession** object to which a remote file is being copied. -When you use this parameter, the *Path* and *LiteralPath* parameters refer to the local path on the remote machine. +When you use this parameter, the **Path** and **LiteralPath** parameters refer to the local path on the +remote machine. ```yaml Type: PSSession @@ -424,6 +455,7 @@ Accept wildcard characters: False ``` ### -Confirm + Prompts you for confirmation before running the cmdlet. ```yaml @@ -457,7 +489,10 @@ Accept wildcard characters: False ### CommonParameters -This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). +This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, +`-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, +`-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see +[about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS @@ -469,8 +504,8 @@ You can pipe a string that contains a path to this cmdlet. ### None or an object representing the copied item. -When you use the *PassThru* parameter, this cmdlet returns an object that represents the copied item. -Otherwise, this cmdlet does not generate any output. +When you use the *PassThru* parameter, this cmdlet returns an object that represents the copied +item. Otherwise, this cmdlet does not generate any output. ## NOTES @@ -496,4 +531,6 @@ For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/a [Set-Item](Set-Item.md) -[Get-PSProvider](Get-PSProvider.md) \ No newline at end of file +[Get-PSProvider](Get-PSProvider.md) + +[about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Functions.md b/reference/6/Microsoft.PowerShell.Core/About/about_Functions.md index a90c198cdd4a..9425374767e4 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Functions.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Functions.md @@ -29,7 +29,10 @@ positional, switch, or dynamic parameters. Function parameters can be read from the command line or from the pipeline. Functions can return values that can be displayed, assigned to variables, or -passed to other functions or cmdlets. +passed to other functions or cmdlets. You can also specify a return value using +the `return` keyword. The `return` keyword does not affect or suppress other +output returned from your function. However, the `return` keyword exits the +function at that line. For more information, see [about_Return](about_Return.md). The function's statement list can contain different types of statement lists with the keywords `Begin`, `Process`, and `End`. These statement lists diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Return.md b/reference/6/Microsoft.PowerShell.Core/About/about_Return.md index 8276ef332218..55d9b5f6455c 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Return.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Return.md @@ -8,6 +8,7 @@ title: about_Return # About Return ## Short description + Exits the current scope, which can be a function, script, or script block. ## Long description @@ -109,14 +110,17 @@ $a = calculation 14 ``` The "Please wait. Working on calculation..." string is not displayed. Instead, -it is assigned to the `$a` variable. +it is assigned to the `$a` variable, as in the following example: -```output -C:\PS> $a +``` +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. + If you would like to display a message within your function, beginning in PowerShell 5.0, you can use the `Information` stream. The code below corrects the above example using the `Write-Information` cmdlet with a @@ -140,6 +144,87 @@ C:\PS> $a 87 ``` +### Return values and the Pipeline + +When you return a collection from your script block or function, PowerShell +automatically unrolls the members and passes them one at a time through the +pipeline. This is due to PowerShell's one-at-a-time processing. For more +information, see [about_pipelines](about_pipelines.md). + +This concept is illustrated by the following sample function that returns an +array of numbers. The output from the function is piped to the `Measure-Object` +cmdlet which counts the number of objects in the pipeline. + +```powershell +function Test-Return +{ + $array = 1,2,3 + return $array +} +Test-Return | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +To force a script block or function to return collection as a single +object to the pipeline, use one of the following two methods: + +- Unary array expression + + Utilizing a unary expression you can send your return value down the pipeline + as a single object as illustrated by the following example. + + ```powershell + function Test-Return + { + $array = 1,2,3 + return (, $array) + } + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + +- `Write-Output` with **NoEnumerate** parameter. + + You can also use the `Write-Output` cmdlet with the **NoEnumerate** + parameter. The example below uses the `Measure-Object` cmdlet to count the + objects sent to the pipeline from the sample function by the `return` + keyword. + + ```powershell + function Test-Return + { + $array = 1, 2, 3 + return Write-Output -NoEnumerate $array + } + + Test-Return | Measure-Object + ``` + + ```Output + Count : 1 + Average : + Sum : + Maximum : + Minimum : + Property : + ``` + ## See also [about_Language_Keywords](about_Language_Keywords.md) diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Script_Blocks.md b/reference/6/Microsoft.PowerShell.Core/About/about_Script_Blocks.md index 7728f9ba5405..973338103c5a 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Script_Blocks.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Script_Blocks.md @@ -8,6 +8,7 @@ title: about_Script_Blocks # About Script Blocks ## Short description + Defines what a script block is and explains how to use script blocks in the PowerShell programming language. @@ -27,6 +28,11 @@ the following syntax: A script block returns the output of all the commands in the script block, either as a single object or as an array. +You can also specify a return value using the `return` keyword. The `return` +keyword does not affect or suppress other output returned from your script +block. However, the `return` keyword exits the script block at that line. For +more information, see [about_Return](about_Return.md). + Like functions, a script block can include parameters. Use the Param keyword to assign named parameters, as shown in the following syntax: diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_Switch.md b/reference/6/Microsoft.PowerShell.Core/About/about_Switch.md index 7e42ec071000..21140924c54f 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_Switch.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_Switch.md @@ -166,13 +166,11 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one |Parameter |Description | |------------|----------------------------------------------------------| -|**Wildcard**|Indicates that the condition is a wildcard string. If you | -| |you use **Wildcard**, **Regex** and **Exact** are ignored. | -| |Also, if the match clause is not a string, the parameter is| +|**Wildcard**|Indicates that the condition is a wildcard string. | +| |If the match clause is not a string, the parameter is| | |ignored. | |**Exact** |Indicates that the match clause, if it is a string, must | -| |match exactly. **Regex** and **Wildcard** are ignored. | -| |Also, if the match clause is not a string, this parameter | +| |match exactly. If the match clause is not a string, this parameter | | |is ignored. | |**CaseSensitive**|Performs a case-sensitive match. If the match clause is not| | |a string, this parameter is ignored. | @@ -181,9 +179,15 @@ conditions. It is equivalent to an `Else` clause in an `If` statement. Only one | |used. Each line of the file is read and evaluated by the | | |`Switch` statement. | |**Regex** |Performs regular expression matching of the value to the | -| |condition. **Wildcard** and **Exact** are ignored. Also, if the| +| |condition. If the| | |match clause is not a string, this parameter is ignored. | +> [!NOTE] +> When specifying conflicting values, like **Regex** and **Wildcard**, the last +> parameter specified takes precedence, and all conflicting parameters are ignored. +> Multiple instances of parameters are also permitted. However, only the +> last parameter used is effective. + In this example, there is no matching case so there is no output. ```powershell @@ -197,6 +201,27 @@ switch ("fourteen") } ``` +By adding the `Default` clause, you can perform an action when no other +conditions succeed. + +```powershell +switch ("fourteen") +{ + 1 {"It is one."; Break} + 2 {"It is two."; Break} + 3 {"It is three."; Break} + 4 {"It is four."; Break} + "fo*" {"That's too many."} + Default { + "No matches" + } +} +``` + +```Output +No matches +``` + For the word "fourteen" to match a case you must use the `-Wildcard` or `-Regex` parameter. @@ -231,28 +256,67 @@ switch -Regex ($target) user@contoso.com is an email address ``` -Multiple instances of **Regex**, **Wildcard**, or **Exact** are permitted. -However, only the last parameter used is effective. +A `Switch` statement condition may be either: + +- An expression whose value is compared to the input value +- A script block which should return `$true` if a condition is met. The + script block receives the current object to compare in the `$_` + automatic variable and is evaluated in its own scope. + +The action for each condition is independent of the actions in other +conditions. + +The following example demonstrates the use of script blocks as `Switch` +statement conditions. + +```powershell +switch ("Test") +{ + {$_ -is [String]} { + "Found a string" + } + "Test" { + "This executes as well" + } +} +``` + +```Output +Found a string +This executes as well +``` If the value matches multiple conditions, the action for each condition is executed. To change this behavior, use the `Break` or `Continue` keywords. -The Break keyword stops processing and exits the Switch statement. +The `Break` keyword stops processing and exits the `Switch` statement. The `Continue` keyword stops processing the current value, but continues processing any subsequent values. -If the condition is an expression or a script block, it is evaluated just -before it is compared to the value. The value is assigned to the `$_` -automatic variable and is available in the expression. The match succeeds -if the expression is true or matches the value. The expression is evaluated -in its own scope. +The following example processes an array of numbers and displays if they are +odd or even. Negative numbers are skipped with the `Continue` keyword. If a +non-number is encountered, execution is terminated with the `Break` keyword. -The `Default` keyword specifies a condition that is evaluated only when no -other conditions match the value. +```powershell +switch (1,4,-1,3,"Hello",2,1) +{ + {$_ -lt 0} { Continue } + {$_ -isnot [Int32]} { Break } + {$_ % 2} { + "$_ is Odd" + } + {-not ($_ % 2)} { + "$_ is Even" + } +} +``` -The action for each condition is independent of the actions in other -conditions. +```Output +1 is Odd +4 is Even +3 is Odd +``` ## SEE ALSO diff --git a/reference/6/Microsoft.PowerShell.Core/About/about_pipelines.md b/reference/6/Microsoft.PowerShell.Core/About/about_pipelines.md index 165b448c6cb3..1fe7bb51eed0 100644 --- a/reference/6/Microsoft.PowerShell.Core/About/about_pipelines.md +++ b/reference/6/Microsoft.PowerShell.Core/About/about_pipelines.md @@ -8,6 +8,7 @@ title: about_pipelines # About Pipelines ## Short Description + Combining commands into pipelines in the PowerShell ## Long Description @@ -40,6 +41,7 @@ Here is a simple example. The following command gets the Notepad process and then stops it. For example, + ```powershell Get-Process notepad | Stop-Process ``` @@ -47,7 +49,7 @@ Get-Process notepad | Stop-Process The first command uses the `Get-Process` cmdlet to get an object representing the Notepad process. It uses a pipeline operator (`|`) to send the process object to the `Stop-Process` cmdlet, which stops the Notepad process. Notice -that the `Stop-Process` command does not have a Name or ID parameter to +that the `Stop-Process` command does not have a **Name** or **ID** parameter to specify the process, because the specified process is submitted through the pipeline. @@ -118,8 +120,8 @@ tmp3.txt 114000 ## Using Pipelines The PowerShell cmdlets were designed to be used in pipelines. For example, you -can usually pipe the results of a Get cmdlet to an action cmdlet (such as a -Set, Start, Stop, or Rename cmdlet) for the same noun. +can usually pipe the results of a **Get** cmdlet to an action cmdlet (such as a +**Set**, **Start**, **Stop**, or **Rename** cmdlet) for the same noun. For example, you can pipe any service from the `Get-Service` cmdlet to the `Start-Service` or `Stop-Service` cmdlets (although disabled services cannot @@ -128,19 +130,21 @@ be restarted in this way). This command pipeline starts the WMI service on the computer: For example, + ```powershell Get-Service wmi | Start-Service ``` The cmdlets that get and set objects of the PowerShell providers, such as the -Item and ItemProperty cmdlets, are also designed to be used in pipelines. +**Item** and **ItemProperty** cmdlets, are also designed to be used in pipelines. For example, you can pipe the results of a `Get-Item` or `Get-ChildItem` command in the PowerShell registry provider to the `New-ItemProperty` cmdlet. -This command adds a new registry entry, NoOfEmployees, with a value of 8124, -to the MyCompany registry key. +This command adds a new registry entry, **NoOfEmployees**, with a value of 8124, +to the **MyCompany** registry key. For example, + ```powershell Get-Item -Path HKLM:\Software\MyCompany | New-ItemProperty -Name NoOfEmployees -Value 8124 @@ -164,7 +168,7 @@ Also, you can pipe any objects to the formatting cmdlets, such as `Format-List` and `Format-Table`, the Export cmdlets, such as `Export-Clixml` and `Export-CSV`, and the Out cmdlets, such as `Out-Printer`. -For example, you can pipe the Winlogon process to the `Format-List` cmdlet to +For example, you can pipe the "Winlogon" process to the `Format-List` cmdlet to display all of the properties of the process in a list. For example, @@ -186,7 +190,7 @@ To do so, the PowerShell "parameter binding" component, which associates input objects with cmdlet parameters, tries to find a parameter that meets the following criteria: -- The parameter must accept input from a pipeline (not all do) +- The parameter must accept input from a pipeline (not all do). - The parameter must accept the type of object being sent or a type that the object can be converted to. - The parameter must not already be used in the command. @@ -220,7 +224,7 @@ Get-Service | Format-Table -Property name, dependentservices ``` is much like saving the service objects in a variable and using the -InputObject parameter of `Format-Table` to submit the service object. +**InputObject** parameter of `Format-Table` to submit the service object. For example, @@ -249,8 +253,45 @@ cmdlet to the `Get-Member` cmdlet, PowerShell sends each process object, one at a time, to `Get-Member`. `Get-Member` displays the .NET class (type) of the process objects, and their properties and methods. -NOTE: `Get-Member` eliminates duplicates, so if the objects are all of the -same type, it displays only one object type. +PowerShell automatically enumerates any type that implements the `IEnumerable` +interface and sends the members through the pipeline one at a time. The +exception is `[hashtable]`, which requires a call to the `GetEnumerator()` +method. + +In the example below, an array and a hashtable are piped to the `Measure-Object` +cmdlet, which counts the number of objects received from the pipeline. The array +has multiple members, and the hashtable has multiple key-value pairs. Only the +array is enumerated one at a time. + +```powershell +@(1,2,3) | Measure-Object +``` + +```Output +Count : 3 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +```powershell +@{"One"=1;"Two"=2} | Measure-Object +``` + +```Output +Count : 1 +Average : +Sum : +Maximum : +Minimum : +Property : +``` + +> [!NOTE] +> `Get-Member` eliminates duplicates, so if the objects are all of the +> same type, it displays only one object type. In this case, `Get-Member` displays the properties and methods of each process object, that is, a System.Diagnostics.Process object. @@ -272,10 +313,10 @@ NPM AliasProperty NPM = NonpagedSystemMemorySize ... ``` -However, if you use the InputObject parameter of `Get-Member`, then -`Get-Member` receives an array of System.Diagnostics.Process objects as a +However, if you use the **InputObject** parameter of `Get-Member`, then +`Get-Member` receives an array of **System.Diagnostics.Process** objects as a single unit, and it displays the properties of an array of objects. (Note the -array symbol ([]) after the System.Object type name.) +array symbol (`[]`) after the **System.Object** type name.) For example, @@ -295,8 +336,8 @@ Clone Method System.Object Clone() ``` This result might not be what you intended, but after you understand it, you -can use it. For example, an array of process objects has a Count property that -you can use to count the number of processes on the computer. +can use it. For example, an array of process objects has a **Count** property +that you can use to count the number of processes on the computer. For example, @@ -368,7 +409,7 @@ This means that you can send objects (PsObjects) through the pipeline to the Cmdlets parameters can accept pipeline input in one of two different ways: -- ByValue: Parameters that accept input "by value" can accept piped objects +- **ByValue**: Parameters that accept input "by value" can accept piped objects that have the same .NET type as their parameter value or objects that can be converted to that type. @@ -376,7 +417,7 @@ Cmdlets parameters can accept pipeline input in one of two different ways: value. It can accept string objects or objects that can be converted to strings. -- ByPropertyName: Parameters that accept input "by property name" can accept +- **ByPropertyName**: Parameters that accept input "by property name" can accept piped objects only when a property of the object has the same name as the parameter. @@ -424,7 +465,7 @@ To investigate, use the `Trace-Command` cmdlet to trace the Parameter Binding component of PowerShell. The following command traces the Parameter Binding component while the command is processing. It uses the `-PSHost` parameter to display the results at the console and the `-filepath` command to send them to -the debug.txt file for later reference. +the `debug.txt` file for later reference. For example, @@ -482,7 +523,7 @@ Get-Help Move-ItemProperty -Parameter Destination ``` The results show that **Destination** takes pipeline input only "by property -name". That is, the piped object must have a property named Destination. +name". That is, the piped object must have a property named **Destination**. ``` -Destination @@ -505,8 +546,8 @@ For example, Get-Item -Path HKLM:\software\mycompany\sales | Get-Member ``` -The output shows that the item is a Microsoft.Win32.RegistryKey that does not -have a Destination property. That explains why the command failed. +The output shows that the item is a **Microsoft.Win32.RegistryKey** that does +not have a **Destination** property. That explains why the command failed. To fix the command, we must specify the destination in the `Move-ItemProperty` cmdlet. We can use a `Get-ItemProperty` command to get the path, but the name @@ -517,17 +558,19 @@ For example, ```powershell Get-Item -Path HKLM:\software\mycompany\design | -Move-ItemProperty -Dest HKLM:\software\mycompany\sales -Name product +Move-ItemProperty -Destination HKLM:\software\mycompany\sales -Name product ``` To verify that the command worked, use a `Get-ItemProperty` command: For example, + ```powershell -Get-Itemproperty HKLM:\software\mycompany\sales +Get-ItemProperty HKLM:\software\mycompany\sales ``` -The results show that the Product registry entry was moved to the Sales key. +The results show that the **Product** registry entry was moved to the **Sales** +key. ```Output PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\softwa diff --git a/reference/6/Microsoft.PowerShell.Management/Copy-Item.md b/reference/6/Microsoft.PowerShell.Management/Copy-Item.md index 3ba033bdcd0f..c53ce3ca1377 100644 --- a/reference/6/Microsoft.PowerShell.Management/Copy-Item.md +++ b/reference/6/Microsoft.PowerShell.Management/Copy-Item.md @@ -1,5 +1,5 @@ --- -ms.date: 5/14/2019 +ms.date: 5/30/2019 schema: 2.0.0 locale: en-us keywords: powershell,cmdlet @@ -208,7 +208,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: True Accept pipeline input: False Accept wildcard characters: False ``` @@ -303,7 +303,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -379,7 +379,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` @@ -412,7 +412,7 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` diff --git a/reference/6/PowerShellGet/Install-Module.md b/reference/6/PowerShellGet/Install-Module.md index 9592cd011744..e251562f48e9 100644 --- a/reference/6/PowerShellGet/Install-Module.md +++ b/reference/6/PowerShellGet/Install-Module.md @@ -360,13 +360,11 @@ the computer: `$home\Documents\PowerShell\Modules` -When no **Scope** is defined, the default is set based on the current session: +When no **Scope** is defined, the default is set based on the PowerShellGet version. -- For an elevated PowerShell session, **Scope** defaults to **AllUsers**. -- For non-elevated PowerShell sessions in [PowerShellGet versions 2.0.0](https://www.powershellgallery.com/packages/PowerShellGet) - and above, the **Scope** is **CurrentUser**. -- For non-elevated PowerShell sessions in PowerShellGet versions 1.6.7 and earlier, **Scope** is - undefined, and `Install-Module` fails. +- In PowerShellGet versions 2.0.0 and above, the default is **CurrentUser**, which does not require + elevation for install. +- In PowerShellGet 1.x versions, the default is **AllUsers**, which requires elevation for install. ```yaml Type: String @@ -498,4 +496,4 @@ the **RequiredVersion** value. [Uninstall-Module](Uninstall-Module.md) -[Update-Module](Update-Module.md) \ No newline at end of file +[Update-Module](Update-Module.md)