PowerShell:
Working with YAML
How to:
PowerShell, by default, doesn’t come with a built-in cmdlet for parsing YAML, but it works seamlessly with YAML when you leverage the powershell-yaml
module or convert YAML into a PowerShell object using ConvertFrom-Json
in combination with a tool like yq
.
Using powershell-yaml
Module:
First, install the module:
Install-Module -Name powershell-yaml
To read a YAML file:
Import-Module powershell-yaml
$content = Get-Content -Path 'config.yml' -Raw
$yamlObject = ConvertFrom-Yaml -Yaml $content
Write-Output $yamlObject
To write a PowerShell object into a YAML file:
$myObject = @{
name = "John Doe"
age = 30
languages = @("PowerShell", "Python")
}
$yamlContent = ConvertTo-Yaml -Data $myObject
$yamlContent | Out-File -FilePath 'output.yml'
Sample output.yml
:
name: John Doe
age: 30
languages:
- PowerShell
- Python
Parsing YAML with yq
and ConvertFrom-Json
:
Another approach involves using yq
, a lightweight and portable command-line YAML processor. yq
can convert YAML into JSON, which PowerShell can natively parse.
First, ensure yq
is installed on your system.
Then run:
$yamlToJson = yq e -o=json ./config.yml
$jsonObject = $yamlToJson | ConvertFrom-Json
Write-Output $jsonObject
This method is particularly useful for users who work in cross-platform environments or prefer using JSON within PowerShell.