gpt4 book ai didi

powershell - PowerShell:循环浏览.ini文件

转载 作者:行者123 更新时间:2023-12-02 23:53:14 24 4
gpt4 key购买 nike

我正在使用将执行以下操作的PowerShell脚本:

  • 使用一个函数来获取ini数据并将其分配给哈希表(基本上是Get-IniContent的功能,但是我使用的是在此站点上找到的数据)。
  • 检查嵌套键(不是节,而是每个节的键),以查看是否存在值“NoRequest”。
  • 如果一个节包含一个NoRequest键,并且仅当NoRequest值为false时,我才想返回该节的名称,NoRequest键和键的值。例如,类似“部分[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中提到的正确输出。

    最佳答案

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

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

    当然,既然你说了..

    If a section contains a NoRequest key, and ONLY IF the NoRequest value is false, then I want to return the name of the section, the NoRequest key, and the key's value.



    ..键名和-value在输出中将始终相同。

    关于powershell - PowerShell:循环浏览.ini文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085819/

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