PowerShell:
Trabajando con YAML
Cómo:
PowerShell, por defecto, no viene con un cmdlet integrado para analizar YAML, pero funciona sin problemas con YAML cuando aprovechas el módulo powershell-yaml o conviertes YAML en un objeto de PowerShell usando ConvertFrom-Json en combinación con una herramienta como yq.
Usando el Módulo powershell-yaml:
Primero, instala el módulo:
Install-Module -Name powershell-yamlPara leer un archivo YAML:
Import-Module powershell-yaml
$content = Get-Content -Path 'config.yml' -Raw
$yamlObject = ConvertFrom-Yaml -Yaml $content
Write-Output $yamlObjectPara escribir un objeto de PowerShell en un archivo YAML:
$myObject = @{
name = "John Doe"
age = 30
languages = @("PowerShell", "Python")
}
$yamlContent = ConvertTo-Yaml -Data $myObject
$yamlContent | Out-File -FilePath 'output.yml'Ejemplo de output.yml:
name: John Doe
age: 30
languages:
- PowerShell
- PythonAnalizando YAML con yq y ConvertFrom-Json:
Otro enfoque implica usar yq, un procesador de YAML de línea de comandos ligero y portátil. yq puede convertir YAML en JSON, el cual PowerShell puede analizar de manera nativa.
Primero, asegúrate de que yq esté instalado en tu sistema.
Luego ejecuta:
$yamlToJson = yq e -o=json ./config.yml
$jsonObject = $yamlToJson | ConvertFrom-Json
Write-Output $jsonObjectEste método es particularmente útil para usuarios que trabajan en entornos multiplataforma o prefieren usar JSON dentro de PowerShell.