How to Convert String to Object in PowerShell?

Recently, a PowerShell developer asked me how to convert a string to an object in PowerShell. I explained different methods with examples. In this tutorial, I will show you how to convert string to object in PowerShell with complete examples.

To convert a string to an object in PowerShell using the ConvertFrom-Csv cmdlet, you can parse CSV-formatted data directly into objects. For example, given a CSV string containing information about US states:

$csvString = "State,Capital,Population
California,Sacramento,39538223
Texas,Austin,29145505
Florida,Tallahassee,21538187"

You can convert it to objects with:

$states = $csvString | ConvertFrom-Csv

This will create objects with properties State, Capital, and Population for each line of the CSV data.

Convert String to Object in PowerShell

Now, let me show you different methods to convert string to object in PowerShell.

Method 1: Using ConvertFrom-String

The ConvertFrom-String cmdlet in PowerShell is used to extract and parse structured properties from string content. This cmdlet is useful when the string data has a predictable format.

Example: Parsing CSV Data

Let’s say you have a CSV string containing information about US states:

$csvString = "State,Capital,Population
California,Sacramento,39538223
Texas,Austin,29145505
Florida,Tallahassee,21538187"

To convert this string into objects, you can use ConvertFrom-Csv:

$csvString = @"
State,Capital,Population
California,Sacramento,39538223
Texas,Austin,29145505
Florida,Tallahassee,21538187
"@

$states = $csvString | ConvertFrom-Csv
$states | ForEach-Object { Write-Output "State: $($_.State), Capital: $($_.Capital), Population: $($_.Population)" }

This will output:

State: California, Capital: Sacramento, Population: 39538223
State: Texas, Capital: Austin, Population: 29145505
State: Florida, Capital: Tallahassee, Population: 21538187

You can see the output in the screenshot below after I executed the above PowerShell script:

Convert String to Object in PowerShell

Check out Convert String to Double in PowerShell

Method 2: Using ConvertTo-Json and ConvertFrom-Json

PowerShell provides a straightforward way to work with JSON data using the ConvertTo-Json and ConvertFrom-Json cmdlets.

Example: Parsing JSON Data

Suppose you have a JSON string containing information about some US cities:

$jsonString = @'
[
    {"City": "New York", "State": "NY", "Population": 8419000},
    {"City": "Los Angeles", "State": "CA", "Population": 3980400},
    {"City": "Chicago", "State": "IL", "Population": 2716000}
]
'@

You can convert this JSON string into objects using ConvertFrom-Json:

$jsonString = @'
[
    {"City": "New York", "State": "NY", "Population": 8419000},
    {"City": "Los Angeles", "State": "CA", "Population": 3980400},
    {"City": "Chicago", "State": "IL", "Population": 2716000}
]
'@

$cities = $jsonString | ConvertFrom-Json
$cities | ForEach-Object { Write-Output "City: $($_.City), State: $($_.State), Population: $($_.Population)" }

This will output:

City: New York, State: NY, Population: 8419000
City: Los Angeles, State: CA, Population: 3980400
City: Chicago, State: IL, Population: 2716000

The exact output is shown in the screenshot below after I executed the above PowerShell script using VS code.

PowerShell Convert String to Object

Check out How to Convert Base64 String to Byte Array in PowerShell?

Method 3: Using Custom Parsing Logic

In some cases, you may need to parse strings that don’t fit into common formats like CSV or JSON. For such scenarios, you can write custom parsing logic.

Example: Parsing Custom Log Entries

Imagine you have a log file with entries in the following format:

2024-08-19 10:00:00 - Event: UserLogin - User: jdoe
2024-08-19 10:05:00 - Event: FileUpload - User: jdoe - File: report.pdf

You can parse these entries into objects as follows:

$logEntries = @"
2024-08-19 10:00:00 - Event: UserLogin - User: jdoe
2024-08-19 10:05:00 - Event: FileUpload - User: jdoe - File: report.pdf
"@

$logEntries.Split("`n") | ForEach-Object {
    if ($_ -match '(?<timestamp>.*?) - Event: (?<event>.*?) - User: (?<user>.*?)( - File: (?<file>.*))?$') {
        [PSCustomObject]@{
            Timestamp = $matches.timestamp
            Event     = $matches.event
            User      = $matches.user
            File      = $matches.file
        }
    }
} | ForEach-Object { Write-Output "Timestamp: $_.Timestamp, Event: $_.Event, User: $_.User, File: $_.File" }

This will output:

Timestamp: 2024-08-19 10:00:00, Event: UserLogin, User: jdoe, File: 
Timestamp: 2024-08-19 10:05:00, Event: FileUpload, User: jdoe, File: report.pdf

Read Convert String to Hashtable in PowerShell

Method 4: Using ConvertFrom-StringData

The ConvertFrom-StringData cmdlet is useful for converting strings formatted as key-value pairs into a hash table in PowerShell.

Example: Parsing Configuration Data

Suppose you have a configuration string:

$configString = @"
Server=us-west-1.example.com
Port=443
UseSSL=True
"@

You can convert this string into a hash table using ConvertFrom-StringData:

$configString = @"
Server=us-west-1.example.com
Port=443
UseSSL=True
"@

$config = $configString | ConvertFrom-StringData
$config.GetEnumerator() | ForEach-Object { Write-Output "$($_.Key): $($_.Value)" }

This will output:

Server: us-west-1.example.com
Port: 443
UseSSL: True

You can see the output in the screenshot below:

How to Convert String to Object in PowerShell

Conclusion

In this tutorial, I have explained how to convert strings to objects in PowerShell using various methods like:

  • Using ConvertFrom-String
  • Using ConvertTo-Json and ConvertFrom-Json
  • Using ConvertFrom-StringData

I hope this helps you. Do let me know if you still have any questions in the comment below.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.