From db4b5782334dab539af6c2831e8e1acc6648fd25 Mon Sep 17 00:00:00 2001 From: Nitish Janawadkar Date: Tue, 24 Apr 2018 10:16:10 +0530 Subject: [PATCH] Closed the open file stream 1) When convertfrom-yaml is being used on a yaml file and if an error occurs while parsing it, then the file cannot be modified until the powershell session is closed. Fixed it using $streamReader.Close() 2) Extracted the common code in the if and else section of convertfrom-yaml to make code more readable. --- PSYaml/PSYaml.psd1 | 2 +- PSYaml/Public/ConvertFrom-Yaml.ps1 | 23 ++++++++++++++++------- README.md | 1 + 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/PSYaml/PSYaml.psd1 b/PSYaml/PSYaml.psd1 index 9399e7f..54141bf 100644 --- a/PSYaml/PSYaml.psd1 +++ b/PSYaml/PSYaml.psd1 @@ -12,7 +12,7 @@ RootModule = 'PSYaml.psm1' # Version number of this module. -ModuleVersion = '1.0.2' +ModuleVersion = '1.0.3' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/PSYaml/Public/ConvertFrom-Yaml.ps1 b/PSYaml/Public/ConvertFrom-Yaml.ps1 index 08b11fa..5d7bd5e 100644 --- a/PSYaml/Public/ConvertFrom-Yaml.ps1 +++ b/PSYaml/Public/ConvertFrom-Yaml.ps1 @@ -38,17 +38,26 @@ function ConvertFrom-Yaml { BEGIN { } PROCESS { - If($Path){ - $streamReader = [System.IO.File]::OpenText($Path) + try { + If($Path) { + $streamReader = [System.IO.File]::OpenText($Path) + } + Else { + $streamReader = new-object System.IO.StringReader([string]$yamlString) + } + $yamlStream = New-Object YamlDotNet.RepresentationModel.YamlStream $yamlStream.Load([System.IO.TextReader]$streamReader) ConvertFrom-YAMLDocument ($yamlStream.Documents[0]) } - Else{ - $stringReader = new-object System.IO.StringReader([string]$yamlString) - $yamlStream = New-Object YamlDotNet.RepresentationModel.YamlStream - $yamlStream.Load([System.IO.TextReader]$stringReader) - ConvertFrom-YAMLDocument ($yamlStream.Documents[0]) + Catch { + Write-Error $_ + } + Finally { + if ($streamReader.Basestream -ne $null) + { + $streamReader.Close() + } } } END {} diff --git a/README.md b/README.md index 79a875e..f79a090 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ Author: Phil-Factor, Brian Marsh ## Release Notes | Version | Change Log | | :-------: | ----------------------------------------------------------------- | +| 1.0.3 | Closed the open YAML file if error occurs in it during parsing | | 1.0.2 | Reformated several sections for readability, added pester tests | | 1.0.1 | Converted single psm1 file to multiple public/private functions |