The requirements are that
- All files are examined
- Any files that have an issue are called out
- 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
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
No comments:
Post a Comment