使用XML文件在PowerShell中创建项目列表 [英] Create list of items in PowerShell using XML file
问题描述
我有一个放置文件的XML文件.我的目标是让PowerShell脚本显示所有文件及其属性的列表.
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.
我的XML文件:
<FileList>
<File>
<Path>C:\File1.txt</Path>
<MaxSize>20000</MaxSize>
</File>
<File>
<Path>C:\File2.txt</Path>
<MaxSize>20000</MaxSize>
</File>
</FileList>
我在PowerShell中的输出需要检索文件及其大小.
My output in PowerShell needs to retrieve the file and the size of it.
示例输出:
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)
我试图找到一种方法,可以将XML中的所有文件强制转换为PowerShell中的列表或数组(文件),但未成功.尝试实现此目标的最佳做法是什么?
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?
当前代码:
$files = $configFile.SelectNodes("FileList/File")
foreach ($file in $files) {
Write-Host $file.Path
}
break
推荐答案
根据您的XML数据和文件属性创建自定义对象,然后将这些对象收集到一个变量中,例如像这样:
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
}
}
或者,您可以将计算的属性添加到FileInfo
对象:
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}}
}
这篇关于使用XML文件在PowerShell中创建项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!