【发布时间】:2019-04-04 18:21:25
【问题描述】:
我正在编写一个 PowerShell 脚本,它将执行以下操作:
- 使用函数获取 ini 数据并将其分配给哈希表(基本上是 Get-IniContent 所做的,但我使用的是在此站点上找到的)。
- 检查嵌套的键(不是部分,而是每个部分的键)以查看值“NoRequest”是否存在。
- 如果一个部分包含一个 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