代码之家  ›  专栏  ›  技术社区  ›  Jeremiah Williams

PowerShell:在.ini文件中循环

  •  1
  • Jeremiah Williams  · 技术社区  · 7 年前

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

    1. 使用函数获取ini数据并将其分配给哈希表(基本上是Get IniContent所做的,但我使用的是我在这个站点上找到的一个函数)。
    2. 检查嵌套键(不是节,而是每个节的键)以查看值“NoRequest”是否存在。
    3. 如果一个节包含NoRequest键,并且只有NoRequest值为false,那么我要返回节的名称、NoRequest键和键的值。例如,类似“Section[datastaff]的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中提到的正确输出。

    1 回复  |  直到 7 年前
        1
  •  1
  •   marsze    7 年前

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

    $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'."
        }
    }
    

    当然,既然你说。。

    如果为false,则我要返回节的名称,NoRequest 键和键的值。

    .. 键名和-值在输出中总是相同的。

    推荐文章