-
Notifications
You must be signed in to change notification settings - Fork 81
Open
Description
First of all awesome work with this module!
It really helped me a lot, but I had to find a workaround for saving multi documents.
My use case is very simple, a K8s manifest with several resources defined.
I Import an existing yaml file, do my changes and by the time I have to save it to a new yaml file this is what I use:
function Save-ArrayAsYamlFile {
<#
.SYNOPSIS
Saves an array of objects as a YAML file.
.PARAMETER InputObject
The array of objects to save as a YAML file.
.PARAMETER OutputPath
The path to save the YAML file.
.EXAMPLE
Save-ArrayAsYamlFile -InputObject $array -OutputPath "path/to/output.yaml"
#>
param(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = "The array of objects to save as a YAML file.")]
[array]$InputObject,
[Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = "The path to save the YAML file.")]
[string] $OutputPath
)
$ErrorActionPreference = "Stop"
try {
Import-YamlModule -Force -NoClobber
Write-Debug "Document count: $($InputObject.Count)"
Write-Debug "Document array: $InputObject"
for ($i = 0; $i -lt $InputObject.Count; $i++) {
if ($i -eq 0) {
Write-Debug ("Writing the first document to '$OutputPath' as:`n{0}`n" -f ($InputObject[$i] | ConvertTo-Yaml) )
$InputObject[$i] | ConvertTo-Yaml | Out-File -Path $OutputPath -Force
Write-Debug "Content saved."
}
else {
Write-Debug ("Appending the next document to '$OutputPath' as:`n{0}`n" -f ($InputObject[$i] | ConvertTo-Yaml) )
"---" | Out-File -Path $OutputPath -Append
$InputObject[$i] | ConvertTo-Yaml | Out-File -Path $OutputPath -Append
Write-debug "Content appended."
}
}
Write-Debug "Updated deployment manifest has been written to '$OutputPath'."
}
catch {
Write-Error -Message "Error in script $($MyInvocation.MyCommand.Name) at line $($MyInvocation.ScriptLineNumber): $($_.Exception.Message)"
throw $_
}
}
Found that when converting from YAML, I get an object of type System.Array, indexed by [int]
So was easy for me to be lazy and generate the YAML for each item at a time, add the "---" at the end, save to the file and keep going
Hope it can serve as base for a much more elegant solution, for now, this one just works like charm for me
Metadata
Metadata
Assignees
Labels
No labels