How to convert command output to the Hashtable format in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To convert any command output to the hashtable in PowerShell, we can first convert the output to the JSON format using the ConvertTo-JSON command, and applying the ConvertFrom-JSON command from the first output will produce an output to the Hashtable.

Example

Get-Service

The above command will give the output in the array format.

Output

Status  Name            DisplayName
------  ----            -----------
Stopped WwanSvc         WWAN AutoConfig
Stopped XblAuthManager  Xbox Live Auth Manager
Stopped XblGameSave     Xbox Live Game Save
Stopped XboxGipSvc      Xbox Accessory Management Service
Stopped XboxNetApiSvc   Xbox Live Networking Service

To convert the above output into the hashtable use the below command,

Example

Get-Service | ConvertTo-Json | ConvertFrom-Json

When you use the above command, it exposes all the properties. To get only a few properties, use the select command.

Get-Service | ConvertTo-Json | ConvertFrom-Json | Select Name, DisplayName, Status, Startype, DependentServices
Name : XblAuthManager
DisplayName : Xbox Live Auth Manager
Status : 1
Startype :
DependentServices : {System.ServiceProcess.ServiceController}
Name : XblGameSave
DisplayName : Xbox Live Game Save
Status : 1
Startype :
DependentServices : {}

You can now store the output and play it like a Hashtable.

raja
Published on 08-Feb-2021 07:52:31
Advertisements