0

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
3
  • Person who downvoted, care to explain what's wrong in my question? Or link me to similar questions if it's a duplicate? I have found 0 similar examples here on SO Commented Mar 21, 2017 at 14:26
  • Can you share the code that you already have? Commented Mar 21, 2017 at 14:40
  • Added my code, it gives the output of the paths but how would I use the path to get the actual size of each file? Commented Mar 21, 2017 at 14:41

1 Answer 1

3

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}}
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for you answer it helped me but I have no idea how. Is your first applied method comparable to 'casting' in programming? I haven't seen anything similar when I was doing my research on casting objects in PowerShell. Is there a name for what you used there?
It's not really casting. You're constructing a new object and fill it with values from another.
Hmm I guess I kind of get it after checking the New-Object cmdlet out. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.