Kahn Kah
Kahn Kah

Reputation: 1453

Create list of items in PowerShell using XML file

I have a XML file in which files are put. My target is to let a PowerShell script show a list of all the files and their properties.

My XML File:

<FileList>
    <File>  
        <Path>C:\File1.txt</Path>
        <MaxSize>20000</MaxSize>
    </File>

    <File>  
        <Path>C:\File2.txt</Path>
        <MaxSize>20000</MaxSize>
    </File>
</FileList>

My output in PowerShell needs to retrieve the file and the size of it.

Example Output:

File1: 4mb (max size= 20000mb)
File2: 3mb (max size= 20000mb)

Later, I later want to create a method to check if each file is below their max size (but first I need to check if I can retrieve them of course)

I'm trying to find a method where I can cast all of the files from the XML to a list or array (of files) in PowerShell but haven't succeeded. What are best practices when trying to achieve this?

Current code:

$files = $configFile.SelectNodes("FileList/File")

foreach ($file in $files) {
  Write-Host $file.Path
}
break

Upvotes: 0

Views: 2234

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Create custom objects from your XML data and the file properties, and collect the objects in a variable, e.g. like this:

$list = foreach ($file in $files) {
  $f = Get-Item $file.Path
  New-Object -Type PSObject -Property @{
    Name    = $f.Name
    Path    = $file.Path
    Size    = $f.Length
    MaxSize = [int]$file.MaxSize
  }
}

Alternatively you could add calculated properties to FileInfo objects:

$list = foreach ($file in $files) {
  Get-Item $file.Path | Select-Object *,@{n='MaxSize';e={[int]$file.MaxSize}}
}

Upvotes: 3

Related Questions