Wednesday, February 13, 2019

Passing variables by Reference in PowerShell

I often have to write PowerShell scripts that perform some operation on a set of files. Sometimes I need to validate something about the files, for example that they are all well formed XML. 

The requirements are that 
  1. All files are examined
  2. Any files that have an issue are called out
  3. The script returns a failure if one or more files fails the check.
To examine all of the files I use Get-ChildItem and then pipe that into a function to do the verification. 


Get-Childitem -path $directoryToCheck -filter '*.xml' -recurse | VerifyXMLFileFormat

and VerifyXMLFileFormat looks like



function VerifyXMLFileFormat {     foreach ($o in $input)     {         Write-host 'Reading:' $o.FullName
        try         {             [xml]$xml = Get-Content $o.FullName         }         catch         {             Write-Host "$($o.FullName) is not a valid XML file"         }     } }

The challenge I have run into is that I have been unable to easily set a value in the called function and use it outside of the function because of how it is called as part of a pipeline. If in the catch block I use Write-Host-Error, or return $false, or throw, then not all of the files are processed. 

What I wanted was to pass a variable by reference so that VerifyXMLFileFormat can set the value and the calling function can reference the value. To do that I had to add a [REF] and access the .Value of the variable like this in the function


        catch         {             Write-Host "$($o.FullName) is not a valid XML file"             $invalidFileFound.Value = $true         }

Now I call the function like this


[bool] $invalidFileFound = false
Get-Childitem -path $directoryToCheck -filter '*.xml' -recurse | VerifyXMLFileFormat ([REF]$invalideFileFound)

Using that I can now meet all three requirements that I had


The 2024 State of DevOps Report and the Importance of Internal Development Platforms

On the State of DevOps Report The State of DevOps Report, published annually by the DevOps Research and Assessment (DORA) team, has been a c...