【问题标题】:Powershell Foreach loop in INI fileINI 文件中的 Powershell Foreach 循环
【发布时间】:2020-11-16 11:40:14
【问题描述】:

我实际上是使用 inni 文件编写 Powershell 脚本的新手,我需要创建一个允许我获取多个变量的 foreach 循环。 让我解释 : 我有一个包含多个组(Active Directory 组)的 INI 文件,我需要我的 powershell 脚本来提取那些名称为(group1、group2、group3 等)的组。

我尝试了这段代码,但没有任何结果。

$i=0
$query = $configfile.Domain.group.$i

ForEach($query in $configfile.Domain.group)
{
$i++

write-host $query.$i

}

看起来我很糟糕,有什么建议吗?

【问题讨论】:

  • 什么是$configfile
  • $configfile = Get-IniFile .\Variables.ini
  • 这是存储我的变量的 .ini 文件
  • 那么Get-IniFile 来自哪里?而ini文件的内容又是怎样的呢?

标签: powershell foreach


【解决方案1】:

循环中的 $query 声明了一个新变量,它隐藏了循环外声明的变量。

没有ini文件的例子,我只能猜测,但你可以尝试用write-host $query替换循环块。

这至少会告诉你发生了什么。

【讨论】:

  • ini 文件如下所示:[Groups] group1=example group2=example1 group3=example2 group4=example3 group5=example4 group6=example5
【解决方案2】:

如果您的 INI 文件如下所示:

[Groups]
group1=example
group2=example1
group3=group1
group4=example3
group5=group2
group6=example5

那么你可以像这样使用here中的函数:

function Get-IniContent ($filePath) {
    $ini = @{}
    switch -regex -file $FilePath {
        "^\[(.+)\]" # Section
        {
            $section = $matches[1]
            $ini[$section] = @{}
            $CommentCount = 0
        }
        "^(;.*)$" # Comment
        {
            $value = $matches[1]
            $CommentCount = $CommentCount + 1
            $name = "Comment" + $CommentCount
            $ini[$section][$name] = $value
        }
        "(.+?)\s*=(.*)" # Key
        {
            $name,$value = $matches[1..2]
            $ini[$section][$name] = $value
        }
    }
    return $ini
}

# the data returned is a Hashtable where each entry is listed 
# under a certain section name. This data is UNORDERED by default
$data = Get-IniContent -filePath 'D:\Test\groups.ini'

获取 ini 文件中“组”部分下的所有组名

$data['Groups'].Keys | ForEach-Object { $data['Groups'][$_]}

输出:

example
example5
group2
group1
example1
example3

或者仅获取某些看起来像“组”的组名

($data['Groups'].GetEnumerator() | Where-Object { $_.Value -like 'group*' }).Value   
# or alternatively do:
# $data['Groups'].Keys | Where-Object { $data['Groups'][$_] -like 'group*' } | ForEach-Object { $data['Groups'][$_] }

输出:

group2
group1

如果要对找到的组名进行排序,请附加 | Sort-Object

【讨论】:

  • 谢谢!我已经找到了可以使用的东西,看起来就像你刚刚做的那样。
猜你喜欢
  • 2019-04-04
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 2019-11-12
  • 1970-01-01
相关资源
最近更新 更多