ConvertFrom String - PowerShell
Overview
ConvertFrom-String
is a PowerShell cmdlet that converts a string representation of an object to an object of the specified type. It is useful for deserializing data from text or creating objects programmatically.
Syntax
ConvertFrom-String -String <string> -Type <type> [-Delimiter <delimiter>] [-Format <format>] [-Culture <culture>] [-TimeZone <timeZone>]
Options/Flags
-String
The string representation of the object to be converted.
-Type
The type of the object to be created. This can be a .NET type (e.g., [System.Int32]) or a custom type.
-Delimiter
The delimiter that separates the elements in the string. Defaults to a comma.
-Format
The format of the string representation. Valid values are:
- Default: The format is inferred from the context.
- Xml: The string is in XML format.
- Json: The string is in JSON format.
- Csv: The string is in CSV format.
-Culture
The culture to use when converting the string. Defaults to the current culture.
-TimeZone
The time zone to use when converting the string. Defaults to the current time zone.
Examples
Example 1: Convert a comma-separated string to an array of integers
$string = "1,2,3,4,5"
$array = ConvertFrom-String -String $string -Type [int[]]
Example 2: Convert an XML string to an XML document
$xmlString = '<root><element>value</element></root>'
$xmlDocument = ConvertFrom-String -String $xmlString -Format Xml -Type [System.Xml.XmlDocument]
Example 3: Convert a JSON string to a PowerShell object
$jsonString = '{"Name": "John Doe", "Age": 30}'
$object = ConvertFrom-String -String $jsonString -Format Json
Common Issues
- Invalid type: Ensure that the specified type matches the format of the input string.
- Invalid format: The input string must be in the specified format or the conversion will fail.
- Missing delimiter: If a delimiter is specified, the input string must contain the delimiter.
Integration
ConvertFrom-String
can be integrated with other PowerShell commands to create complex data processing pipelines. For example, you can use ConvertFrom-String
to parse data from a file and then use Export-Csv
to export the data to a CSV file.
$data = Get-Content -Path "data.txt"
$objects = ConvertFrom-String -String $data -Type [MyCustomType]
Export-Csv -InputObject $objects -Path "data.csv"