Powershell 自定义对象

Powershell Custom object

   This data is store in a file

    AUTOM01-AYEHU1:No Updates Available
    AUTOM01-AYEHU2:No Updates Available
    AUTOM01-AYEHU3:No Updates Available
    AUTOM01-AYEHU4:No Updates Available
    AUTOM01-AYEHU5:No Updates Available
    AUTOM01-AYEHU6:No Updates Available
    
    

我在一个文件中有一个上述数据集,我需要创建 2 个名为 (SERVERNAME,STATUS) 的 powershell 自定义对象,并将相应的数据放入其中。

之前:是服务器名,其余是状态

如果你真的想要 2 个对象,这就是答案

$fileLines = @("AUTOM01-AYEHU1:No Updates Available","AUTOM01-AYEHU2:No Updates Available")

 $serverArray = [System.Collections.ArrayList]::new()
 $statusArray = [System.Collections.ArrayList]::new()
 foreach($fileLine in $fileLines)
 {
    $splittedLine = $fileLine.split(":")
    $serverArray.Add([PSCustomObject]@{ServerName=$splittedLine[0]})
    $statusArray.add([PsCustomobject]@{Status=$splittedLine[1]})
 }

在 $serverArray 和 $statusArray 中找到它们

正如评论,你可以简单地做

$result = (Get-Content -Path 'thefile.txt' -Raw) -replace ':', '=' | ConvertFrom-StringData

ConvertFrom-StringData return 一个哈希表,默认情况下,其中的项目是无序的。
由于您希望保持输入文件中的顺序,因此您可能希望改用它:

$result = Get-Content -Path 'D:\Test\thefile.txt' | ConvertFrom-String -Delimiter ':' -PropertyNames Server, Status

至 return PSCustomObject 数组:

Server         Status              
------         ------              
AUTOM01-AYEHU1 No Updates Available
AUTOM01-AYEHU2 No Updates Available
AUTOM01-AYEHU3 No Updates Available
AUTOM01-AYEHU4 No Updates Available
AUTOM01-AYEHU5 No Updates Available
AUTOM01-AYEHU6 No Updates Available