Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine XML type in Powershell?

I'm writing a script that is supposed to look at the content of a file and determine if it is a (well formed) XML or not. I found a page on [ss64.com][1] that this is quite easy to do:

>32 -is [int]
True

The thing is however that I can only test this by casting the left-side for XML files:

>[xml](Get-Content c:\Path\To\xml_file.xml) -is [xml]
False

...which in this case would be rather pointless: if the file is XML, the casting will already prove this, else throw an exception. I therefore wonder: is there any way to determine XML files in Powershell in a True-False way?

like image 897
gustafbstrom Avatar asked Dec 17 '22 01:12

gustafbstrom


2 Answers

Try the -as operator:

[bool]((Get-Content c:\Path\To\xml_file.xml) -as [xml])
like image 196
Shay Levy Avatar answered Dec 27 '22 14:12

Shay Levy


function Is-Valid-XML 
{
    param ([string] $path)

    $xml = New-Object System.Xml.XmlDocument
    try 
    {
        $xml.Load($path)
        $valid = $true
    }

    catch
    {
        $valid = $false
    }

    return $valid
}
like image 22
David Brabant Avatar answered Dec 27 '22 13:12

David Brabant