【问题标题】:PowerShell: Looping through an .ini filePowerShell:循环通过 .ini 文件
【发布时间】:2019-04-04 18:21:25
【问题描述】:

我正在编写一个 PowerShell 脚本,它将执行以下操作:

  1. 使用函数获取 ini 数据并将其分配给哈希表(基本上是 Get-IniContent 所做的,但我使用的是在此站点上找到的)。
  2. 检查嵌套的键(不是部分,而是每个部分的键)以查看值“NoRequest”是否存在。
  3. 如果一个部分包含一个 NoRequest 键,并且仅当 NoRequest 值为 false,那么我想返回该部分的名称、NoRequest 键和键的值。例如,“Section [DataStuff] 的 NoRequest 值设置为 false”之类的内容。如果某个部分不包含 NoRequest 键,或者该值设置为 true,则可以跳过它。

我相信我已经完成了前两部分,但我不确定如何进行第三步。这是我到目前为止的代码:

function Get-IniFile 
{  
    param(  
        [parameter(Mandatory = $true)] [string] $filePath  
    )  

    $anonymous = "NoSection"

    $ini = @{}  
    switch -regex -file $filePath  
    {  
        "^\[(.+)\]$" # Section  
        {  
            $section = $matches[1]  
            $ini[$section] = @{}  
            $CommentCount = 0  
        }  

        "^(;.*)$" # Comment  
        {  
            if (!($section))  
            {  
                $section = $anonymous  
                $ini[$section] = @{}  
            }  
            $value = $matches[1]  
            $CommentCount = $CommentCount + 1  
            $name = "Comment" + $CommentCount  
            $ini[$section][$name] = $value  
        }   

        "(.+?)\s*=\s*(.*)" # Key  
        {  
            if (!($section))  
            {  
                $section = $anonymous  
                $ini[$section] = @{}  
            }  
            $name,$value = $matches[1..2]  
            $ini[$section][$name] = $value  
        }  
    }  

    return $ini  
}  

$iniContents = Get-IniFile C:\testing.ini

    foreach ($key in $iniContents.Keys){
    if ($iniContents.$key.Contains("NoRequest")){
        if ($iniContents.$key.NoRequest -ne "true"){
        Write-Output $iniContents.$key.NoRequest
        }
    }
}

当我运行上面的代码时,它给了我以下预期的输出,因为我知道 INI 中有四个 NoRequest 实例,其中只有一个设置为 false:

false

我相信我已经解决了从文件中找到正确值的问题,但我不确定如何继续获取上面第 3 步中提到的正确输出。

【问题讨论】:

    标签: powershell loops if-statement foreach ini


    【解决方案1】:

    你快到了。这将以您提到的形式输出一个字符串:

    $key = "NoRequest" # They key you're looking for
    $expected = "false" # The expected value
    foreach ($section in $iniContents.Keys) {
        # check if key exists and is set to expected value
        if ($iniContents[$section].Contains($key) -and $iniContents[$section][$key] -eq $expected) {
            # output section-name, key-name and expected value
            "Section '$section' has a '$key' key set to '$expected'."
        }
    }
    

    当然,既然你说..

    如果一个部分包含 NoRequest 键,并且仅当 NoRequest 值 是假的,那么我想返回部分的名称,NoRequest 键和键的值。

    .. 输出中的键名和值将始终相同。

    【讨论】:

    • 谢谢,这正是我想要的! “制作输出”部分比我预期的要简单得多,当我自己尝试时,我可能试图让它变得比必要的更复杂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多