我正在使用将执行以下操作的PowerShell脚本:
我相信我已经完成了前两个部分,但是不确定如何进行第三步。这是我到目前为止的代码:
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'."
}
}
当然,既然你说了..
..键名和-value在输出中将始终相同。
关于powershell - PowerShell:循环浏览.ini文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53085819/