[英]PowerShell: Looping through an .ini file
I'm working on a PowerShell script that will do the following:我正在编写一个 PowerShell 脚本,它将执行以下操作:
I believe I've accomplished the first two parts of this, but I'm unsure of how to proceed with the third step.我相信我已经完成了前两部分,但我不确定如何进行第三步。 Here's the code I have so far:
这是我到目前为止的代码:
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
}
}
}
When I run the run the above code, it gives me the following expected output, since I know there are four instance of NoRequest in the INI and only one of them is set to false:当我运行上面的代码时,它给了我以下预期的输出,因为我知道 INI 中有四个 NoRequest 实例,其中只有一个设置为 false:
false
I believe I've solved the problem of finding the correct value(s) from the file, but I'm unsure of how to proceed with getting the correct output as mentioned in step 3 above.我相信我已经解决了从文件中找到正确值的问题,但我不确定如何继续获得上面步骤 3 中提到的正确输出。
You were almost there.你快到了。 This will output a string in the form you mentioned:
这将以您提到的形式输出一个字符串:
$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'."
}
}
Of course, since you said..当然,既然你说..
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.
如果某个部分包含 NoRequest 键,并且仅当 NoRequest 值为 false,那么我想返回该部分的名称、NoRequest 键和键的值。
.. the key-name and -value will always be the same in the output. .. key-name 和 -value 在输出中总是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.