Updates from: 06/23/2021 03:18:52
Service Microsoft Docs article Related commit history on GitHub Change details
CimCmdlets Cimcmdlets (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/CimCmdlets/CimCmdlets.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390758
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: fb6cc51d-c096-4b38-b78d-0fed6277096a Module Name: CimCmdlets
ISE ISE (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/ISE/ISE.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390780
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: bae93d8e-782c-4a23-b87f-8699bfc17ee0 Module Name: ISE
Microsoft.PowerShell.Archive Microsoft.Powershell.Archive (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Archive/Microsoft.PowerShell.Archive.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?LinkID=393254
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: eb74e8da-9ae2-482a-a648-e96550fb8733 Module Name: Microsoft.PowerShell.Archive
Microsoft.PowerShell.Core About Enum (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/About/about_Enum.md
---
-description: The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list.
-keywords: powershell,cmdlet
+description: The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list.
Locale: en-US Previously updated : 11/27/2017 Last updated : 06/21/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_enum?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Enum ---- # about_Enum ## SHORT DESCRIPTION- The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list.
The `GetEnumNames()` method returns the list of the labels for the enumeration.
```powershell [MediaTypes].GetEnumNames()
+```
+
+```Output
unknown music mp3
The `GetEnumValues()` method returns the list of the values for the enumeration.
```powershell [MediaTypes].GetEnumValues()
+```
+
+```Output
unknown music mp3
avi
m4v ```
-**Note**: GetEnumNames() and GetEnumValues() seem to return the same results.
-However, internally, PowerShell is changing values into labels. Read the list
-carefully and you'll notice that `oga` and `mogg` are mentioned under the 'Get
-Names' results, but not under the 'Get Values' similar output for `jpg`,
-`jpeg`, and `mpg`, `mpeg`.
+> [!NOTE]
+> `GetEnumNames()` and `GetEnumValues()` seem to return the same results; a
+> list of named values. However, internally, `GetEnumValues()` enumerates the
+> values, then maps values into names. Read the list carefully and you'll
+> notice that `ogg`, `oga`, and `mogg` appear in the output of
+> `GetEnumNames()`, but the output of `GetEnumValues()` only shows `oga`. The
+> same thing happens for `jpg`, `jpeg`, and `mpg`, `mpeg`.
+
+The `GetEnumName()` method can be used to get a name associated with a specific
+value. If there are multiple names associated with a value, the method returns
+the alphabetically-first name.
```powershell [MediaTypes].GetEnumName(15) oga
+```
+
+The following example shows how to map each name to its value.
+```powershell
[MediaTypes].GetEnumNames() | ForEach-Object { "{0,-10} {1}" -f $_,[int]([MediaTypes]::$_) }
+```
+
+```Output
unknown 0 music 10 mp3 11
In the following example the *FileAttributes* enumeration is created.
"file2 attributes are: $file2" ```
-```output
+```Output
file1 attributes are: Archive, Compressed, Device file2 attributes are: Device, Directory, Encrypted ```
To test that a specific is set, you can use the binary comparison operator
`-band`. In this example, we test for the **Device** and the **Archive** attributes in the value of `$file2`.
-```
+```powershell
PS > ($file2 -band [FileAttributes]::Device) -eq [FileAttributes]::Device True
Microsoft.PowerShell.Core About Hash Tables (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/About/about_Hash_Tables.md
--- description: Describes how to create, use, and sort hash tables in PowerShell.
-keywords: powershell,cmdlet
Locale: en-US Previously updated : 11/28/2017 Last updated : 06/21/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_hash_tables?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Hash Tables --- # about_Hash_Tables
-## SHORT DESCRIPTION
+## Short description
Describes how to create, use, and sort hash tables in PowerShell.
-## LONG DESCRIPTION
+## Long description
A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more key/value pairs. For example, a hash table might contain a series of IP addresses and computer names, where the IP addresses are the keys and the computer names are the values, or vice versa.
-In PowerShell, each hash table is a Hashtable (System.Collections.Hashtable)
-object. You can use the properties and methods of Hashtable objects in
-PowerShell.
+In PowerShell, each hash table is a **Hashtable**
+(**System.Collections.Hashtable**) object. You can use the properties and
+methods of Hashtable objects in PowerShell.
Beginning in PowerShell 3.0, you can use the [ordered] attribute to create an
-ordered dictionary (System.Collections.Specialized.OrderedDictionary) in
+ordered dictionary (**System.Collections.Specialized.OrderedDictionary**) in
PowerShell. Ordered dictionaries differ from hash tables in that the keys always appear in
nested hash tables, in which the value of a key is another hash table.
Hash tables are frequently used because they are very efficient for finding and retrieving data. You can use hash tables to store lists and to create calculated properties in PowerShell. And, PowerShell has a cmdlet,
-ConvertFrom-StringData, that converts strings to a hash table.
+`ConvertFrom-StringData`, that converts strings to a hash table.
-### Syntax
+## Syntax
The syntax of a hash table is as follows:
The syntax of an ordered dictionary is as follows:
The [ordered] attribute was introduced in PowerShell 3.0.
-### Creating Hash Tables
+## Creating Hash Tables
To create a hash table, follow these guidelines: -- Begin the hash table with an at sign (@).-- Enclose the hash table in braces ({}).
+- Begin the hash table with an at sign (`@`).
+- Enclose the hash table in braces (`{}`).
- Enter one or more key/value pairs for the content of the hash table.-- Use an equal sign (=) to separate each key from its value.-- Use a semicolon (;) or a line break to separate the key/value pairs.-- Key that contains spaces must be enclosed in quotation marks. Values must be
+- Use an equal sign (`=`) to separate each key from its value.
+- Use a semicolon (`;`) or a line break to separate the key/value pairs.
+- Keys that contain spaces must be enclosed in quotation marks. Values must be
valid PowerShell expressions. Strings must appear in quotation marks, even if they do not include spaces. - To manage the hash table, save it in a variable. - When assigning an ordered hash table to a variable, place the [ordered]
- attribute before the "@" symbol. If you place it before the variable name, the
- command fails.
+ attribute before the `@` symbol. If you place it before the variable name,
+ the command fails.
To create an empty hash table in the value of $hash, type:
example, the following statement creates a hash table with three keys.
$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"} ```
-### Creating Ordered Dictionaries
+## Creating Ordered Dictionaries
You can create an ordered dictionary by adding an object of the
-OrderedDictionary type, but the easiest way to create an ordered dictionary is
-use the [Ordered] attribute.
+**OrderedDictionary** type, but the easiest way to create an ordered dictionary
+is use the `[ordered]` attribute.
-The [ordered] attribute is introduced in PowerShell 3.0.
+The `[ordered]` attribute is introduced in PowerShell 3.0.
Place the attribute immediately before the "@" symbol.
$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}
You can use ordered dictionaries in the same way that you use hash tables. Either type can be used as the value of parameters that take a hash table or
-dictionary (iDictionary).
+dictionary (**iDictionary**).
-You cannot use the [ordered] attribute to convert or cast a hash table. If you
-place the ordered attribute before the variable name, the command fails with
-the following error message.
+You cannot use the `[ordered]` attribute to convert or cast a hash table. If
+you place the ordered attribute before the variable name, the command fails
+with the following error message.
```powershell
-PS C:\> [ordered]$hash = @{}
+[ordered]$hash = @{}
At line:1 char:1 + [ordered]$hash = @{} + [!INCLUDE[]()]
eption
To correct the expression, move the [ordered] attribute. ```powershell
-PS C:\> $hash = [ordered]@{}
+$hash = [ordered]@{}
``` You can cast an ordered dictionary to a hash table, but you cannot recover the ordered attribute, even if you clear the variable and enter new values. To re-establish the order, you must remove and recreate the variable.
+```powershell
+[hashtable]$hash = [ordered]@{
+ Number = 1; Shape = "Square"; Color = "Blue"}
+$hash
```
-PS C:\> [hashtable]$hash = [ordered]@{
->> Number = 1; Shape = "Square"; Color = "Blue"}
-PS C:\> $hash
+```Output
Name Value ---- ----- Color Blue
Shape Square
Number 1 ```
-### Displaying Hash Tables
+## Displaying Hash Tables
-To display a hash table that is saved in a variable, type the variable name.
-By default, a hash tables is displayed as a table with one column for keys and
-one for values.
+To display a hash table that is saved in a variable, type the variable name. By
+default, a hash tables is displayed as a table with one column for keys and one
+for values.
```powershell
-C:\PS> $hash
+$hash
+```
+```Output
Name Value ---- ----- Shape Square
Hash tables have Keys and Values properties. Use dot notation to display all
of the keys or all of the values. ```powershell
-C:\PS> $hash.keys
+$hash.keys
+```
+
+```Output
Number Shape Color
+```
-C:\PS> $hash.values
+```powershell
+$hash.values
+```
+
+```Output
1 Square Blue
Each key name is also a property of the hash table, and its value is the value
of the key-name property. Use the following format to display the property values.
-```powershell
+```Syntax
$hashtable.<key> <value> ```
$hashtable.<key>
For example: ```powershell
-C:\PS> $hash.Number
+$hash.Number
1
-C:\PS> $hash.Color
+$hash.Color
Blue ```
Hash tables have a Count property that indicates the number of key-value pairs
in the hash table. ```powershell
-C:\PS> $hash.count
+$hash.count
3 ```
If the key is a string value, enclose the key name in quotation marks.
For example: ```powershell
-C:\PS> $hash["Number"]
+$hash["Number"]
1 ```
-### Adding and Removing Keys and Values
+## Adding and Removing Keys and Values
To add keys and values to a hash table, use the following command format.
the following statement format.
$hash.Add("Time", "Now") ```
-And, you can add keys and values to a hash table by using the addition
-operator (+) to add a hash table to an existing hash table. For example, the
-following statement adds a "Time" key with a value of "Now" to the hash table
-in the $hash variable.
+And, you can add keys and values to a hash table by using the addition operator
+(`+`) to add a hash table to an existing hash table. For example, the following
+statement adds a "Time" key with a value of "Now" to the hash table in the
+$hash variable.
```powershell $hash = $hash + @{Time="Now"}
PowerShell, including Contains, Clear, Clone, and CopyTo. For more information
about Hashtable objects, see [System.Collections.Hashtable](/dotnet/api/system.collections.hashtable).
-### Object Types in HashTables
+## Object Types in HashTables
The keys and values in a hash table can have any .NET object type, and a single hash table can have keys and values of multiple types.
You can display the hash table in `$p` and use the key-name properties to
display the values. ```powershell
-C:\PS> $p
+$p
Name Value ---- ----- PowerShell System.Diagnostics.Process (PowerShell) Notepad System.Diagnostics.Process (notepad)
-C:\PS> $p.PowerShell
+$p.PowerShell
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 441 24 54196 54012 571 5.10 1788 PowerShell
-C:\PS> $p.keys | foreach {$p.$_.handles}
+$p.keys | foreach {$p.$_.handles}
441 251 ```
Service object that represents the WinRM service, and the value is the current
status of the service. ```powershell
-C:\PS> $p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}
+$p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}
``` You can display and access the new key/value pair by using the same methods that you use for other pairs in the hash table. ```powershell
-C:\PS> $p
+$p
Name Value ---- -----
PowerShell System.Diagnostics.Process (PowerShell)
Notepad System.Diagnostics.Process (notepad) System.ServiceProcess.Servi... Running
-C:\PS> $p.keys
+$p.keys
PowerShell Notepad
Status Name DisplayName
------ ---- ----------- Running winrm Windows Remote Management (WS-Manag...
-C:\PS> $p.keys | foreach {$_.name}
+$p.keys | foreach {$_.name}
winrm ```
in which the key is a string, Hash2, and the value is a hash table with three
key/value pairs. ```powershell
-C:\PS> $p = $p + @{"Hash2"= @{a=1; b=2; c=3}}
+$p = $p + @{"Hash2"= @{a=1; b=2; c=3}}
``` You can display and access the new values by using the same methods. ```powershell
-C:\PS> $p
+$p
Name Value ---- -----
Notepad System.Diagnostics.Process (notepad)
System.ServiceProcess.Servi... Running Hash2 {a, b, c}
-C:\PS> $p.Hash2
+$p.Hash2
Name Value ---- -----
a 1
b 2 c 3
-C:\PS> $p.Hash2.b
+$p.Hash2.b
2 ```
-### Sorting Keys and Values
+## Sorting Keys and Values
The items in a hash table are intrinsically unordered. The key/value pairs might appear in a different order each time that you display them.
For example, the following commands enumerate the keys and values in the hash
table in the `$p` variable and then sort the keys in alphabetical order. ```powershell
-C:\PS> $p.GetEnumerator() | Sort-Object -Property key
+$p.GetEnumerator() | Sort-Object -Property key
Name Value ---- -----
The following command uses the same procedure to sort the hash values in
descending order. ```powershell
-C:\PS> $p.getenumerator() | Sort-Object -Property Value -Descending
+$p.getenumerator() | Sort-Object -Property Value -Descending
Name Value ---- -----
Notepad System.Diagnostics.Process (notepad)
System.ServiceProcess.Servi... Running ```
-### Creating Objects from Hash Tables
+## Creating Objects from Hash Tables
Beginning in PowerShell 3.0, you can create an object from a hash table of properties and property values.
settable.
For more information, see [about_Object_Creation](about_Object_Creation.md).
-### ConvertFrom-StringData
+## ConvertFrom-StringData
The `ConvertFrom-StringData` cmdlet converts a string or a here-string of key/value pairs into a hash table. You can use the `ConvertFrom-StringData`
Here-strings are especially useful when the values in the hash table include
quotation marks. For more information about here-strings, see [about_Quoting_Rules](about_Quoting_Rules.md).
-The following example shows how to create a here-string of the user messages
-in the previous example and how to use `ConvertFrom-StringData` to convert them
+The following example shows how to create a here-string of the user messages in
+the previous example and how to use `ConvertFrom-StringData` to convert them
from a string into a hash table. The following command creates a here-string of the key/value pairs and then
-saves it in the \$string variable.
+saves it in the `$string` variable.
```powershell
-C:\PS> $string = @"
+$string = @"
Msg1 = Type "Windows". Msg2 = She said, "Hello, World." Msg3 = Enter an alias (or "nickname"). "@ ```
-This command uses the ConvertFrom-StringData cmdlet to convert the here-string
+This command uses the `ConvertFrom-StringData` cmdlet to convert the here-string
into a hash table. ```powershell
-C:\PS> ConvertFrom-StringData $string
+ConvertFrom-StringData $string
Name Value ---- -----
Msg2 She said, "Hello, World."
Msg1 Type "Windows". ```
-For more information about here-strings, see [about_Quoting_Rules](about_Quoting_Rules.md).
+For more information about here-strings, see
+[about_Quoting_Rules](about_Quoting_Rules.md).
-## SEE ALSO
+## See also
[about_Arrays](about_Arrays.md)
Microsoft.PowerShell.Core Microsoft.Powershell.Core (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Core/Microsoft.PowerShell.Core.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390782
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 00000000-0000-0000-0000-000000000000 Module Name: Microsoft.PowerShell.Core
Microsoft.PowerShell.Diagnostics Microsoft.Powershell.Diagnostics (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=285754
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: ca046f10-ca64-4740-8ff9-2565dba61a4f Module Name: Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host Microsoft.Powershell.Host (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390784
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 56d66100-99a0-4ffc-a12d-eee9a6718aef Module Name: Microsoft.PowerShell.Host
Microsoft.PowerShell.LocalAccounts Microsoft.Powershell.Localaccounts (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?LinkId=717973
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 8e362604-2c0b-448f-a414-a6a690a644e2 Module Name: Microsoft.PowerShell.LocalAccounts
Microsoft.PowerShell.Management Microsoft.Powershell.Management (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390785
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: eefcb906-b326-4e99-9f54-8b4bb6ef3c6d Module Name: Microsoft.PowerShell.Management
Microsoft.PowerShell.ODataUtils Microsoft.Powershell.Odatautils (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.ODataUtils/Microsoft.PowerShell.ODataUtils.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?LinkId=509916
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: fa1606d1-94cb-4264-bfb6-def714420084 Module Name: Microsoft.PowerShell.ODataUtils
Microsoft.PowerShell.Operation.Validation Microsoft.Powershell.Operation.Validation (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Operation.Validation/Microsoft.PowerShell.Operation.Validation.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?LinkId=808399
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 6.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 25bd9e34-bff9-4552-a23d-854857b42462 Module Name: Microsoft.PowerShell.Operation.Validation
Microsoft.PowerShell.Security Microsoft.Powershell.Security (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390786
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: a94c8c7e-9810-47c0-b8af-65089c13a35a Module Name: Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility Microsoft.Powershell.Utility (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390787
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0 Locale: en-US Module Guid: 1da87e53-152b-403e-98dc-74d7b4d63d59
Microsoft.WSMan.Management Microsoft.Wsman.Management (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/Microsoft.WSMan.Management/Microsoft.WSMan.Management.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390788
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 766204a6-330e-4263-a7ab-46c87afc366c Module Name: Microsoft.WSMan.Management
PSDesiredStateConfiguration Psdesiredstateconfiguration (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/PSDesiredStateConfiguration/PSDesiredStateConfiguration.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390814
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 94b905ff-74b5-437e-89ed-7df44386533c Module Name: PSDesiredStateConfiguration
PSDiagnostics Psdiagnostics (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/PSDiagnostics/PSDiagnostics.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=855965
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: c61d6278-02a3-4618-ae37-a524d40a7f44 Module Name: PSDiagnostics
PSReadLine Psreadline (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/PSReadLine/PSReadLine.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?LinkId=528806
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell
Locale: en-US Module Guid: 5714753b-2afd-4492-a5fd-01d9e2cff8b5 Module Name: PSReadLine
PSScheduledJob Psscheduledjob (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/PSScheduledJob/PSScheduledJob.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390816
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 50cdb55f-5ab7-489f-9e94-4ec21ff51e59 Module Name: PSScheduledJob
PSWorkflow Psworkflow (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/PSWorkflow/PSWorkflow.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390817
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 3b6cc51d-c096-4b38-b78d-0fed6277096a Module Name: PSWorkflow
PSWorkflowUtility Psworkflowutility (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/PSWorkflowUtility/PSWorkflowUtility.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=390818
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: e40bae2f-9558-479f-939b-e52407a19c86 Module Name: PSWorkflowUtility
PackageManagement Packagemanagement (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/PackageManagement/PackageManagement.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=392040
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 4ae9fd46-338a-459c-8186-07f910774cb8 Module Name: PackageManagement
PowershellGet Powershellget (5.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/5.1/PowershellGet/PowerShellGet.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?LinkId=393271
+Download Help Link: https://aka.ms/powershell51-help
Help Version: 5.2.0.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 1d73a601-4a6c-43c5-ba3f-619b18bbb404 Module Name: PowerShellGet
CimCmdlets Cimcmdlets (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/CimCmdlets/CimCmdlets.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113536
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: fb6cc51d-c096-4b38-b78d-0fed6277096a Module Name: CimCmdlets
Microsoft.PowerShell.Archive Microsoft.Powershell.Archive (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Archive/Microsoft.PowerShell.Archive.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113631
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: eb74e8da-9ae2-482a-a648-e96550fb8733 Module Name: Microsoft.PowerShell.Archive
Microsoft.PowerShell.Core About Enum (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/About/about_Enum.md
---
-description: The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list.
-keywords: powershell,cmdlet
+description: The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list.
Locale: en-US Previously updated : 11/27/2017 Last updated : 06/21/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_enum?view=powershell-7&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Enum
The `GetEnumNames()` method returns the list of the labels for the enumeration.
```powershell [MediaTypes].GetEnumNames()
+```
+
+```Output
unknown music mp3
The `GetEnumValues()` method returns the list of the values for the enumeration.
```powershell [MediaTypes].GetEnumValues()
+```
+
+```Output
unknown music mp3
avi
m4v ```
-**Note**: GetEnumNames() and GetEnumValues() seem to return the same results.
-However, internally, PowerShell is changing values into labels. Read the list
-carefully and you'll notice that `oga` and `mogg` are mentioned under the 'Get
-Names' results, but not under the 'Get Values' similar output for `jpg`,
-`jpeg`, and `mpg`, `mpeg`.
+> [!NOTE]
+> `GetEnumNames()` and `GetEnumValues()` seem to return the same results; a
+> list of named values. However, internally, `GetEnumValues()` enumerates the
+> values, then maps values into names. Read the list carefully and you'll
+> notice that `ogg`, `oga`, and `mogg` appear in the output of
+> `GetEnumNames()`, but the output of `GetEnumValues()` only shows `oga`. The
+> same thing happens for `jpg`, `jpeg`, and `mpg`, `mpeg`.
+
+The `GetEnumName()` method can be used to get a name associated with a specific
+value. If there are multiple names associated with a value, the method returns
+the alphabetically-first name.
```powershell [MediaTypes].GetEnumName(15) oga
+```
+The following example shows how to map each name to its value.
+
+```powershell
[MediaTypes].GetEnumNames() | ForEach-Object { "{0,-10} {1}" -f $_,[int]([MediaTypes]::$_) }
+```
+
+```Output
unknown 0 music 10 mp3 11
In the following example the *FileAttributes* enumeration is created.
"file2 attributes are: $file2" ```
-```output
+```Output
file1 attributes are: Archive, Compressed, Device file2 attributes are: Device, Directory, Encrypted ```
To test that a specific is set, you can use the binary comparison operator
`-band`. In this example, we test for the **Device** and the **Archive** attributes in the value of `$file2`.
-```
+```powershell
PS > ($file2 -band [FileAttributes]::Device) -eq [FileAttributes]::Device True
Microsoft.PowerShell.Core About Hash Tables (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/About/about_Hash_Tables.md
--- description: Describes how to create, use, and sort hash tables in PowerShell.
-keywords: powershell,cmdlet
Locale: en-US Previously updated : 11/28/2017 Last updated : 06/21/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_hash_tables?view=powershell-7&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Hash Tables --- # about_Hash_Tables
-## SHORT DESCRIPTION
+## Short description
Describes how to create, use, and sort hash tables in PowerShell.
-## LONG DESCRIPTION
+## Long description
A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more key/value pairs. For example, a hash table might contain a series of IP addresses and computer names, where the IP addresses are the keys and the computer names are the values, or vice versa.
-In PowerShell, each hash table is a Hashtable (System.Collections.Hashtable)
-object. You can use the properties and methods of Hashtable objects in
-PowerShell.
+In PowerShell, each hash table is a **Hashtable**
+(**System.Collections.Hashtable**) object. You can use the properties and
+methods of Hashtable objects in PowerShell.
Beginning in PowerShell 3.0, you can use the [ordered] attribute to create an
-ordered dictionary (System.Collections.Specialized.OrderedDictionary) in
+ordered dictionary (**System.Collections.Specialized.OrderedDictionary**) in
PowerShell. Ordered dictionaries differ from hash tables in that the keys always appear in
nested hash tables, in which the value of a key is another hash table.
Hash tables are frequently used because they are very efficient for finding and retrieving data. You can use hash tables to store lists and to create calculated properties in PowerShell. And, PowerShell has a cmdlet,
-ConvertFrom-StringData, that converts strings to a hash table.
+`ConvertFrom-StringData`, that converts strings to a hash table.
-### Syntax
+## Syntax
The syntax of a hash table is as follows:
The syntax of an ordered dictionary is as follows:
The [ordered] attribute was introduced in PowerShell 3.0.
-### Creating Hash Tables
+## Creating Hash Tables
To create a hash table, follow these guidelines: -- Begin the hash table with an at sign (@).-- Enclose the hash table in braces ({}).
+- Begin the hash table with an at sign (`@`).
+- Enclose the hash table in braces (`{}`).
- Enter one or more key/value pairs for the content of the hash table.-- Use an equal sign (=) to separate each key from its value.-- Use a semicolon (;) or a line break to separate the key/value pairs.-- Key that contains spaces must be enclosed in quotation marks. Values must be
+- Use an equal sign (`=`) to separate each key from its value.
+- Use a semicolon (`;`) or a line break to separate the key/value pairs.
+- Keys that contain spaces must be enclosed in quotation marks. Values must be
valid PowerShell expressions. Strings must appear in quotation marks, even if they do not include spaces. - To manage the hash table, save it in a variable. - When assigning an ordered hash table to a variable, place the [ordered]
- attribute before the "@" symbol. If you place it before the variable name, the
- command fails.
+ attribute before the `@` symbol. If you place it before the variable name,
+ the command fails.
To create an empty hash table in the value of $hash, type:
example, the following statement creates a hash table with three keys.
$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"} ```
-### Creating Ordered Dictionaries
+## Creating Ordered Dictionaries
You can create an ordered dictionary by adding an object of the
-OrderedDictionary type, but the easiest way to create an ordered dictionary is
-use the [Ordered] attribute.
+**OrderedDictionary** type, but the easiest way to create an ordered dictionary
+is use the `[ordered]` attribute.
-The [ordered] attribute is introduced in PowerShell 3.0.
+The `[ordered]` attribute is introduced in PowerShell 3.0.
Place the attribute immediately before the "@" symbol.
$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}
You can use ordered dictionaries in the same way that you use hash tables. Either type can be used as the value of parameters that take a hash table or
-dictionary (iDictionary).
+dictionary (**iDictionary**).
-You cannot use the [ordered] attribute to convert or cast a hash table. If you
-place the ordered attribute before the variable name, the command fails with
-the following error message.
+You cannot use the `[ordered]` attribute to convert or cast a hash table. If
+you place the ordered attribute before the variable name, the command fails
+with the following error message.
```powershell
-PS C:\> [ordered]$hash = @{}
+[ordered]$hash = @{}
At line:1 char:1 + [ordered]$hash = @{} + [!INCLUDE[]()]
eption
To correct the expression, move the [ordered] attribute. ```powershell
-PS C:\> $hash = [ordered]@{}
+$hash = [ordered]@{}
``` You can cast an ordered dictionary to a hash table, but you cannot recover the ordered attribute, even if you clear the variable and enter new values. To re-establish the order, you must remove and recreate the variable.
+```powershell
+[hashtable]$hash = [ordered]@{
+ Number = 1; Shape = "Square"; Color = "Blue"}
+$hash
```
-PS C:\> [hashtable]$hash = [ordered]@{
->> Number = 1; Shape = "Square"; Color = "Blue"}
-PS C:\> $hash
+```Output
Name Value ---- ----- Color Blue
Shape Square
Number 1 ```
-### Displaying Hash Tables
+## Displaying Hash Tables
-To display a hash table that is saved in a variable, type the variable name.
-By default, a hash tables is displayed as a table with one column for keys and
-one for values.
+To display a hash table that is saved in a variable, type the variable name. By
+default, a hash tables is displayed as a table with one column for keys and one
+for values.
```powershell
-C:\PS> $hash
+$hash
+```
+```Output
Name Value ---- ----- Shape Square
Hash tables have Keys and Values properties. Use dot notation to display all
of the keys or all of the values. ```powershell
-C:\PS> $hash.keys
+$hash.keys
+```
+
+```Output
Number Shape Color
+```
-C:\PS> $hash.values
+```powershell
+$hash.values
+```
+
+```Output
1 Square Blue
Each key name is also a property of the hash table, and its value is the value
of the key-name property. Use the following format to display the property values.
-```powershell
+```Syntax
$hashtable.<key> <value> ```
$hashtable.<key>
For example: ```powershell
-C:\PS> $hash.Number
+$hash.Number
1
-C:\PS> $hash.Color
+$hash.Color
Blue ```
Hash tables have a Count property that indicates the number of key-value pairs
in the hash table. ```powershell
-C:\PS> $hash.count
+$hash.count
3 ```
If the key is a string value, enclose the key name in quotation marks.
For example: ```powershell
-C:\PS> $hash["Number"]
+$hash["Number"]
1 ```
-### Adding and Removing Keys and Values
+## Adding and Removing Keys and Values
To add keys and values to a hash table, use the following command format.
the following statement format.
$hash.Add("Time", "Now") ```
-And, you can add keys and values to a hash table by using the addition
-operator (+) to add a hash table to an existing hash table. For example, the
-following statement adds a "Time" key with a value of "Now" to the hash table
-in the $hash variable.
+And, you can add keys and values to a hash table by using the addition operator
+(`+`) to add a hash table to an existing hash table. For example, the following
+statement adds a "Time" key with a value of "Now" to the hash table in the
+$hash variable.
```powershell $hash = $hash + @{Time="Now"}
PowerShell, including Contains, Clear, Clone, and CopyTo. For more information
about Hashtable objects, see [System.Collections.Hashtable](/dotnet/api/system.collections.hashtable).
-### Object Types in HashTables
+## Object Types in HashTables
The keys and values in a hash table can have any .NET object type, and a single hash table can have keys and values of multiple types.
You can display the hash table in `$p` and use the key-name properties to
display the values. ```powershell
-C:\PS> $p
+$p
Name Value ---- ----- PowerShell System.Diagnostics.Process (PowerShell) Notepad System.Diagnostics.Process (notepad)
-C:\PS> $p.PowerShell
+$p.PowerShell
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 441 24 54196 54012 571 5.10 1788 PowerShell
-C:\PS> $p.keys | foreach {$p.$_.handles}
+$p.keys | foreach {$p.$_.handles}
441 251 ```
Service object that represents the WinRM service, and the value is the current
status of the service. ```powershell
-C:\PS> $p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}
+$p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}
``` You can display and access the new key/value pair by using the same methods that you use for other pairs in the hash table. ```powershell
-C:\PS> $p
+$p
Name Value ---- -----
PowerShell System.Diagnostics.Process (PowerShell)
Notepad System.Diagnostics.Process (notepad) System.ServiceProcess.Servi... Running
-C:\PS> $p.keys
+$p.keys
PowerShell Notepad
Status Name DisplayName
------ ---- ----------- Running winrm Windows Remote Management (WS-Manag...
-C:\PS> $p.keys | foreach {$_.name}
+$p.keys | foreach {$_.name}
winrm ```
in which the key is a string, Hash2, and the value is a hash table with three
key/value pairs. ```powershell
-C:\PS> $p = $p + @{"Hash2"= @{a=1; b=2; c=3}}
+$p = $p + @{"Hash2"= @{a=1; b=2; c=3}}
``` You can display and access the new values by using the same methods. ```powershell
-C:\PS> $p
+$p
Name Value ---- -----
Notepad System.Diagnostics.Process (notepad)
System.ServiceProcess.Servi... Running Hash2 {a, b, c}
-C:\PS> $p.Hash2
+$p.Hash2
Name Value ---- -----
a 1
b 2 c 3
-C:\PS> $p.Hash2.b
+$p.Hash2.b
2 ```
-### Sorting Keys and Values
+## Sorting Keys and Values
The items in a hash table are intrinsically unordered. The key/value pairs might appear in a different order each time that you display them.
For example, the following commands enumerate the keys and values in the hash
table in the `$p` variable and then sort the keys in alphabetical order. ```powershell
-C:\PS> $p.GetEnumerator() | Sort-Object -Property key
+$p.GetEnumerator() | Sort-Object -Property key
Name Value ---- -----
The following command uses the same procedure to sort the hash values in
descending order. ```powershell
-C:\PS> $p.getenumerator() | Sort-Object -Property Value -Descending
+$p.getenumerator() | Sort-Object -Property Value -Descending
Name Value ---- -----
Notepad System.Diagnostics.Process (notepad)
System.ServiceProcess.Servi... Running ```
-### Creating Objects from Hash Tables
+## Creating Objects from Hash Tables
Beginning in PowerShell 3.0, you can create an object from a hash table of properties and property values.
settable.
For more information, see [about_Object_Creation](about_Object_Creation.md).
-### ConvertFrom-StringData
+## ConvertFrom-StringData
The `ConvertFrom-StringData` cmdlet converts a string or a here-string of key/value pairs into a hash table. You can use the `ConvertFrom-StringData`
Here-strings are especially useful when the values in the hash table include
quotation marks. For more information about here-strings, see [about_Quoting_Rules](about_Quoting_Rules.md).
-The following example shows how to create a here-string of the user messages
-in the previous example and how to use `ConvertFrom-StringData` to convert them
+The following example shows how to create a here-string of the user messages in
+the previous example and how to use `ConvertFrom-StringData` to convert them
from a string into a hash table. The following command creates a here-string of the key/value pairs and then
-saves it in the \$string variable.
+saves it in the `$string` variable.
```powershell
-C:\PS> $string = @"
+$string = @"
Msg1 = Type "Windows". Msg2 = She said, "Hello, World." Msg3 = Enter an alias (or "nickname"). "@ ```
-This command uses the ConvertFrom-StringData cmdlet to convert the here-string
+This command uses the `ConvertFrom-StringData` cmdlet to convert the here-string
into a hash table. ```powershell
-C:\PS> ConvertFrom-StringData $string
+ConvertFrom-StringData $string
Name Value ---- -----
Msg2 She said, "Hello, World."
Msg1 Type "Windows". ```
-For more information about here-strings, see [about_Quoting_Rules](about_Quoting_Rules.md).
+For more information about here-strings, see
+[about_Quoting_Rules](about_Quoting_Rules.md).
-## SEE ALSO
+## See also
[about_Arrays](about_Arrays.md)
Microsoft.PowerShell.Core Microsoft.Powershell.Core (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Core/Microsoft.PowerShell.Core.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113534
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 00000000-0000-0000-0000-000000000000 Module Name: Microsoft.PowerShell.Core
Microsoft.PowerShell.Diagnostics Microsoft.Powershell.Diagnostics (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113532
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: ca046f10-ca64-4740-8ff9-2565dba61a4f Module Name: Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host Microsoft.Powershell.Host (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113538
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 56d66100-99a0-4ffc-a12d-eee9a6718aef Module Name: Microsoft.PowerShell.Host
Microsoft.PowerShell.Management Microsoft.Powershell.Management (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113632
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: eefcb906-b326-4e99-9f54-8b4bb6ef3c6d Module Name: Microsoft.PowerShell.Management
Microsoft.PowerShell.Security Microsoft.Powershell.Security (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113533
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: a94c8c7e-9810-47c0-b8af-65089c13a35a Module Name: Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility Microsoft.Powershell.Utility (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113633
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0 Locale: en-US Module Guid: 1da87e53-152b-403e-98dc-74d7b4d63d59
Microsoft.WSMan.Management Microsoft.Wsman.Management (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/Microsoft.WSMan.Management/Microsoft.WSMan.Management.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113537
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 766204a6-330e-4263-a7ab-46c87afc366c Module Name: Microsoft.WSMan.Management
PSDesiredStateConfiguration Psdesiredstateconfiguration (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/PSDesiredStateConfiguration/PSDesiredStateConfiguration.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113535
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 779e0998-8c72-4567-89b5-49313fc15351 Module Name: PSDesiredStateConfiguration
PSDiagnostics Psdiagnostics (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/PSDiagnostics/PSDiagnostics.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113635
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: c61d6278-02a3-4618-ae37-a524d40a7f44 Module Name: PSDiagnostics
PSReadLine Psreadline (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/PSReadLine/PSReadLine.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113630
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell
Locale: en-US Module Guid: 5714753b-2afd-4492-a5fd-01d9e2cff8b5 Module Name: PSReadLine
PackageManagement Packagemanagement (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/PackageManagement/PackageManagement.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113634
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 4ae9fd46-338a-459c-8186-07f910774cb8 Module Name: PackageManagement
PowerShellGet Powershellget (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/PowerShellGet/PowerShellGet.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113539
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0
-keywords: powershell,cmdlet
Locale: en-US Module Guid: 1d73a601-4a6c-43c5-ba3f-619b18bbb404 Module Name: PowerShellGet
ThreadJob Threadjob (7.0) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.0/ThreadJob/ThreadJob.md
---
-Download Help Link: https://go.microsoft.com/fwlink/?linkid=2113345
+Download Help Link: https://aka.ms/powershell70-help
Help Version: 7.0.1.0 Locale: en-US Module Guid: 0e7b895d-2fec-43f7-8cae-11e8d16f6e40
Microsoft.PowerShell.Core About Enum (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/About/about_Enum.md
---
-description: The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list.
-keywords: powershell,cmdlet
+description: The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list.
Locale: en-US Previously updated : 11/27/2017 Last updated : 06/21/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_enum?view=powershell-7.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Enum
The `GetEnumNames()` method returns the list of the labels for the enumeration.
```powershell [MediaTypes].GetEnumNames()
+```
+
+```Output
unknown music mp3
The `GetEnumValues()` method returns the list of the values for the enumeration.
```powershell [MediaTypes].GetEnumValues()
+```
+
+```Output
unknown music mp3
avi
m4v ```
-**Note**: GetEnumNames() and GetEnumValues() seem to return the same results.
-However, internally, PowerShell is changing values into labels. Read the list
-carefully and you'll notice that `oga` and `mogg` are mentioned under the 'Get
-Names' results, but not under the 'Get Values' similar output for `jpg`,
-`jpeg`, and `mpg`, `mpeg`.
+> [!NOTE]
+> `GetEnumNames()` and `GetEnumValues()` seem to return the same results; a
+> list of named values. However, internally, `GetEnumValues()` enumerates the
+> values, then maps values into names. Read the list carefully and you'll
+> notice that `ogg`, `oga`, and `mogg` appear in the output of
+> `GetEnumNames()`, but the output of `GetEnumValues()` only shows `oga`. The
+> same thing happens for `jpg`, `jpeg`, and `mpg`, `mpeg`.
+
+The `GetEnumName()` method can be used to get a name associated with a specific
+value. If there are multiple names associated with a value, the method returns
+the alphabetically-first name.
```powershell [MediaTypes].GetEnumName(15) oga
+```
+
+The following example shows how to map each name to its value.
+```powershell
[MediaTypes].GetEnumNames() | ForEach-Object { "{0,-10} {1}" -f $_,[int]([MediaTypes]::$_) }
+```
+
+```Output
unknown 0 music 10 mp3 11
In the following example the *FileAttributes* enumeration is created.
"file2 attributes are: $file2" ```
-```output
+```Output
file1 attributes are: Archive, Compressed, Device file2 attributes are: Device, Directory, Encrypted ```
To test that a specific is set, you can use the binary comparison operator
`-band`. In this example, we test for the **Device** and the **Archive** attributes in the value of `$file2`.
-```
+```powershell
PS > ($file2 -band [FileAttributes]::Device) -eq [FileAttributes]::Device True PS > ($file2 -band [FileAttributes]::Archive) -eq [FileAttributes]::Archive False ```-
Microsoft.PowerShell.Core About Hash Tables (7.1) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.1/Microsoft.PowerShell.Core/About/about_Hash_Tables.md
--- description: Describes how to create, use, and sort hash tables in PowerShell.
-keywords: powershell,cmdlet
Locale: en-US Previously updated : 11/28/2017 Last updated : 06/21/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_hash_tables?view=powershell-7.1&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Hash Tables --- # about_Hash_Tables
-## SHORT DESCRIPTION
+## Short description
Describes how to create, use, and sort hash tables in PowerShell.
-## LONG DESCRIPTION
+## Long description
A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more key/value pairs. For example, a hash table might contain a series of IP addresses and computer names, where the IP addresses are the keys and the computer names are the values, or vice versa.
-In PowerShell, each hash table is a Hashtable (System.Collections.Hashtable)
-object. You can use the properties and methods of Hashtable objects in
-PowerShell.
+In PowerShell, each hash table is a **Hashtable**
+(**System.Collections.Hashtable**) object. You can use the properties and
+methods of Hashtable objects in PowerShell.
Beginning in PowerShell 3.0, you can use the [ordered] attribute to create an
-ordered dictionary (System.Collections.Specialized.OrderedDictionary) in
+ordered dictionary (**System.Collections.Specialized.OrderedDictionary**) in
PowerShell. Ordered dictionaries differ from hash tables in that the keys always appear in
nested hash tables, in which the value of a key is another hash table.
Hash tables are frequently used because they are very efficient for finding and retrieving data. You can use hash tables to store lists and to create calculated properties in PowerShell. And, PowerShell has a cmdlet,
-ConvertFrom-StringData, that converts strings to a hash table.
+`ConvertFrom-StringData`, that converts strings to a hash table.
-### Syntax
+## Syntax
The syntax of a hash table is as follows:
The syntax of an ordered dictionary is as follows:
The [ordered] attribute was introduced in PowerShell 3.0.
-### Creating Hash Tables
+## Creating Hash Tables
To create a hash table, follow these guidelines: -- Begin the hash table with an at sign (@).-- Enclose the hash table in braces ({}).
+- Begin the hash table with an at sign (`@`).
+- Enclose the hash table in braces (`{}`).
- Enter one or more key/value pairs for the content of the hash table.-- Use an equal sign (=) to separate each key from its value.-- Use a semicolon (;) or a line break to separate the key/value pairs.-- Key that contains spaces must be enclosed in quotation marks. Values must be
+- Use an equal sign (`=`) to separate each key from its value.
+- Use a semicolon (`;`) or a line break to separate the key/value pairs.
+- Keys that contain spaces must be enclosed in quotation marks. Values must be
valid PowerShell expressions. Strings must appear in quotation marks, even if they do not include spaces. - To manage the hash table, save it in a variable. - When assigning an ordered hash table to a variable, place the [ordered]
- attribute before the "@" symbol. If you place it before the variable name, the
- command fails.
+ attribute before the `@` symbol. If you place it before the variable name,
+ the command fails.
To create an empty hash table in the value of $hash, type:
example, the following statement creates a hash table with three keys.
$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"} ```
-### Creating Ordered Dictionaries
+## Creating Ordered Dictionaries
You can create an ordered dictionary by adding an object of the
-OrderedDictionary type, but the easiest way to create an ordered dictionary is
-use the [Ordered] attribute.
+**OrderedDictionary** type, but the easiest way to create an ordered dictionary
+is use the `[ordered]` attribute.
-The [ordered] attribute is introduced in PowerShell 3.0.
+The `[ordered]` attribute is introduced in PowerShell 3.0.
Place the attribute immediately before the "@" symbol.
$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}
You can use ordered dictionaries in the same way that you use hash tables. Either type can be used as the value of parameters that take a hash table or
-dictionary (iDictionary).
+dictionary (**iDictionary**).
-You cannot use the [ordered] attribute to convert or cast a hash table. If you
-place the ordered attribute before the variable name, the command fails with
-the following error message.
+You cannot use the `[ordered]` attribute to convert or cast a hash table. If
+you place the ordered attribute before the variable name, the command fails
+with the following error message.
```powershell
-PS C:\> [ordered]$hash = @{}
+[ordered]$hash = @{}
At line:1 char:1 + [ordered]$hash = @{} + [!INCLUDE[]()]
eption
To correct the expression, move the [ordered] attribute. ```powershell
-PS C:\> $hash = [ordered]@{}
+$hash = [ordered]@{}
``` You can cast an ordered dictionary to a hash table, but you cannot recover the ordered attribute, even if you clear the variable and enter new values. To re-establish the order, you must remove and recreate the variable.
+```powershell
+[hashtable]$hash = [ordered]@{
+ Number = 1; Shape = "Square"; Color = "Blue"}
+$hash
```
-PS C:\> [hashtable]$hash = [ordered]@{
->> Number = 1; Shape = "Square"; Color = "Blue"}
-PS C:\> $hash
+```Output
Name Value ---- ----- Color Blue
Shape Square
Number 1 ```
-### Displaying Hash Tables
+## Displaying Hash Tables
-To display a hash table that is saved in a variable, type the variable name.
-By default, a hash tables is displayed as a table with one column for keys and
-one for values.
+To display a hash table that is saved in a variable, type the variable name. By
+default, a hash tables is displayed as a table with one column for keys and one
+for values.
```powershell
-C:\PS> $hash
+$hash
+```
+```Output
Name Value ---- ----- Shape Square
Hash tables have Keys and Values properties. Use dot notation to display all
of the keys or all of the values. ```powershell
-C:\PS> $hash.keys
+$hash.keys
+```
+
+```Output
Number Shape Color
+```
-C:\PS> $hash.values
+```powershell
+$hash.values
+```
+
+```Output
1 Square Blue
Each key name is also a property of the hash table, and its value is the value
of the key-name property. Use the following format to display the property values.
-```powershell
+```Syntax
$hashtable.<key> <value> ```
$hashtable.<key>
For example: ```powershell
-C:\PS> $hash.Number
+$hash.Number
1
-C:\PS> $hash.Color
+$hash.Color
Blue ```
Hash tables have a Count property that indicates the number of key-value pairs
in the hash table. ```powershell
-C:\PS> $hash.count
+$hash.count
3 ```
If the key is a string value, enclose the key name in quotation marks.
For example: ```powershell
-C:\PS> $hash["Number"]
+$hash["Number"]
1 ```
-### Adding and Removing Keys and Values
+## Adding and Removing Keys and Values
To add keys and values to a hash table, use the following command format.
the following statement format.
$hash.Add("Time", "Now") ```
-And, you can add keys and values to a hash table by using the addition
-operator (+) to add a hash table to an existing hash table. For example, the
-following statement adds a "Time" key with a value of "Now" to the hash table
-in the $hash variable.
+And, you can add keys and values to a hash table by using the addition operator
+(`+`) to add a hash table to an existing hash table. For example, the following
+statement adds a "Time" key with a value of "Now" to the hash table in the
+$hash variable.
```powershell $hash = $hash + @{Time="Now"}
PowerShell, including Contains, Clear, Clone, and CopyTo. For more information
about Hashtable objects, see [System.Collections.Hashtable](/dotnet/api/system.collections.hashtable).
-### Object Types in HashTables
+## Object Types in HashTables
The keys and values in a hash table can have any .NET object type, and a single hash table can have keys and values of multiple types.
You can display the hash table in `$p` and use the key-name properties to
display the values. ```powershell
-C:\PS> $p
+$p
Name Value ---- ----- PowerShell System.Diagnostics.Process (PowerShell) Notepad System.Diagnostics.Process (notepad)
-C:\PS> $p.PowerShell
+$p.PowerShell
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 441 24 54196 54012 571 5.10 1788 PowerShell
-C:\PS> $p.keys | foreach {$p.$_.handles}
+$p.keys | foreach {$p.$_.handles}
441 251 ```
Service object that represents the WinRM service, and the value is the current
status of the service. ```powershell
-C:\PS> $p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}
+$p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}
``` You can display and access the new key/value pair by using the same methods that you use for other pairs in the hash table. ```powershell
-C:\PS> $p
+$p
Name Value ---- -----
PowerShell System.Diagnostics.Process (PowerShell)
Notepad System.Diagnostics.Process (notepad) System.ServiceProcess.Servi... Running
-C:\PS> $p.keys
+$p.keys
PowerShell Notepad
Status Name DisplayName
------ ---- ----------- Running winrm Windows Remote Management (WS-Manag...
-C:\PS> $p.keys | foreach {$_.name}
+$p.keys | foreach {$_.name}
winrm ```
in which the key is a string, Hash2, and the value is a hash table with three
key/value pairs. ```powershell
-C:\PS> $p = $p + @{"Hash2"= @{a=1; b=2; c=3}}
+$p = $p + @{"Hash2"= @{a=1; b=2; c=3}}
``` You can display and access the new values by using the same methods. ```powershell
-C:\PS> $p
+$p
Name Value ---- -----
Notepad System.Diagnostics.Process (notepad)
System.ServiceProcess.Servi... Running Hash2 {a, b, c}
-C:\PS> $p.Hash2
+$p.Hash2
Name Value ---- -----
a 1
b 2 c 3
-C:\PS> $p.Hash2.b
+$p.Hash2.b
2 ```
-### Sorting Keys and Values
+## Sorting Keys and Values
The items in a hash table are intrinsically unordered. The key/value pairs might appear in a different order each time that you display them.
For example, the following commands enumerate the keys and values in the hash
table in the `$p` variable and then sort the keys in alphabetical order. ```powershell
-C:\PS> $p.GetEnumerator() | Sort-Object -Property key
+$p.GetEnumerator() | Sort-Object -Property key
Name Value ---- -----
The following command uses the same procedure to sort the hash values in
descending order. ```powershell
-C:\PS> $p.getenumerator() | Sort-Object -Property Value -Descending
+$p.getenumerator() | Sort-Object -Property Value -Descending
Name Value ---- -----
Notepad System.Diagnostics.Process (notepad)
System.ServiceProcess.Servi... Running ```
-### Creating Objects from Hash Tables
+## Creating Objects from Hash Tables
Beginning in PowerShell 3.0, you can create an object from a hash table of properties and property values.
settable.
For more information, see [about_Object_Creation](about_Object_Creation.md).
-### ConvertFrom-StringData
+## ConvertFrom-StringData
The `ConvertFrom-StringData` cmdlet converts a string or a here-string of key/value pairs into a hash table. You can use the `ConvertFrom-StringData`
Here-strings are especially useful when the values in the hash table include
quotation marks. For more information about here-strings, see [about_Quoting_Rules](about_Quoting_Rules.md).
-The following example shows how to create a here-string of the user messages
-in the previous example and how to use `ConvertFrom-StringData` to convert them
+The following example shows how to create a here-string of the user messages in
+the previous example and how to use `ConvertFrom-StringData` to convert them
from a string into a hash table. The following command creates a here-string of the key/value pairs and then
-saves it in the \$string variable.
+saves it in the `$string` variable.
```powershell
-C:\PS> $string = @"
+$string = @"
Msg1 = Type "Windows". Msg2 = She said, "Hello, World." Msg3 = Enter an alias (or "nickname"). "@ ```
-This command uses the ConvertFrom-StringData cmdlet to convert the here-string
+This command uses the `ConvertFrom-StringData` cmdlet to convert the here-string
into a hash table. ```powershell
-C:\PS> ConvertFrom-StringData $string
+ConvertFrom-StringData $string
Name Value ---- -----
Msg2 She said, "Hello, World."
Msg1 Type "Windows". ```
-For more information about here-strings, see [about_Quoting_Rules](about_Quoting_Rules.md).
+For more information about here-strings, see
+[about_Quoting_Rules](about_Quoting_Rules.md).
-## SEE ALSO
+## See also
[about_Arrays](about_Arrays.md)
Microsoft.PowerShell.Core About Enum (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/About/about_Enum.md
--- description: The `enum` statement is used to declare an enumeration. An enumeration is a distinct type that consists of a set of named labels called the enumerator list. Locale: en-US Previously updated : 11/27/2017 Last updated : 06/21/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_enum?view=powershell-7.2&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Enum
The `GetEnumNames()` method returns the list of the labels for the enumeration.
```powershell [MediaTypes].GetEnumNames()
+```
+
+```Output
unknown music mp3
The `GetEnumValues()` method returns the list of the values for the enumeration.
```powershell [MediaTypes].GetEnumValues()
+```
+
+```Output
unknown music mp3
avi
m4v ```
-**Note**: GetEnumNames() and GetEnumValues() seem to return the same results.
-However, internally, PowerShell is changing values into labels. Read the list
-carefully and you'll notice that `oga` and `mogg` are mentioned under the 'Get
-Names' results, but not under the 'Get Values' similar output for `jpg`,
-`jpeg`, and `mpg`, `mpeg`.
+> [!NOTE]
+> `GetEnumNames()` and `GetEnumValues()` seem to return the same results; a
+> list of named values. However, internally, `GetEnumValues()` enumerates the
+> values, then maps values into names. Read the list carefully and you'll
+> notice that `ogg`, `oga`, and `mogg` appear in the output of
+> `GetEnumNames()`, but the output of `GetEnumValues()` only shows `oga`. The
+> same thing happens for `jpg`, `jpeg`, and `mpg`, `mpeg`.
+
+The `GetEnumName()` method can be used to get a name associated with a specific
+value. If there are multiple names associated with a value, the method returns
+the alphabetically-first name.
```powershell [MediaTypes].GetEnumName(15) oga
+```
+
+The following example shows how to map each name to its value.
+```powershell
[MediaTypes].GetEnumNames() | ForEach-Object { "{0,-10} {1}" -f $_,[int]([MediaTypes]::$_) }
+```
+
+```Output
unknown 0 music 10 mp3 11
In the following example the *FileAttributes* enumeration is created.
"file2 attributes are: $file2" ```
-```output
+```Output
file1 attributes are: Archive, Compressed, Device file2 attributes are: Device, Directory, Encrypted ```
To test that a specific is set, you can use the binary comparison operator
`-band`. In this example, we test for the **Device** and the **Archive** attributes in the value of `$file2`.
-```
+```powershell
PS > ($file2 -band [FileAttributes]::Device) -eq [FileAttributes]::Device True PS > ($file2 -band [FileAttributes]::Archive) -eq [FileAttributes]::Archive False ```-
Microsoft.PowerShell.Core About Hash Tables (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/Microsoft.PowerShell.Core/About/about_Hash_Tables.md
--- description: Describes how to create, use, and sort hash tables in PowerShell. Locale: en-US Previously updated : 11/28/2017 Last updated : 06/21/2021 online version: https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_hash_tables?view=powershell-7.2&WT.mc_id=ps-gethelp schema: 2.0.0 Title: about Hash Tables --- # about_Hash_Tables
-## SHORT DESCRIPTION
+## Short description
Describes how to create, use, and sort hash tables in PowerShell.
-## LONG DESCRIPTION
+## Long description
A hash table, also known as a dictionary or associative array, is a compact data structure that stores one or more key/value pairs. For example, a hash table might contain a series of IP addresses and computer names, where the IP addresses are the keys and the computer names are the values, or vice versa.
-In PowerShell, each hash table is a Hashtable (System.Collections.Hashtable)
-object. You can use the properties and methods of Hashtable objects in
-PowerShell.
+In PowerShell, each hash table is a **Hashtable**
+(**System.Collections.Hashtable**) object. You can use the properties and
+methods of Hashtable objects in PowerShell.
Beginning in PowerShell 3.0, you can use the [ordered] attribute to create an
-ordered dictionary (System.Collections.Specialized.OrderedDictionary) in
+ordered dictionary (**System.Collections.Specialized.OrderedDictionary**) in
PowerShell. Ordered dictionaries differ from hash tables in that the keys always appear in
nested hash tables, in which the value of a key is another hash table.
Hash tables are frequently used because they are very efficient for finding and retrieving data. You can use hash tables to store lists and to create calculated properties in PowerShell. And, PowerShell has a cmdlet,
-ConvertFrom-StringData, that converts strings to a hash table.
+`ConvertFrom-StringData`, that converts strings to a hash table.
-### Syntax
+## Syntax
The syntax of a hash table is as follows:
The syntax of an ordered dictionary is as follows:
The [ordered] attribute was introduced in PowerShell 3.0.
-### Creating Hash Tables
+## Creating Hash Tables
To create a hash table, follow these guidelines: -- Begin the hash table with an at sign (@).-- Enclose the hash table in braces ({}).
+- Begin the hash table with an at sign (`@`).
+- Enclose the hash table in braces (`{}`).
- Enter one or more key/value pairs for the content of the hash table.-- Use an equal sign (=) to separate each key from its value.-- Use a semicolon (;) or a line break to separate the key/value pairs.-- Key that contains spaces must be enclosed in quotation marks. Values must be
+- Use an equal sign (`=`) to separate each key from its value.
+- Use a semicolon (`;`) or a line break to separate the key/value pairs.
+- Keys that contain spaces must be enclosed in quotation marks. Values must be
valid PowerShell expressions. Strings must appear in quotation marks, even if they do not include spaces. - To manage the hash table, save it in a variable. - When assigning an ordered hash table to a variable, place the [ordered]
- attribute before the "@" symbol. If you place it before the variable name, the
- command fails.
+ attribute before the `@` symbol. If you place it before the variable name,
+ the command fails.
To create an empty hash table in the value of $hash, type:
example, the following statement creates a hash table with three keys.
$hash = @{ Number = 1; Shape = "Square"; Color = "Blue"} ```
-### Creating Ordered Dictionaries
+## Creating Ordered Dictionaries
You can create an ordered dictionary by adding an object of the
-OrderedDictionary type, but the easiest way to create an ordered dictionary is
-use the [Ordered] attribute.
+**OrderedDictionary** type, but the easiest way to create an ordered dictionary
+is use the `[ordered]` attribute.
-The [ordered] attribute is introduced in PowerShell 3.0.
+The `[ordered]` attribute is introduced in PowerShell 3.0.
Place the attribute immediately before the "@" symbol.
$hash = [ordered]@{ Number = 1; Shape = "Square"; Color = "Blue"}
You can use ordered dictionaries in the same way that you use hash tables. Either type can be used as the value of parameters that take a hash table or
-dictionary (iDictionary).
+dictionary (**iDictionary**).
-You cannot use the [ordered] attribute to convert or cast a hash table. If you
-place the ordered attribute before the variable name, the command fails with
-the following error message.
+You cannot use the `[ordered]` attribute to convert or cast a hash table. If
+you place the ordered attribute before the variable name, the command fails
+with the following error message.
```powershell
-PS C:\> [ordered]$hash = @{}
+[ordered]$hash = @{}
At line:1 char:1 + [ordered]$hash = @{} + [!INCLUDE[]()]
eption
To correct the expression, move the [ordered] attribute. ```powershell
-PS C:\> $hash = [ordered]@{}
+$hash = [ordered]@{}
``` You can cast an ordered dictionary to a hash table, but you cannot recover the ordered attribute, even if you clear the variable and enter new values. To re-establish the order, you must remove and recreate the variable.
+```powershell
+[hashtable]$hash = [ordered]@{
+ Number = 1; Shape = "Square"; Color = "Blue"}
+$hash
```
-PS C:\> [hashtable]$hash = [ordered]@{
->> Number = 1; Shape = "Square"; Color = "Blue"}
-PS C:\> $hash
+```Output
Name Value ---- ----- Color Blue
Shape Square
Number 1 ```
-### Displaying Hash Tables
+## Displaying Hash Tables
-To display a hash table that is saved in a variable, type the variable name.
-By default, a hash tables is displayed as a table with one column for keys and
-one for values.
+To display a hash table that is saved in a variable, type the variable name. By
+default, a hash tables is displayed as a table with one column for keys and one
+for values.
```powershell
-C:\PS> $hash
+$hash
+```
+```Output
Name Value ---- ----- Shape Square
Hash tables have Keys and Values properties. Use dot notation to display all
of the keys or all of the values. ```powershell
-C:\PS> $hash.keys
+$hash.keys
+```
+
+```Output
Number Shape Color
+```
-C:\PS> $hash.values
+```powershell
+$hash.values
+```
+
+```Output
1 Square Blue
Each key name is also a property of the hash table, and its value is the value
of the key-name property. Use the following format to display the property values.
-```powershell
+```Syntax
$hashtable.<key> <value> ```
$hashtable.<key>
For example: ```powershell
-C:\PS> $hash.Number
+$hash.Number
1
-C:\PS> $hash.Color
+$hash.Color
Blue ```
Hash tables have a Count property that indicates the number of key-value pairs
in the hash table. ```powershell
-C:\PS> $hash.count
+$hash.count
3 ```
If the key is a string value, enclose the key name in quotation marks.
For example: ```powershell
-C:\PS> $hash["Number"]
+$hash["Number"]
1 ```
-### Adding and Removing Keys and Values
+## Adding and Removing Keys and Values
To add keys and values to a hash table, use the following command format.
the following statement format.
$hash.Add("Time", "Now") ```
-And, you can add keys and values to a hash table by using the addition
-operator (+) to add a hash table to an existing hash table. For example, the
-following statement adds a "Time" key with a value of "Now" to the hash table
-in the $hash variable.
+And, you can add keys and values to a hash table by using the addition operator
+(`+`) to add a hash table to an existing hash table. For example, the following
+statement adds a "Time" key with a value of "Now" to the hash table in the
+$hash variable.
```powershell $hash = $hash + @{Time="Now"}
PowerShell, including Contains, Clear, Clone, and CopyTo. For more information
about Hashtable objects, see [System.Collections.Hashtable](/dotnet/api/system.collections.hashtable).
-### Object Types in HashTables
+## Object Types in HashTables
The keys and values in a hash table can have any .NET object type, and a single hash table can have keys and values of multiple types.
You can display the hash table in `$p` and use the key-name properties to
display the values. ```powershell
-C:\PS> $p
+$p
Name Value ---- ----- PowerShell System.Diagnostics.Process (PowerShell) Notepad System.Diagnostics.Process (notepad)
-C:\PS> $p.PowerShell
+$p.PowerShell
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 441 24 54196 54012 571 5.10 1788 PowerShell
-C:\PS> $p.keys | foreach {$p.$_.handles}
+$p.keys | foreach {$p.$_.handles}
441 251 ```
Service object that represents the WinRM service, and the value is the current
status of the service. ```powershell
-C:\PS> $p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}
+$p = $p + @{(Get-Service WinRM) = ((Get-Service WinRM).Status)}
``` You can display and access the new key/value pair by using the same methods that you use for other pairs in the hash table. ```powershell
-C:\PS> $p
+$p
Name Value ---- -----
PowerShell System.Diagnostics.Process (PowerShell)
Notepad System.Diagnostics.Process (notepad) System.ServiceProcess.Servi... Running
-C:\PS> $p.keys
+$p.keys
PowerShell Notepad
Status Name DisplayName
------ ---- ----------- Running winrm Windows Remote Management (WS-Manag...
-C:\PS> $p.keys | foreach {$_.name}
+$p.keys | foreach {$_.name}
winrm ```
in which the key is a string, Hash2, and the value is a hash table with three
key/value pairs. ```powershell
-C:\PS> $p = $p + @{"Hash2"= @{a=1; b=2; c=3}}
+$p = $p + @{"Hash2"= @{a=1; b=2; c=3}}
``` You can display and access the new values by using the same methods. ```powershell
-C:\PS> $p
+$p
Name Value ---- -----
Notepad System.Diagnostics.Process (notepad)
System.ServiceProcess.Servi... Running Hash2 {a, b, c}
-C:\PS> $p.Hash2
+$p.Hash2
Name Value ---- -----
a 1
b 2 c 3
-C:\PS> $p.Hash2.b
+$p.Hash2.b
2 ```
-### Sorting Keys and Values
+## Sorting Keys and Values
The items in a hash table are intrinsically unordered. The key/value pairs might appear in a different order each time that you display them.
For example, the following commands enumerate the keys and values in the hash
table in the `$p` variable and then sort the keys in alphabetical order. ```powershell
-C:\PS> $p.GetEnumerator() | Sort-Object -Property key
+$p.GetEnumerator() | Sort-Object -Property key
Name Value ---- -----
The following command uses the same procedure to sort the hash values in
descending order. ```powershell
-C:\PS> $p.getenumerator() | Sort-Object -Property Value -Descending
+$p.getenumerator() | Sort-Object -Property Value -Descending
Name Value ---- -----
Notepad System.Diagnostics.Process (notepad)
System.ServiceProcess.Servi... Running ```
-### Creating Objects from Hash Tables
+## Creating Objects from Hash Tables
Beginning in PowerShell 3.0, you can create an object from a hash table of properties and property values.
settable.
For more information, see [about_Object_Creation](about_Object_Creation.md).
-### ConvertFrom-StringData
+## ConvertFrom-StringData
The `ConvertFrom-StringData` cmdlet converts a string or a here-string of key/value pairs into a hash table. You can use the `ConvertFrom-StringData`
Here-strings are especially useful when the values in the hash table include
quotation marks. For more information about here-strings, see [about_Quoting_Rules](about_Quoting_Rules.md).
-The following example shows how to create a here-string of the user messages
-in the previous example and how to use `ConvertFrom-StringData` to convert them
+The following example shows how to create a here-string of the user messages in
+the previous example and how to use `ConvertFrom-StringData` to convert them
from a string into a hash table. The following command creates a here-string of the key/value pairs and then
-saves it in the \$string variable.
+saves it in the `$string` variable.
```powershell
-C:\PS> $string = @"
+$string = @"
Msg1 = Type "Windows". Msg2 = She said, "Hello, World." Msg3 = Enter an alias (or "nickname"). "@ ```
-This command uses the ConvertFrom-StringData cmdlet to convert the here-string
+This command uses the `ConvertFrom-StringData` cmdlet to convert the here-string
into a hash table. ```powershell
-C:\PS> ConvertFrom-StringData $string
+ConvertFrom-StringData $string
Name Value ---- -----
Msg2 She said, "Hello, World."
Msg1 Type "Windows". ```
-For more information about here-strings, see [about_Quoting_Rules](about_Quoting_Rules.md).
+For more information about here-strings, see
+[about_Quoting_Rules](about_Quoting_Rules.md).
-## SEE ALSO
+## See also
[about_Arrays](about_Arrays.md)
PSDesiredStateConfiguration About Classes And DSC (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/PSDesiredStateConfiguration/About/about_Classes_and_DSC.md
-description: Describes how you can use classes to develop in PowerShell with Desired State Configuration (DSC).
-Locale: en-US
Previously updated : 01/11/2019
-online version: https://docs.microsoft.com/powershell/module/psdesiredstateconfiguration/about/about_classes_and_dsc?view=powershell-7.2&WT.mc_id=ps-gethelp
-schema: 2.0.0
Title: about Classes and DSC
-# about_Classes_and_DSC
-
-## Short description
-
-Describes how you can use classes to develop in PowerShell with Desired State
-Configuration (DSC).
-
-## Long description
-
-Starting in Windows PowerShell 5.0, language was added to define classes and
-other user-defined types, by using formal syntax and semantics that are
-similar to other object-oriented programming languages. The goal is to enable
-developers and IT professionals to embrace PowerShell for a wider
-range of use cases, simplify development of PowerShell artifacts such as DSC
-resources, and accelerate coverage of management surfaces.
-
-## Supported scenarios
-
-The following scenarios are supported:
--- Define DSC resources and their associated types by using the PowerShell
- language.
-- Define custom types in PowerShell by using familiar object-oriented
- programming constructs, such as classes, properties, methods, and inheritance.
-- Debug types by using the PowerShell language.-- Generate and handle exceptions by using formal mechanisms, and at the right
- level.
-
-## Define DSC resources with classes
-
-Apart from syntax changes, the major differences between a class-defined DSC
-resource and a cmdlet DSC resource provider are the following items:
--- A Management Object Format (MOF) file is not required.-- A DSCResource subfolder in the module folder is not required.-- A PowerShell module file can contain multiple DSC resource classes.-
-## Create a class-defined DSC resource provider
-
-The following example is a class-defined DSC resource provider that is saved
-as a module, MyDSCResource.psm1. You must always include a key property in a
-class-defined DSC resource provider.
-
-```powershell
-enum Ensure
-{
- Absent
- Present
-}
-
-<#
- This resource manages the file in a specific path.
- [DscResource()] indicates the class is a DSC resource
-#>
-
-[DscResource()]
-class FileResource
-{
- <#
- This property is the fully qualified path to the file that is
- expected to be present or absent.
-
- The [DscProperty(Key)] attribute indicates the property is a
- key and its value uniquely identifies a resource instance.
- Defining this attribute also means the property is required
- and DSC will ensure a value is set before calling the resource.
-
- A DSC resource must define at least one key property.
- #>
- [DscProperty(Key)]
- [string]$Path
-
- <#
- This property indicates if the settings should be present or absent
- on the system. For present, the resource ensures the file pointed
- to by $Path exists. For absent, it ensures the file point to by
- $Path does not exist.
-
- The [DscProperty(Mandatory)] attribute indicates the property is
- required and DSC will guarantee it is set.
-
- If Mandatory is not specified or if it is defined as
- Mandatory=$false, the value is not guaranteed to be set when DSC
- calls the resource. This is appropriate for optional properties.
- #>
- [DscProperty(Mandatory)]
- [Ensure] $Ensure
-
- <#
- This property defines the fully qualified path to a file that will
- be placed on the system if $Ensure = Present and $Path does not
- exist.
-
- NOTE: This property is required because [DscProperty(Mandatory)] is
- set.
- #>
- [DscProperty(Mandatory)]
- [string] $SourcePath
-
- <#
- This property reports the file's create timestamp.
-
- [DscProperty(NotConfigurable)] attribute indicates the property is
- not configurable in DSC configuration. Properties marked this way
- are populated by the Get() method to report additional details
- about the resource when it is present.
-
- #>
- [DscProperty(NotConfigurable)]
- [Nullable[datetime]] $CreationTime
-
- <#
- This method is equivalent of the Set-TargetResource script function.
- It sets the resource to the desired state.
- #>
- [void] Set()
- {
- $fileExists = $this.TestFilePath($this.Path)
- if($this.ensure -eq [Ensure]::Present)
- {
- if(-not $fileExists)
- {
- $this.CopyFile()
- }
- }
- else
- {
- if($fileExists)
- {
- Write-Verbose -Message "Deleting the file $($this.Path)"
- Remove-Item -LiteralPath $this.Path -Force
- }
- }
- }
-
- <#
-
- This method is equivalent of the Test-TargetResource script
- function. It should return True or False, showing whether the
- resource is in a desired state.
- #>
- [bool] Test()
- {
- $present = $this.TestFilePath($this.Path)
-
- if($this.Ensure -eq [Ensure]::Present)
- {
- return $present
- }
- else
-{
- return -not $present
- }
- }
-
- <#
- This method is equivalent of the Get-TargetResource script function.
- The implementation should use the keys to find appropriate
- resources. This method returns an instance of this class with the
- updated key properties.
- #>
- [FileResource] Get()
- {
- $present = $this.TestFilePath($this.Path)
-
- if ($present)
- {
- $file = Get-ChildItem -LiteralPath $this.Path
- $this.CreationTime = $file.CreationTime
- $this.Ensure = [Ensure]::Present
- }
- else
- {
- $this.CreationTime = $null
- $this.Ensure = [Ensure]::Absent
- }
- return $this
- }
-
- <#
- Helper method to check if the file exists and it is correct file
- #>
- [bool] TestFilePath([string] $location)
- {
- $present = $true
-
- $item = Get-ChildItem -LiteralPath $location -ea Ignore
- if ($null -eq $item)
- {
- $present = $false
- }
- elseif( $item.PSProvider.Name -ne "FileSystem")
- {
- throw "Path $($location) is not a file path."
- }
- elseif($item.PSIsContainer)
- {
- throw "Path $($location) is a directory path."
- }
- return $present
- }
-
- <#
- Helper method to copy file from source to path
- #>
- [void] CopyFile()
- {
- if(-not $this.TestFilePath($this.SourcePath))
- {
- throw "SourcePath $($this.SourcePath) is not found."
- }
-
- [System.IO.FileInfo]
- $destFileInfo = new-object System.IO.FileInfo($this.Path)
-
- if (-not $destFileInfo.Directory.Exists)
- {
- $FullName = $destFileInfo.Directory.FullName
- $Message = "Creating directory $FullName"
-
- Write-Verbose -Message $Message
-
- #use CreateDirectory instead of New-Item to avoid code
- # to handle the non-terminating error
- [System.IO.Directory]::CreateDirectory($FullName)
- }
-
- if(Test-Path -LiteralPath $this.Path -PathType Container)
- {
- throw "Path $($this.Path) is a directory path"
- }
-
- Write-Verbose -Message "Copying $this.SourcePath to $this.Path"
-
- #DSC engine catches and reports any error that occurs
- Copy-Item -Path $this.SourcePath -Destination $this.Path -Force
- }
-}
-```
-
-## Create a module manifest
-
-After creating the class-defined DSC resource provider, and saving it as a
-module, create a module manifest for the module. To make a class-based
-resource available to the DSC engine, you must include a `DscResourcesToExport`
-statement in the manifest file that instructs the module to export the
-resource. In this example, the following module manifest is saved as
-MyDscResource.psd1.
-
-```powershell
-@{
-
-# Script module or binary module file associated with this manifest.
-RootModule = 'MyDscResource.psm1'
-
-DscResourcesToExport = 'FileResource'
-
-# Version number of this module.
-ModuleVersion = '1.0'
-
-# ID used to uniquely identify this module
-GUID = '81624038-5e71-40f8-8905-b1a87afe22d7'
-
-# Author of this module
-Author = 'Microsoft Corporation'
-
-# Company or vendor of this module
-CompanyName = 'Microsoft Corporation'
-
-# Copyright statement for this module
-Copyright = '(c) 2014 Microsoft. All rights reserved.'
-
-# Description of the functionality provided by this module
-# Description = ''
-
-# Minimum version of the PowerShell engine required by this module
-PowerShellVersion = '5.0'
-
-# Name of the PowerShell host required by this module
-# PowerShellHostName = ''
-
-}
-```
-
-## Deploy a DSC resource provider
-
-Deploy the new DSC resource provider by creating a MyDscResource folder in
-`$pshome\Modules` or `$env:SystemDrive\ProgramFiles\WindowsPowerShell\Modules`.
-
-You do not need to create a DSCResource subfolder. Copy the module and module
-manifest files (MyDscResource.psm1 and MyDscResource.psd1) to the
-MyDscResource folder.
-
-From this point, you create and run a configuration script as you would with
-any DSC resource.
-
-## Create a DSC configuration script
-
-After saving the class and manifest files in the folder structure as described
-earlier, you can create a configuration that uses the new resource. The
-following configuration references the MyDSCResource module. Save the
-configuration as a script, MyResource.ps1.
-
-For information about how to run a DSC configuration,
-see [Windows PowerShell Desired State Configuration Overview](/powershell/scripting/dsc/overview/dscforengineers).
-
-Before you run the configuration, create `C:\test.txt`. The configuration
-checks if the file exists at `c:\test\test.txt`. If the file does not exist,
-the configuration copies the file from `C:\test.txt`.
-
-```powershell
-Configuration Test
-{
- Import-DSCResource -module MyDscResource
- FileResource file
- {
- Path = "C:\test\test.txt"
- SourcePath = "C:\test.txt"
- Ensure = "Present"
- }
-}
-Test
-Start-DscConfiguration -Wait -Force Test
-```
-
-Run this script as you would any DSC configuration script. To start the
-configuration, in an elevated PowerShell console, run the following:
-
-`PS C:\test> .\MyResource.ps1`
-
-## Inheritance in PowerShell classes
-
-### Declare base classes for PowerShell classes
-
-You can declare a PowerShell class as a base type for another PowerShell
-class, as shown in the following example, in which **fruit** is a base type
-for **apple**.
-
-```powershell
-class fruit
-{
- [int]sold() {return 100500}
-}
-
-class apple : fruit {}
- [apple]::new().sold() # return 100500
-```
-
-### Declare implemented interfaces for PowerShell classes
-
-You can declare implemented interfaces after base types, or immediately after
-a colon (`:`) if there is no base type specified. Separate all type names by
-using commas. This is similar to C# syntax.
-
-```powershell
-class MyComparable : system.IComparable
-{
- [int] CompareTo([object] $obj)
- {
- return 0;
- }
-}
-
-class MyComparableTest : test, system.IComparable
-{
- [int] CompareTo([object] $obj)
- {
- return 0;
- }
-}
-```
-
-### Call base class constructors
-
-To call a base class constructor from a subclass, add the `base` keyword, as
-shown in the following example:
-
-```powershell
-class A {
- [int]$a
- A([int]$a)
- {
- $this.a = $a
- }
-}
-
-class B : A
-{
- B() : base(103) {}
-}
-
- [B]::new().a # return 103
-```
-
-If a base class has a default constructor (no parameters), you can omit an
-explicit constructor call, as shown.
-
-```powershell
-class C : B
-{
- C([int]$c) {}
-}
-```
-
-### Call base class methods
-
-You can override existing methods in subclasses. To do the override, declare
-methods by using the same name and signature.
-
-```powershell
-class baseClass
-{
- [int]days() {return 100500}
-}
-class childClass1 : baseClass
-{
- [int]days () {return 200600}
-}
-
- [childClass1]::new().days() # return 200600
-```
-
-To call base class methods from overridden implementations, cast to the base
-class `([baseclass]$this)` on invocation.
-
-```powershell
-class childClass2 : baseClass
-{
- [int]days()
- {
- return 3 * ([baseClass]$this).days()
- }
-}
-
- [childClass2]::new().days() # return 301500
-```
-
-All PowerShell methods are virtual. You can hide non-virtual .NET methods in a
-subclass by using the same syntax as you do for an override: declare methods
-with same name and signature.
-
-```powershell
-class MyIntList : system.collections.generic.list[int]
-{
- # Add is final in system.collections.generic.list
- [void] Add([int]$arg)
- {
- ([system.collections.generic.list[int]]$this).Add($arg * 2)
- }
-}
-
-$list = [MyIntList]::new()
-$list.Add(100)
-$list[0] # return 200
-```
-
-### Current limitations with class inheritance
-
-A limitation with class inheritance is that there is no syntax to declare
-interfaces in PowerShell.
-
-## Defining custom types in PowerShell
-
-Windows PowerShell 5.0 introduced several language elements.
-
-### Class keyword
-
-Defines a new class.
-The `class` keyword is a true .NET Framework type.
-Class members are public.
-
-```powershell
-class MyClass
-{
-}
-```
-
-### Enum keyword and enumerations
-
-Support for the `enum` keyword was added and is a breaking change. The `enum`
-delimiter is currently a newline. A workaround for those who are already using
-`enum` is to insert an ampersand (`&`) before the word. Current limitations:
-you cannot define an enumerator in terms of itself, but you can initialize
-`enum` in terms of another `enum`, as shown in the following example:
-
-The base type cannot currently be specified. The base type is always [int].
-
-```powershell
-enum Color2
-{
- Yellow = [Color]::Blue
-}
-```
-
-An enumerator value must be a parse time constant. The enumerator value cannot
-be set to the result of an invoked command.
-
-```powershell
-enum MyEnum
-{
- Enum1
- Enum2
- Enum3 = 42
- Enum4 = [int]::MaxValue
-}
-```
-
-`Enum` supports arithmetic operations, as shown in the following example:
-
-```powershell
-enum SomeEnum { Max = 42 }
-enum OtherEnum { Max = [SomeEnum]::Max + 1 }
-```
-
-### Hidden keyword
-
-The `hidden` keyword, introduced in Windows PowerShell 5.0, hides class
-members from default `Get-Member` results. Specify the hidden property as
-shown in the following line:
-
-```powershell
-hidden [type] $classmember = <value>
-```
-
-Hidden members are not displayed by using tab completion or IntelliSense,
-unless the completion occurs in the class that defines the hidden member.
-
-A new attribute, **System.Management.Automation.HiddenAttribute**, was added,
-so that C# code can have the same semantics within PowerShell.
-
-For more information, see
-[about_Hidden](../../Microsoft.PowerShell.Core/About/about_hidden.md).
-
-### Import-DscResource
-
-`Import-DscResource` is now a true dynamic keyword. PowerShell parses the
-specified module's root module, searching for classes that contain the
-DscResource attribute.
-
-### Properties
-
-A new field, `ImplementingAssembly`, was added to `ModuleInfo`. If the script
-defines classes, or the loaded assembly for binary modules
-`ImplementingAssembly` is set to the dynamic assembly created for a script
-module. It is not set when ModuleType = Manifest.
-
-Reflection on the `ImplementingAssembly` field discovers resources in a
-module. This means you can discover resources written in either PowerShell or
-other managed languages.
-
-Fields with initializers.
-
-`[int] $i = 5`
-
-Static is supported and works like an attribute, similar to the type
-constraints, so it can be specified in any order.
-
-`static [int] $count = 0`
-
-A type is optional.
-
-`$s = "hello"`
-
-All members are public. Properties require either a newline or semicolon. If
-no object type is specified, the property type is **Object**.
-
-### Constructors and instantiation
-
-PowerShell classes can have constructors that have the same name as their
-class. Constructors can be overloaded. Static constructors are supported.
-Properties with initialization expressions are initialized before running any
-code in a constructor. Static properties are initialized before the body of a
-static constructor, and instance properties are initialized before the body of
-the non-static constructor. Currently, there is no syntax for calling a
-constructor from another constructor such as the C# syntax: `": this()")`. The
-workaround is to define a common Init method.
-
-The following are ways of instantiating classes:
--- Instantiating by using the default constructor. Note that `New-Object` is
- not supported in this release.
-
- `$a = [MyClass]::new()`
--- Calling a constructor with a parameter.-
- `$b = [MyClass]::new(42)`
--- Passing an array to a constructor with multiple parameters-
- `$c = [MyClass]::new(@(42,43,44), "Hello")`
-
-For this release, the type name is only visible lexically, meaning it is not
-visible outside of the module or script that defines the class. Functions can
-return instances of a class defined in PowerShell, and instances work well
-outside of the module or script.
-
-The `Get-Member` **Static** parameter lists constructors, so you can view
-overloads like any other method. The performance of this syntax is also
-considerably faster than `New-Object`.
-
-The pseudo-static method named **new** works with .NET types, as shown in the
-following example. `[hashtable]::new()`
-
-You can now see constructor overloads with `Get-Member`, or as shown in this
-example:
-
-```powershell
-[hashtable]::new
-OverloadDefinitions
-hashtable new()
-hashtable new(int capacity)
-hashtable new(int capacity, float loadFactor)
-```
-
-### Methods
-
-A PowerShell class method is implemented as a **ScriptBlock** that has only an
-end block. All methods are public. The following shows an example of defining
-a method named **DoSomething**.
-
-```powershell
-class MyClass
-{
- DoSomething($x)
- {
- $this._doSomething($x) # method syntax
- }
- private _doSomething($a) {}
-}
-```
-
-### Method invocation
-
-Overloaded methods are supported. Overloaded methods are named the same as an
-existing method but differentiated by their specified values.
-
-```powershell
-$b = [MyClass]::new()
-$b.DoSomething(42)
-```
-
-### Invocation
-
-See [Method invocation](#method-invocation).
-
-### Attributes
-
-Three new attributes were added: `DscResource`, `DscResourceKey`, and
-`DscResourceMandatory`.
-
-### Return types
-
-Return type is a contract. The return value is converted to the expected type.
-If no return type is specified, the return type is void. There is no streaming
-of objects and objects cannot be written to the pipeline either intentionally
-or by accident.
-
-### Lexical scoping of variables
-
-The following shows an example of how lexical scoping works in this release.
-
-```powershell
-$d = 42 # Script scope
-
-function bar
-{
- $d = 0 # Function scope
- [MyClass]::DoSomething()
-}
-
-class MyClass
-{
- static [object] DoSomething()
- {
- return $d # error, not found dynamically
- return $script:d # no error
-
- $d = $script:d
- return $d # no error, found lexically
- }
-}
-
-$v = bar
-$v -eq $d # true
-```
-
-## Example: Create custom classes
-
-The following example creates several new, custom classes to implement an HTML
-Dynamic Stylesheet Language (DSL). The example adds helper functions to create
-specific element types as part of the element class, such as heading styles
-and tables, because types cannot be used outside the scope of a module.
-
-```powershell
-# Classes that define the structure of the document
-#
-class Html
-{
- [string] $docType
- [HtmlHead] $Head
- [Element[]] $Body
-
- [string] Render()
- {
- $text = "<html>`n<head>`n"
- $text += $Head
- $text += "`n</head>`n<body>`n"
- $text += $Body -join "`n" # Render all of the body elements
- $text += "</body>`n</html>"
- return $text
- }
- [string] ToString() { return $this.Render() }
-}
-
-class HtmlHead
-{
- $Title
- $Base
- $Link
- $Style
- $Meta
- $Script
- [string] Render() { return "<title>$Title</title>" }
- [string] ToString() { return $this.Render() }
-}
-
-class Element
-{
- [string] $Tag
- [string] $Text
- [hashtable] $Attributes
- [string] Render() {
- $attributesText= ""
- if ($Attributes)
- {
- foreach ($attr in $Attributes.Keys)
- {
- $attributesText = " $attr=`"$($Attributes[$attr])`""
- }
- }
-
- return "<${tag}${attributesText}>$text</$tag>`n"
- }
- [string] ToString() { return $this.Render() }
-}
-
-#
-# Helper functions for creating specific element types on top of the classes.
-# These are required because types aren't visible outside of the module.
-#
-function H1 {[Element] @{Tag = "H1"; Text = $args.foreach{$_} -join " "}}
-function H2 {[Element] @{Tag = "H2"; Text = $args.foreach{$_} -join " "}}
-function H3 {[Element] @{Tag = "H3"; Text = $args.foreach{$_} -join " "}}
-function P {[Element] @{Tag = "P" ; Text = $args.foreach{$_} -join " "}}
-function B {[Element] @{Tag = "B" ; Text = $args.foreach{$_} -join " "}}
-function I {[Element] @{Tag = "I" ; Text = $args.foreach{$_} -join " "}}
-function HREF
-{
- param (
- $Name,
- $Link
- )
-
- return [Element] @{
- Tag = "A"
- Attributes = @{ HREF = $link }
- Text = $name
- }
-}
-function Table
-{
- param (
- [Parameter(Mandatory)]
- [object[]]
- $Data,
- [Parameter()]
- [string[]]
- $Properties = "*",
- [Parameter()]
- [hashtable]
- $Attributes = @{ border=2; cellpadding=2; cellspacing=2 }
- )
-
- $bodyText = ""
- # Add the header tags
- $bodyText += $Properties.foreach{TH $_}
- # Add the rows
- $bodyText += foreach ($row in $Data)
- {
- TR (-join $Properties.Foreach{ TD ($row.$_) } )
- }
-
- $table = [Element] @{
- Tag = "Table"
- Attributes = $Attributes
- Text = $bodyText
- }
- $table
-}
-function TH {([Element] @{Tag="TH"; Text=$args.foreach{$_} -join " "})}
-function TR {([Element] @{Tag="TR"; Text=$args.foreach{$_} -join " "})}
-function TD {([Element] @{Tag="TD"; Text=$args.foreach{$_} -join " "})}
-
-function Style
-{
- return [Element] @{
- Tag = "style"
- Text = "$args"
- }
-}
-
-# Takes a hash table, casts it to and HTML document
-# and then returns the resulting type.
-#
-function Html ([HTML] $doc) { return $doc }
-```
-
-## See also
-
-[about_Enum](../../Microsoft.PowerShell.Core/About/about_Enum.md)
-
-[about_Hidden](../../Microsoft.PowerShell.Core/About/about_hidden.md)
-
-[about_Language_Keywords](../../Microsoft.PowerShell.Core/About/about_Language_Keywords.md)
-
-[about_Methods](../../Microsoft.PowerShell.Core/About/about_Methods.md)
-
-[Build Custom PowerShell Desired State Configuration Resources](/powershell/scripting/dsc/resources/authoringResource)
-
PSDesiredStateConfiguration Get Dscresource (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/PSDesiredStateConfiguration/Get-DscResource.md
-external help file: PSDesiredStateConfiguration-help.xml
-Locale: en-US
-Module Name: PSDesiredStateConfiguration
Previously updated : 07/23/2020
-online version: https://docs.microsoft.com/powershell/module/psdesiredstateconfiguration/get-dscresource?view=powershell-7.2&WT.mc_id=ps-gethelp
-schema: 2.0.0
Title: Get-DscResource
-# Get-DscResource
-
-## SYNOPSIS
-Gets Desired State Configuration (DSC) resources present on the computer.
-
-## SYNTAX
-
-```
-Get-DscResource [[-Name] <String[]>] [[-Module] <Object>] [-Syntax] [<CommonParameters>]
-```
-
-## DESCRIPTION
-
-The `Get-DscResource` cmdlet retrieves the PowerShell DSC resources present on the computer. This
-cmdlet discovers only the resources installed in the PSModulePath. It shows the details about
-built-in and custom providers, which are created by the user. This cmdlet also shows details about
-composite resources, which are other configurations that are packaged as module or created at run
-time in the session.
-
-## EXAMPLES
-
-### Example 1: Get all resources on the local computer
-
-```powershell
-Get-DscResource
-```
-
-This command gets all the resources on the local computer.
-
-### Example 2: Get a resource by specifying the name
-
-```powershell
-Get-DscResource -Name "WindowsFeature"
-```
-
-This command gets the WindowsFeature resource.
-
-### Example 3: Get all the resources from a module
-
-```powershell
-Get-DscResource -Module "xHyper-V"
-```
-
-This command gets all the resources from the xHyper-V module.
-
-### Example 4: Get a resource by using wildcard characters
-
-```powershell
-Get-DscResource -Name P*,r*
-```
-
-This command gets all resources that match the wildcard pattern specified by the **Name** parameter.
-
-### Example 5: Get a resource syntax
-
-```powershell
-Get-DscResource -Name "WindowsFeature" -Syntax
-```
-
-This command gets the WindowsFeature resource, and shows the syntax for the resource.
-
-### Example 6: Get all the properties for a resource
-
-```powershell
-Get-DscResource -Name "User" | Select-Object -ExpandProperty Properties
-```
-
-This command gets the User resource, and then uses the pipeline operator to return all the
-properties for the User resource.
-
-### Example 7: Get all the resources from a specified module with a specified version
-
-```powershell
-Get-DscResource -Module @{ModuleName='xHyper-V';RequiredVersion='3.0.0.0'}
-```
-
-This command gets all the resources from xHyper-V module with version 3.0.0.0.
-
-## PARAMETERS
-
-### -Module
-
-Specifies the name or fully qualified name of the module for which to view the DSC resource.
-
-```yaml
-Type: System.Object
-Parameter Sets: (All)
-Aliases:
-
-Required: False
-Position: 1
-Default value: None
-Accept pipeline input: True (ByPropertyName, ByValue)
-Accept wildcard characters: False
-```
-
-### -Name
-
-Specifies an array of names of the DSC resource to view.
-
-```yaml
-Type: System.String[]
-Parameter Sets: (All)
-Aliases:
-
-Required: False
-Position: 0
-Default value: None
-Accept pipeline input: True (ByPropertyName, ByValue)
-Accept wildcard characters: False
-```
-
-### -Syntax
-
-Indicates that the cmdlet returns the syntax view of the specified DSC resources. The returned
-syntax shows how to use the resources in a PowerShell script.
-
-```yaml
-Type: System.Management.Automation.SwitchParameter
-Parameter Sets: (All)
-Aliases:
-
-Required: False
-Position: Named
-Default value: None
-Accept pipeline input: False
-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](https://go.microsoft.com/fwlink/?LinkID=113216).
-
-## INPUTS
-
-### System.String[]
-
-### System.Object
-
-## OUTPUTS
-
-### Microsoft.PowerShell.DesiredStateConfiguration.DscResourceInfo[]
-
-### string[]
-
-## NOTES
-
-## RELATED LINKS
-
-[PowerShell Desired State Configuration Overview](/powershell/scripting/dsc/overview/overview)
-
-[Invoke-DscResource](/powershell/module/PSDesiredStateConfiguration/Invoke-DscResource)
-
PSDesiredStateConfiguration Invoke Dscresource (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/PSDesiredStateConfiguration/Invoke-DscResource.md
-external help file: PSDesiredStateConfiguration-help.xml
-Locale: en-US
-Module Name: PSDesiredStateConfiguration
Previously updated : 08/11/2020
-online version: https://docs.microsoft.com/powershell/module/psdesiredstateconfiguration/invoke-dscresource?view=powershell-7.2&WT.mc_id=ps-gethelp
-schema: 2.0.0
Title: Invoke-DscResource-
-# Invoke-DscResource
-
-## SYNOPSIS
-Runs a method of a specified PowerShell Desired State Configuration (DSC) resource.
-
-## SYNTAX
-
-```
-Invoke-DscResource [-Name] <String> [[-ModuleName] <ModuleSpecification>] [-Method] <String>
- [-Property] <Hashtable> [<CommonParameters>]
-```
-
-## DESCRIPTION
-
-The `Invoke-DscResource` cmdlet runs a method of a specified PowerShell Desired State Configuration
-(DSC) resource.
-
-This cmdlet invokes a DSC resource directly, without creating a configuration document. Using this
-cmdlet, configuration management products can manage windows or Linux by using DSC resources. This
-cmdlet also enables debugging of resources when the DSC engine is running with debugging enabled.
-
-> [!NOTE]
-> `Invoke-DscResource` is an experimental feature in PowerShell 7. To use the cmdlet, you must
-> enable it using the following command.
->
-> `Enable-ExperimentalFeature PSDesiredStateConfiguration.InvokeDscResource`
-
-## EXAMPLES
-
-### Example 1: Invoke the Set method of a resource by specifying its mandatory properties
-
-This example invokes the **Set** method of a resource named **WindowsProcess** and provides the
-mandatory **Path** and **Arguments** properties to start the specified Windows process.
-
-```powershell
-Invoke-DscResource -Name WindowsProcess -Method Set -ModuleName PSDesiredStateConfiguration -Property @{
- Path = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
- Arguments = ''
-}
-```
-
-### Example 2: Invoke the Test method of a resource for a specified module
-
-This example invokes the **Test** method of a resource named **WindowsProcess**, which is in the
-module named **PSDesiredStateConfiguration**.
-
-```powershell
-$SplatParam = @{
- Name = 'WindowsProcess'
- ModuleName = 'PSDesiredStateConfiguration'
- Property = @{Path = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'; Arguments = ''}
- Method = Test
-}
-
-Invoke-DscResource @SplatParam
-```
-
-## PARAMETERS
-
-### -Method
-
-Specifies the method of the resource that this cmdlet invokes. The acceptable values for this
-parameter are: **Get**, **Set**, and **Test**.
-
-```yaml
-Type: System.String
-Parameter Sets: (All)
-Aliases:
-Accepted values: Get, Set, Test
-
-Required: True
-Position: 2
-Default value: None
-Accept pipeline input: False
-Accept wildcard characters: False
-```
-
-### -ModuleName
-
-Specifies the name of the module from which this cmdlet invokes the specified resource.
-
-```yaml
-Type: Microsoft.PowerShell.Commands.ModuleSpecification
-Parameter Sets: (All)
-Aliases:
-
-Required: False
-Position: 1
-Default value: None
-Accept pipeline input: True (ByPropertyName, ByValue)
-Accept wildcard characters: False
-```
-
-### -Name
-
-Specifies the name of the DSC resource to start.
-
-```yaml
-Type: System.String
-Parameter Sets: (All)
-Aliases:
-
-Required: True
-Position: 0
-Default value: None
-Accept pipeline input: True (ByPropertyName, ByValue)
-Accept wildcard characters: False
-```
-
-### -Property
-
-Specifies the resource property name and its value in a hash table as key and value, respectively.
-
-```yaml
-Type: System.Collections.Hashtable
-Parameter Sets: (All)
-Aliases:
-
-Required: True
-Position: 3
-Default value: None
-Accept pipeline input: False
-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](https://go.microsoft.com/fwlink/?LinkID=113216).
-
-## INPUTS
-
-### System.String
-
-### Microsoft.PowerShell.Commands.ModuleSpecification
-
-## OUTPUTS
-
-### System.Object
-
-## NOTES
--- Previously, Windows PowerShell 5.1 resources ran under System context unless specified with user
-context using the key **PsDscRunAsCredential**. In PowerShell 7.0, Resources run in the user's
-context, and **PsDscRunAsCredential** is no longer supported. Previous configurations using this key
-will throw an exception.
--- As of PowerShell 7, `Invoke-DscResource` no longer supports invoking WMI DSC resources. This
- includes the **File** and **Log** resources in **PSDesiredStateConfiguration**.
-
-## RELATED LINKS
-
-[Windows PowerShell Desired State Configuration Overview](/powershell/scripting/dsc/overview/dscforengineers)
-
-[Get-DscResource](Get-DscResource.md)
PSDesiredStateConfiguration New Dscchecksum (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/PSDesiredStateConfiguration/New-DSCCheckSum.md
-external help file: PSDesiredStateConfiguration-help.xml
-Locale: en-US
-Module Name: PSDesiredStateConfiguration
Previously updated : 06/09/2017
-online version: https://docs.microsoft.com/powershell/module/psdesiredstateconfiguration/new-dscchecksum?view=powershell-7.2&WT.mc_id=ps-gethelp
-schema: 2.0.0
Title: New-DscChecksum
-# New-DscChecksum
-
-## SYNOPSIS
-Creates checksum files for DSC documents and DSC resources.
-
-## SYNTAX
-
-```
-New-DscChecksum [-Path] <String[]> [[-OutPath] <String>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]
-```
-
-## DESCRIPTION
-
-The **New-DSCCheckSum** cmdlet generates checksum files for PowerShell Desired State Configuration (DSC) documents and compressed DSC resources.
-This cmdlet generates a checksum file for each configuration and resource to be used in pull mode.
-The DSC service uses the checksums to make sure that the correct configuration and resources exist on the target node.
-Place the checksums together with the associated DSC documents and compressed DSC resources in the DSC service store.
-
-## EXAMPLES
-
-### Example 1: Create checksum files for all configurations in a specific path
-
-```
-PS C:\> New-DscCheckSum -Path "C:\DSC\Configurations\"
-```
-
-This command creates checksum files for all configurations in the path C:\DSC\Configurations.
-Any checksum files that already exist are skipped.
-
-### Example 2: Create checksum files for all configurations in a specific path and overwrite the existing checksum files
-
-```
-PS C:\> New-DscCheckSum -Path "C:\DSC\Configurations\" -Force
-```
-
-This command creates new checksum files for all configurations in the path C:\DSC\Configurations.
-Specifying the *Force* parameter causes the command to overwrite any checksum files that already exist.
-
-## PARAMETERS
-
-### -Confirm
-
-Prompts you for confirmation before running the cmdlet.
-
-```yaml
-Type: System.Management.Automation.SwitchParameter
-Parameter Sets: (All)
-Aliases: cf
-
-Required: False
-Position: Named
-Default value: False
-Accept pipeline input: False
-Accept wildcard characters: False
-```
-
-### -Force
-
-Indicates that the cmdlet overwrites the specified output file if it already exists.
-
-```yaml
-Type: System.Management.Automation.SwitchParameter
-Parameter Sets: (All)
-Aliases:
-
-Required: False
-Position: Named
-Default value: None
-Accept pipeline input: False
-Accept wildcard characters: False
-```
-
-### -OutPath
-
-Specifies the path and file name of the output checksum file.
-
-```yaml
-Type: System.String
-Parameter Sets: (All)
-Aliases:
-
-Required: False
-Position: 1
-Default value: None
-Accept pipeline input: False
-Accept wildcard characters: False
-```
-
-### -Path
-
-Specifies the path of the input file.
-
-```yaml
-Type: System.String[]
-Parameter Sets: (All)
-Aliases: ConfigurationPath
-
-Required: True
-Position: 0
-Default value: None
-Accept pipeline input: False
-Accept wildcard characters: False
-```
-
-### -WhatIf
-
-Shows what would happen if the cmdlet runs.
-The cmdlet is not run.
-
-```yaml
-Type: System.Management.Automation.SwitchParameter
-Parameter Sets: (All)
-Aliases: wi
-
-Required: False
-Position: Named
-Default value: False
-Accept pipeline input: False
-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](https://go.microsoft.com/fwlink/?LinkID=113216).
-
-## INPUTS
-
-### None
-
-## OUTPUTS
-
-### System.Object
-
-## NOTES
-
-## RELATED LINKS
-
-[Windows PowerShell Desired State Configuration Overview](/powershell/scripting/dsc/overview/dscforengineers)
-
PSDesiredStateConfiguration Psdesiredstateconfiguration (7.2) https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/7.2/PSDesiredStateConfiguration/PSDesiredStateConfiguration.md
-Download Help Link: https://aka.ms/powershell72-help
-Help Version: 7.2.0.0
-Locale: en-US
-Module Guid: 779e0998-8c72-4567-89b5-49313fc15351
-Module Name: PSDesiredStateConfiguration
Previously updated : 06/09/2017
-schema: 2.0.0
Title: PSDesiredStateConfiguration
-# PSDesiredStateConfiguration Module
-
-## Description
-This module contains cmdlets that designed to work with DSC Resources.
-
-## PSDesiredStateConfiguration Cmdlets
-
-### [Get-DscResource](Get-DscResource.md)
-Gets the DSC resources present on the computer.
-
-### [Invoke-DscResource](Invoke-DscResource.md)
-Runs a method of a specified PowerShell Desired State Configuration (DSC) resource.
-
-### [New-DSCCheckSum](New-DSCCheckSum.md)
-Creates checksum files for DSC documents and DSC resources.
dsc Authoringresourceclass https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/docs-conceptual/dsc/resources/authoringResourceClass.md
--- Previously updated : 07/08/2020
-keywords: dsc,powershell,configuration,setup
Last updated : 06/22/2021 Title: Writing a custom DSC resource with PowerShell classes description: This article shows how to create a simple resource that manages a file in a specified path. ---
use the `DscResource()` attribute. The name of the class is the name of the DSC
```powershell [DscResource()]
-class FileResource {
+class File {
} ```
follows.
```powershell [DscProperty(Key)]
-[string]$Path
+[string] $path
[DscProperty(Mandatory)]
-[Ensure] $Ensure
+[ensure] $ensure
-[DscProperty(Mandatory)]
-[string] $SourcePath
+[DscProperty()]
+[string] $content
[DscProperty(NotConfigurable)]
-[Nullable[datetime]] $CreationTime
+[Reason[]] $Reasons
``` Notice that the properties are modified by attributes. The meaning of the attributes is as follows:
enum Ensure
} ```
-### Implementing the methods
-
-The `Get()`, `Set()`, and `Test()` methods are analogous to the `Get-TargetResource`,
-`Set-TargetResource`, and `Test-TargetResource` functions in a script resource.
+### Embedding classes
-This code also includes the `CopyFile()` function, a helper function that copies the file from
-`$SourcePath` to `$Path`.
+If you would like to include a new type with defined properties that you can
+use within your resource, just create a class with property types as described
+above.
```powershell
- <#
- This method is equivalent of the Set-TargetResource script function.
- It sets the resource to the desired state.
- #>
- [void] Set()
- {
- $fileExists = $this.TestFilePath($this.Path)
-
- if ($this.ensure -eq [Ensure]::Present)
- {
- if(-not $fileExists)
- {
- $this.CopyFile()
- }
- }
- else
- {
- if ($fileExists)
- {
- Write-Verbose -Message "Deleting the file $($this.Path)"
- Remove-Item -LiteralPath $this.Path -Force
- }
- }
- }
+class Reason {
+ [DscProperty()]
+ [string] $Code
- <#
- This method is equivalent of the Test-TargetResource script function.
- It should return True or False, showing whether the resource
- is in a desired state.
- #>
- [bool] Test()
- {
- $present = $this.TestFilePath($this.Path)
+ [DscProperty()]
+ [string] $Phrase
+}
+```
- if ($this.Ensure -eq [Ensure]::Present)
- {
- return $present
- }
- else
- {
- return -not $present
- }
- }
+### Public and Private functions
- <#
- This method is equivalent of the Get-TargetResource script function.
- The implementation should use the keys to find appropriate resources.
- This method returns an instance of this class with the updated key
- properties.
- #>
- [FileResource] Get()
- {
- $present = $this.TestFilePath($this.Path)
+You can create PowerShell functions within the same module file and use them
+inside the methods of your DSC class resource. The functions must be delcared
+as public, however the script blocks within those public functions can call
+functions that are private. The only difference is whether they are listed in
+the `FunctionsToExport` property of the module manifest.
- if ($present)
- {
- $file = Get-ChildItem -LiteralPath $this.Path
- $this.CreationTime = $file.CreationTime
- $this.Ensure = [Ensure]::Present
- }
- else
- {
- $this.CreationTime = $null
- $this.Ensure = [Ensure]::Absent
- }
+```powershell
+<#
+ Public Functions
+#>
- return $this
- }
+function Get-File {
+ param(
+ [ensure]$ensure,
+
+ [parameter(Mandatory = $true)]
+ [ValidateNotNullOrEmpty()]
+ [String]$path,
- <#
- Helper method to check if the file exists and it is file
- #>
- [bool] TestFilePath([string] $location)
- {
- $present = $true
+ [String]$content
+ )
+ $fileContent = [reason]::new()
+ $fileContent.code = 'file:file:content'
+
+ $filePresent = [reason]::new()
+ $filePresent.code = 'file:file:path'
- $item = Get-ChildItem -LiteralPath $location -ErrorAction Ignore
+ $ensureReturn = 'Absent'
- if ($item -eq $null)
- {
- $present = $false
+ $fileExists = Test-path $path -ErrorAction SilentlyContinue
+
+ if ($true -eq $fileExists) {
+ $filePresent.phrase = "The file was expected to be: $ensure`nThe file exists at path: $path"
+
+ $existingFileContent = Get-Content $path -Raw
+ if ([string]::IsNullOrEmpty($existingFileContent)) {
+ $existingFileContent = ''
}
- elseif ($item.PSProvider.Name -ne "FileSystem")
- {
- throw "Path $($location) is not a file path."
+
+ if ($false -eq ([string]::IsNullOrEmpty($content))) {
+ $content = $content | ConvertTo-SpecialChars
}
- elseif ($item.PSIsContainer)
- {
- throw "Path $($location) is a directory path."
+
+ $fileContent.phrase = "The file was expected to contain: $content`nThe file contained: $existingFileContent"
+
+ if ($content -eq $existingFileContent) {
+ $ensureReturn = 'Present'
}
+ }
+ else {
+ $filePresent.phrase = "The file was expected to be: $ensure`nThe file does not exist at path: $path"
+ $path = 'file not found'
+ }
- return $present
+ return @{
+ ensure = $ensureReturn
+ path = $path
+ content = $existingFileContent
+ Reasons = @($filePresent,$fileContent)
}
+}
- <#
- Helper method to copy file from source to path
- #>
- [void] CopyFile()
- {
- if (-not $this.TestFilePath($this.SourcePath))
- {
- throw "SourcePath $($this.SourcePath) is not found."
+function Set-File {
+ param(
+ [ensure]$ensure = "Present",
+
+ [parameter(Mandatory = $true)]
+ [ValidateNotNullOrEmpty()]
+ [String]$path,
+
+ [String]$content
+ )
+ Remove-Item $path -Force -ErrorAction SilentlyContinue
+ if ($ensure -eq "Present") {
+ New-Item $path -ItemType File -Force
+ if ([ValidateNotNullOrEmpty()]$content) {
+ $content | ConvertTo-SpecialChars | Set-Content $path -NoNewline -Force
}
+ }
+}
- [System.IO.FileInfo] $destFileInfo = New-Object -TypeName System.IO.FileInfo($this.Path)
+function Test-File {
+ param(
+ [ensure]$ensure = "Present",
+
+ [parameter(Mandatory = $true)]
+ [ValidateNotNullOrEmpty()]
+ [String]$path,
+
+ [String]$content
+ )
+ $test = $false
+ $get = Get-File @PSBoundParameters
+
+ if ($get.ensure -eq $ensure) {
+ $test = $true
+ }
+ return $test
+}
- if (-not $destFileInfo.Directory.Exists)
- {
- Write-Verbose -Message "Creating directory $($destFileInfo.Directory.FullName)"
+<#
+ Private Functions
+#>
- <#
- Use CreateDirectory instead of New-Item to avoid code
- to handle the non-terminating error
- #>
- [System.IO.Directory]::CreateDirectory($destFileInfo.Directory.FullName)
- }
+function ConvertTo-SpecialChars {
+ param(
+ [parameter(Mandatory = $true,ValueFromPipeline)]
+ [ValidateNotNullOrEmpty()]
+ [string]$string
+ )
+ $specialChars = @{
+ '`n' = "`n"
+ '\\n' = "`n"
+ '`r' = "`r"
+ '\\r' = "`r"
+ '`t' = "`t"
+ '\\t' = "`t"
+ }
+ foreach ($char in $specialChars.Keys) {
+ $string = $string -replace ($char,$specialChars[$char])
+ }
+ return $string
+}
+```
- if (Test-Path -LiteralPath $this.Path -PathType Container)
- {
- throw "Path $($this.Path) is a directory path"
- }
+### Implementing the methods
- Write-Verbose -Message "Copying $($this.SourcePath) to $($this.Path)"
+The `Get()`, `Set()`, and `Test()` methods are analogous to the `Get-TargetResource`,
+`Set-TargetResource`, and `Test-TargetResource` functions in a script resource.
- # DSC engine catches and reports any error that occurs
- Copy-Item -LiteralPath $this.SourcePath -Destination $this.Path -Force
- }
+As a best practice, minimize the amount of code within the class implementation. Instead,
+move the majority of your code our to public functions in the module, which can then
+be independently tested.
+
+```powershell
+<#
+ This method is equivalent of the Get-TargetResource script function.
+ The implementation should use the keys to find appropriate
+ resources. This method returns an instance of this class with the
+ updated key properties.
+#>
+[File] Get() {
+ $get = Get-File -ensure $this.ensure -path $this.path -content $this.content
+ return $get
+}
+
+<#
+ This method is equivalent of the Set-TargetResource script function.
+ It sets the resource to the desired state.
+#>
+[void] Set() {
+ $set = Set-File -ensure $this.ensure -path $this.path -content $this.content
+}
+
+<#
+ This method is equivalent of the Test-TargetResource script
+ function. It should return True or False, showing whether the
+ resource is in a desired state.
+#>
+[bool] Test() {
+ $test = Test-File -ensure $this.ensure -path $this.path -content $this.content
+ return $test
+}
``` ### The complete file
This code also includes the `CopyFile()` function, a helper function that copies
The complete class file follows. ```powershell
-enum Ensure
-{
+enum ensure {
Absent Present } <#
- This resource manages the file in a specific path.
- [DscResource()] indicates the class is a DSC resource
+ This class is used within the DSC Resource to standardize how data
+ is returned about the compliance details of the machine.
+#>
+class Reason {
+ [DscProperty()]
+ [string] $Code
+
+ [DscProperty()]
+ [string] $Phrase
+}
+
+<#
+ Public Functions
+#>
+
+function Get-File {
+ param(
+ [ensure]$ensure,
+
+ [parameter(Mandatory = $true)]
+ [ValidateNotNullOrEmpty()]
+ [String]$path,
+
+ [String]$content
+ )
+ $fileContent = [reason]::new()
+ $fileContent.code = 'file:file:content'
+
+ $filePresent = [reason]::new()
+ $filePresent.code = 'file:file:path'
+
+ $ensureReturn = 'Absent'
+
+ $fileExists = Test-path $path -ErrorAction SilentlyContinue
+
+ if ($true -eq $fileExists) {
+ $filePresent.phrase = "The file was expected to be: $ensure`nThe file exists at path: $path"
+
+ $existingFileContent = Get-Content $path -Raw
+ if ([string]::IsNullOrEmpty($existingFileContent)) {
+ $existingFileContent = ''
+ }
+
+ if ($false -eq ([string]::IsNullOrEmpty($content))) {
+ $content = $content | ConvertTo-SpecialChars
+ }
+
+ $fileContent.phrase = "The file was expected to contain: $content`nThe file contained: $existingFileContent"
+
+ if ($content -eq $existingFileContent) {
+ $ensureReturn = 'Present'
+ }
+ }
+ else {
+ $filePresent.phrase = "The file was expected to be: $ensure`nThe file does not exist at path: $path"
+ $path = 'file not found'
+ }
+
+ return @{
+ ensure = $ensureReturn
+ path = $path
+ content = $existingFileContent
+ Reasons = @($filePresent,$fileContent)
+ }
+}
+
+function Set-File {
+ param(
+ [ensure]$ensure = "Present",
+
+ [parameter(Mandatory = $true)]
+ [ValidateNotNullOrEmpty()]
+ [String]$path,
+
+ [String]$content
+ )
+ Remove-Item $path -Force -ErrorAction SilentlyContinue
+ if ($ensure -eq "Present") {
+ New-Item $path -ItemType File -Force
+ if ([ValidateNotNullOrEmpty()]$content) {
+ $content | ConvertTo-SpecialChars | Set-Content $path -NoNewline -Force
+ }
+ }
+}
+
+function Test-File {
+ param(
+ [ensure]$ensure = "Present",
+
+ [parameter(Mandatory = $true)]
+ [ValidateNotNullOrEmpty()]
+ [String]$path,
+
+ [String]$content
+ )
+ $test = $false
+ $get = Get-File @PSBoundParameters
+
+ if ($get.ensure -eq $ensure) {
+ $test = $true
+ }
+ return $test
+}
+
+<#
+ Private Functions
+#>
+
+function ConvertTo-SpecialChars {
+ param(
+ [parameter(Mandatory = $true,ValueFromPipeline)]
+ [ValidateNotNullOrEmpty()]
+ [string]$string
+ )
+ $specialChars = @{
+ '`n' = "`n"
+ '\\n' = "`n"
+ '`r' = "`r"
+ '\\r' = "`r"
+ '`t' = "`t"
+ '\\t' = "`t"
+ }
+ foreach ($char in $specialChars.Keys) {
+ $string = $string -replace ($char,$specialChars[$char])
+ }
+ return $string
+}
+
+<#
+ This resource manages the file in a specific path.
+ [DscResource()] indicates the class is a DSC resource
#> [DscResource()]
-class FileResource
-{
+class File {
+
<#
- This property is the fully qualified path to the file that is
- expected to be present or absent.
+ This property is the fully qualified path to the file that is
+ expected to be present or absent.
- The [DscProperty(Key)] attribute indicates the property is a
- key and its value uniquely identifies a resource instance.
- Defining this attribute also means the property is required
- and DSC will ensure a value is set before calling the resource.
+ The [DscProperty(Key)] attribute indicates the property is a
+ key and its value uniquely identifies a resource instance.
+ Defining this attribute also means the property is required
+ and DSC will ensure a value is set before calling the resource.
- A DSC resource must define at least one key property.
+ A DSC resource must define at least one key property.
#> [DscProperty(Key)]
- [string]$Path
+ [string] $path
<# This property indicates if the settings should be present or absent
class FileResource
calls the resource. This is appropriate for optional properties. #> [DscProperty(Mandatory)]
- [Ensure] $Ensure
+ [ensure] $ensure
<#
- This property defines the fully qualified path to a file that will
- be placed on the system if $Ensure = Present and $Path does not
- exist.
-
- NOTE: This property is required because [DscProperty(Mandatory)] is
- set.
+ This property is optional. When provided, the content of the file
+ will be overwridden by this value.
#>
- [DscProperty(Mandatory)]
- [string] $SourcePath
+ [DscProperty()]
+ [string] $content
<#
- This property reports the file's create timestamp.
-
- [DscProperty(NotConfigurable)] attribute indicates the property is
- not configurable in DSC configuration. Properties marked this way
- are populated by the Get() method to report additional details
- about the resource when it is present.
+ This property reports the reasons the machine is or is not compliant.
+ [DscProperty(NotConfigurable)] attribute indicates the property is
+ not configurable in DSC configuration. Properties marked this way
+ are populated by the Get() method to report additional details
+ about the resource when it is present.
#> [DscProperty(NotConfigurable)]
- [Nullable[datetime]] $CreationTime
-
- <#
- This method is equivalent of the Set-TargetResource script function.
- It sets the resource to the desired state.
- #>
- [void] Set()
- {
- $fileExists = $this.TestFilePath($this.Path)
- if ($this.ensure -eq [Ensure]::Present)
- {
- if (-not $fileExists)
- {
- $this.CopyFile()
- }
- }
- else
- {
- if ($fileExists)
- {
- Write-Verbose -Message "Deleting the file $($this.Path)"
- Remove-Item -LiteralPath $this.Path -Force
- }
- }
- }
-
- <#
- This method is equivalent of the Test-TargetResource script function.
- It should return True or False, showing whether the resource
- is in a desired state.
- #>
- [bool] Test()
- {
- $present = $this.TestFilePath($this.Path)
-
- if ($this.Ensure -eq [Ensure]::Present)
- {
- return $present
- }
- else
- {
- return -not $present
- }
- }
+ [Reason[]] $Reasons
<# This method is equivalent of the Get-TargetResource script function.
- The implementation should use the keys to find appropriate resources.
- This method returns an instance of this class with the updated key
- properties.
+ The implementation should use the keys to find appropriate
+ resources. This method returns an instance of this class with the
+ updated key properties.
#>
- [FileResource] Get()
- {
- $present = $this.TestFilePath($this.Path)
-
- if ($present)
- {
- $file = Get-ChildItem -LiteralPath $this.Path
- $this.CreationTime = $file.CreationTime
- $this.Ensure = [Ensure]::Present
- }
- else
- {
- $this.CreationTime = $null
- $this.Ensure = [Ensure]::Absent
- }
-
- return $this
+ [File] Get() {
+ $get = Get-File -ensure $this.ensure -path $this.path -content $this.content
+ return $get
}-
+
<#
- Helper method to check if the file exists and it is file
+ This method is equivalent of the Set-TargetResource script function.
+ It sets the resource to the desired state.
#>
- [bool] TestFilePath([string] $location)
- {
- $present = $true
-
- $item = Get-ChildItem -LiteralPath $location -ea Ignore
- if ($item -eq $null)
- {
- $present = $false
- }
- elseif ($item.PSProvider.Name -ne "FileSystem")
- {
- throw "Path $($location) is not a file path."
- }
- elseif ($item.PSIsContainer)
- {
- throw "Path $($location) is a directory path."
- }
-
- return $present
+ [void] Set() {
+ $set = Set-File -ensure $this.ensure -path $this.path -content $this.content
}-
+
<#
- Helper method to copy file from source to path
+ This method is equivalent of the Test-TargetResource script
+ function. It should return True or False, showing whether the
+ resource is in a desired state.
#>
- [void] CopyFile()
- {
- if (-not $this.TestFilePath($this.SourcePath))
- {
- throw "SourcePath $($this.SourcePath) is not found."
- }
-
- [System.IO.FileInfo] $destFileInfo = new-object System.IO.FileInfo($this.Path)
- if (-not $destFileInfo.Directory.Exists)
- {
- Write-Verbose -Message "Creating directory $($destFileInfo.Directory.FullName)"
-
- <#
- Use CreateDirectory instead of New-Item to avoid code
- to handle the non-terminating error
- #>
- [System.IO.Directory]::CreateDirectory($destFileInfo.Directory.FullName)
- }
-
- if (Test-Path -LiteralPath $this.Path -PathType Container)
- {
- throw "Path $($this.Path) is a directory path"
- }
-
- Write-Verbose -Message "Copying $($this.SourcePath) to $($this.Path)"
-
- # DSC engine catches and reports any error that occurs
- Copy-Item -LiteralPath $this.SourcePath -Destination $this.Path -Force
+ [bool] Test() {
+ $test = Test-File -ensure $this.ensure -path $this.path -content $this.content
+ return $test
}
-} # This module defines a class for a DSC "FileResource" provider.
+}
``` ## Create a manifest
resource. Our manifest looks like this:
```powershell @{
-# Script module or binary module file associated with this manifest.
-RootModule = 'MyDscResource.psm1'
-
-DscResourcesToExport = 'FileResource'
-
-# Version number of this module.
-ModuleVersion = '1.0'
-
-# ID used to uniquely identify this module
-GUID = '81624038-5e71-40f8-8905-b1a87afe22d7'
-
-# Author of this module
-Author = 'Microsoft Corporation'
-
-# Company or vendor of this module
-CompanyName = 'Microsoft Corporation'
-
-# Copyright statement for this module
-Copyright = '(c) 2014 Microsoft. All rights reserved.'
-
-# Description of the functionality provided by this module
-# Description = ''
-
-# Minimum version of the Windows PowerShell engine required by this module
-PowerShellVersion = '5.0'
-
-# Name of the Windows PowerShell host required by this module
-# PowerShellHostName = ''
+ # Script module or binary module file associated with this manifest.
+ RootModule = 'File.psm1'
+
+ # Version number of this module.
+ ModuleVersion = '1.0.0.0'
+
+ # ID used to uniquely identify this module
+ GUID = 'fad0d04e-65d9-4e87-aa17-39de1d008ee4'
+
+ # Author of this module
+ Author = 'Microsoft Corporation'
+
+ # Company or vendor of this module
+ CompanyName = 'Microsoft Corporation'
+
+ # Copyright statement for this module
+ Copyright = ''
+
+ # Description of the functionality provided by this module
+ Description = 'Create and set content of a file'
+
+ # Minimum version of the Windows PowerShell engine required by this module
+ PowerShellVersion = '5.0'
+
+ # Functions to export from this module
+ FunctionsToExport = @('Get-File','Set-File','Test-File')
+
+ # DSC resources to export from this module
+ DscResourcesToExport = @('File')
+
+ # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
+ PrivateData = @{
+
+ PSData = @{
+
+ # Tags applied to this module. These help with module discovery in online galleries.
+ # Tags = @(Power Plan, Energy, Battery)
+
+ # A URL to the license for this module.
+ # LicenseUri = ''
+
+ # A URL to the main website for this project.
+ # ProjectUri = ''
+
+ # A URL to an icon representing this module.
+ # IconUri = ''
+
+ # ReleaseNotes of this module
+ # ReleaseNotes = ''
+
+ } # End of PSData hashtable
+
+ }
} ```
PowerShellVersion = '5.0'
After saving the class and manifest files in the folder structure as described earlier, you can create a configuration that uses the new resource. For information about how to run a DSC configuration, see [Enacting configurations](../pull-server/enactingConfigurations.md). The
-following configuration will check to see whether the file at `c:\test\test.txt` exists, and, if
-not, copies the file from `c:\test.txt` (you should create `c:\test.txt` before you run the
-configuration).
+following configuration will check to see whether the file at `/tmp/test.txt` exists and if the contents
+match the string provided by the property 'Content'. If not, the entire file is written.
```powershell Configuration Test {
- Import-DSCResource -module MyDscResource
- FileResource file
+ Import-DSCResource -module File
+ File testFile
{
- Path = "C:\test\test.txt"
- SourcePath = "c:\test.txt"
+ Path = "/tmp/test.txt"
+ Content = "DSC Rocks!"
Ensure = "Present" } } Test
-Start-DscConfiguration -Wait -Force Test
``` ## Supporting PsDscRunAsCredential
learn Experimental Features https://github.com/MicrosoftDocs/PowerShell-Docs/commits/staging/reference/docs-conceptual/learn/experimental-features.md
--- Previously updated : 04/19/2021 Last updated : 06/22/2021 Title: Using Experimental Features in PowerShell description: Lists the currently available experimental features and how to use them. ---
PS> 1.2 -replace ','
Enables compilation to MOF on non-Windows systems and enables the use of `Invoke-DSCResource` without an LCM.
+In earlier previews of PowerShell 7.2, this feature was enabled by default. Beginning with
+PowerShell 7.2-preview7, the **PSDesiredStateConfiguration** module was removed and this feature is
+disabled by default. To enable this feature you must install the **PSDesiredStateConfiguration**
+v2.0.5 module from the PowerShell Gallery and enable the feature using `Enable-ExperimentalFeature`.
+ ## PSImplicitRemotingBatching This feature examines the command typed in the shell, and if all the commands are implicit remoting