【问题标题】:Powershell Array Split wrong orderPowershell Array Split 错误的顺序
【发布时间】:2017-09-08 17:34:34
【问题描述】:

我正在编写一个脚本来读取状态文件以记录设备的状态。该文件遵循这种“规则”风格: 第一行是“[ACTIVE_JOB]”,然后是每行列出的作业。 然后,有一行写着“[COMPLETE_JOB]”,后面跟着每行列出的已完成的作业。在该列表的末尾,它进入了一些我不关心的其他内容,但“其他内容”的第一行总是以“[”开头。 所以这是交易,当我将这些东西推入一个数组时,然后对数组进行拆分,如果没有活动作业,它似乎将第一个已完成的作业推入活动作业数组。 我只是想创建一个 Active Jobs 和 Completed Jobs 的列表或数组,但是当没有 Active Jobs 时它会绊倒我。

无论如何,这是我正在处理的代码片段(您可以取消注释 PATH 变量集以在测试文件读取之间交替,如果这样可以让事情变得更容易):

#$Path = 'C:\Scripts\NoJOBS.txt'
#$Path = 'C:\Scripts\NoActiveJobs.txt'
#$Path = 'C:\Scripts\ManyJobs.txt'
$StatusFile = Get-Content $path ##  Reads the Status File as an array
#$StatusArray = @()
#$ActiveJobs = @()
#$CompleteJobs = @()
$StatusArray = New-Object System.Collections.ArrayList
$ActiveJobs = New-Object System.Collections.ArrayList
$CompleteJobs = New-Object System.Collections.ArrayList

foreach ($Line in $StatusFile) {
if ($Line -like "*PUBLISHER*") {Break}
#$StatusArray += $Line
$StatusArray.Add($Line)
}
$Seperator = "[ACTIVE_JOB]","[COMPLETE_JOB]"
$ActiveJobs,$CompleteJobs = $StatusArray.Split($Seperator,2,[System.StringSplitOptions]::RemoveEmptyEntries)
#$ActiveJobs = [System.Collections.ArrayList]$ActiveJobs
#$CompleteJobs = [System.Collections.ArrayList]$CompleteJobs
foreach ($Job in $ActiveJobs) {
    #if($job.Contains("[")){ $ActiveJobs.Remove($Job) }
    if($job.Contains("[")){ $ActiveJobs = $ActiveJobs | ? {$_ -ne $job} }

}
foreach ($Job in $CompleteJobs) {
    #if($job.Contains("[")){ $CompleteJobs.Remove($Job) }
    if($job.Contains("[")){ $CompleteJobs = $CompleteJobs | ? {$_ -ne $Job } }

}

如果没有工作,文件的内容如下(另存为 NoJOBS.txt):

[ACTIVE_JOB]
[COMPLETE_JOB]
[PUBLISHER1]
NAME=PP-50 1
STACKER1=62
STACKER2=9
STACKER3=0

如果有 1 个已完成的作业,但没有活动作业(另存为 NoActiveJobs.txt),则如下所示:

[ACTIVE_JOB]
[COMPLETE_JOB]
JOB1=Frank_L_Smith-085149-08092017
[Frank_L_Smith-085149-08092017]
STATUS=99

最后,这是 1 个活动作业和许多已完成作业的样子(另存为 ManyJobs.txt):

[ACTIVE_JOB]
JOB1=April_Ztest-124856-31082017
[COMPLETE_JOB]
JOB1=Mel_R_Smith-141307-31082017
JOB2=Mel_R_Smithe-132029-31082017
JOB3=Melvin_R_Smithy-131037-31082017
JOB5=Will_R_Smith-123534-31082017
[Mel_R_Smith-141307-31082017]
PUBLISHER=PP-50 1
STATUS=4
PUBLICATION_NUMBER=1
COMPLETION_NUMBER=1
ERRORDISC_NUMBER=0

在带有 .NET 4.7 的 Win10 上使用 PSVersion 5.1.14393.1066

【问题讨论】:

  • 看起来您正在尝试使用 ini 语法解析文件。为什么不使用现有的 ini 解析器,例如 PSIni
  • @BenH 嗯,我正在尝试不使用附加组件,但我可以尝试...谢谢您的建议!在某些时候,我的脚本将是一台多台生产计算机,所以我想让设置尽可能简单,但如果它有效,它就会有效!
  • Get-IniContent 将是您需要包含的全部内容,大约 80 行。但是还有很多其他解决方案,比如SO question
  • 我找到了 ScriptingGuys 关于这个的帖子,并且包含了他的足够多的 sn-p 来制作一些漂亮的东西!只需将 INI 扩展要求更改为 txt 就可以了!请提供您的评论作为答案,我将宣布它为答案!谢谢@BenH!!!

标签: arrays powershell windows-10


【解决方案1】:

从 TheScritpingGuy 添加了这个功能,它就像一个魅力!谢谢@BenH!

Function Get-IniContent {  
    <#  
    .Synopsis  
        Gets the content of an INI file  

    .Description  
        Gets the content of an INI file and returns it as a hashtable  

    .Notes  
        Author        : Oliver Lipkau <oliver@lipkau.net>  
        Blog        : http://oliver.lipkau.net/blog/  
        Source        : https://github.com/lipkau/PsIni 
                      http://gallery.technet.microsoft.com/scriptcenter/ea40c1ef-c856-434b-b8fb-ebd7a76e8d91 
        Version        : 1.0 - 2010/03/12 - Initial release  
                      1.1 - 2014/12/11 - Typo (Thx SLDR) 
                                         Typo (Thx Dave Stiff) 

        #Requires -Version 2.0  

    .Inputs  
        System.String  

    .Outputs  
        System.Collections.Hashtable  

    .Parameter FilePath  
        Specifies the path to the input file.  

    .Example  
        $FileContent = Get-IniContent "C:\myinifile.ini"  
        -----------  
        Description  
        Saves the content of the c:\myinifile.ini in a hashtable called $FileContent  

    .Example  
        $inifilepath | $FileContent = Get-IniContent  
        -----------  
        Description  
        Gets the content of the ini file passed through the pipe into a hashtable called $FileContent  

    .Example  
        C:\PS>$FileContent = Get-IniContent "c:\settings.ini"  
        C:\PS>$FileContent["Section"]["Key"]  
        -----------  
        Description  
        Returns the key "Key" of the section "Section" from the C:\settings.ini file  

    .Link  
        Out-IniFile  
    #>  

    [CmdletBinding()]  
    Param(  
        [ValidateNotNullOrEmpty()]  
        [ValidateScript({(Test-Path $_) -and ((Get-Item $_).Extension -eq ".txt")})]  
        [Parameter(ValueFromPipeline=$True,Mandatory=$True)]  
        [string]$FilePath  
    )  

    Begin  
        {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}  

    Process  
    {  
        Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath"  

        $ini = @{}  
        switch -regex -file $FilePath  
        {  
            "^\[(.+)\]$" # Section  
            {  
                $section = $matches[1]  
                $ini[$section] = @{}  
                $CommentCount = 0  
            }  
            "^(;.*)$" # Comment  
            {  
                if (!($section))  
                {  
                    $section = "No-Section"  
                    $ini[$section] = @{}  
                }  
                $value = $matches[1]  
                $CommentCount = $CommentCount + 1  
                $name = "Comment" + $CommentCount  
                $ini[$section][$name] = $value  
            }   
            "(.+?)\s*=\s*(.*)" # Key  
            {  
                if (!($section))  
                {  
                    $section = "No-Section"  
                    $ini[$section] = @{}  
                }  
                $name,$value = $matches[1..2]  
                $ini[$section][$name] = $value  
            }  
        }  
        Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $FilePath"  
        Return $ini  
    }  

    End  
        {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}  
} 

【讨论】:

    猜你喜欢
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多