gpt4 book ai didi

powershell - 如何在powershell中的csv中包含所有数组对象的所有属性

转载 作者:行者123 更新时间:2023-12-04 01:50:16 25 4
gpt4 key购买 nike

我有一个 Powershell 脚本,它读取一个文本文件,其中包含对共享及其属性的单行描述。

然后,它会为每个共享添加一个对象到数组,并带有属性。

我最终得到了一系列共享,其中许多具有共同属性,但也有一些仅出现在少数共享中。

当我将完成的数组通过管道传输到 Export-CSV 时,生成的 CSV 只有与数组中第一个对象的属性相匹配的列。

感谢收到的任何想法/帮助。

代码如下:

$shares_only = gc \\server\share\SHARES.txt | where {$_ -match '^*TYPE = DISK'}

$share_index = @()

$shares_only |foreach {

$sharename = ($_.Split(" ")[1])
$_ -match '\([\w\s.,"=<>()\/\*\+\-]*\);'|out-null

$shareparams = $matches[0]

$paramlist = ($shareparams.Substring(1,($shareparams.Length -3))).Split(",")

$obj = $null
$obj = New-Object System.Object

$obj | Add-Member -type NoteProperty -Name NAME -Value $sharename

$paramlist | foreach {
$obj `
| Add-Member -type NoteProperty -Name ($_.Split("=")[0]) -Value ($_.Split("=")[1])
}
$share_index += $obj
}

$share_index | Select * | Export-CSV -notype \\server\share\Shares.csv

这里以数组中的前两个对象为例(使用$share_index[0..2]输出到控制台):

NAME          : _ACCTEST_
TYPE : DISK
PREFIX : (<USERCODE>)
AREABYTES : 184320
ACCESS : ALL
FAMILY : ACCTESTPACK
DOWNSIZEAREA : TRUE

NAME : _HOME_
TYPE : DISK
PREFIX : (<USERCODE>)
COMMENT : Private user files
AREABYTES : 184320
ACCESS : ALL -EXTRACT
FAMILY : <FAMILY>
DOWNSIZEAREA : TRUE
ALLOWGUESTACCESS : TRUE

这是 CSV 的前 3 行:

"NAME","TYPE ","PREFIX ","AREABYTES ","ACCESS ","FAMILY ","DOWNSIZEAREA "
"_ACCTEST_"," DISK "," (<USERCODE>) "," 184320 "," ALL "," ACCTESTPACK "," TRUE "
"_HOME_"," DISK "," (<USERCODE>) "," 184320 "," ALL -EXTRACT "," <FAMILY> "," TRUE "

您可以看到 COMMENTALLOWGUESTACCESS 属性丢失了,尽管它们在 _HOME_ 共享的数组中。

编辑: 接受了@JPBlancs 答案的略微修改版本,所以我的代码的最后两行现在是:

$fixed_index = $share_index | Sort-Object -Property @{expression={(($_.psobject.Properties)|Measure-Object).count}} -Descending | ConvertTo-CSV -notype
$fixed_index | ConvertFrom-CSV | Sort -Property Name | Export-CSV -notype \\server\share\Shares.csv

因此,按照建议完成,然后在新对象中转换为 CSV。然后,将该对象从 CSV 转换回,保留新属性,再次对名称排序以获得我需要的字母列表,然后再次导出到 CSV。

给我,例如:

"NAME","TYPE","PREFIX","PUBLIC","COMMENT","AREABYTES","ACCESS","FAMILY","DOWNSIZEAREA","ALLOWGUESTACCESS"
"_ACCTEST_"," DISK "," (<USERCODE>) ","",""," 184320 "," ALL "," ACCTESTPACK "," TRUE ",
"_HOME_"," DISK "," (<USERCODE>) ",""," Private user files "," 184320 "," ALL -EXTRACT "," <FAMILY> "," TRUE "," TRUE "

最佳答案

Export-CsvConvertTo-Csv 似乎只接受发送给它们的对象之间的属性联合。我认为您必须解析文本文件并编译所有属性的列表,并且在创建对象时将任何缺失的属性值设置为 null。

关于powershell - 如何在powershell中的csv中包含所有数组对象的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17959386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com