powershell - 如何将 .ini 文件解析为 PowerShell 变量

标签 powershell

我有以下 .ini 文件(名为 metrics.ini),其中包含一条记录,但将来可能会添加更多记录:

$DatabaseConnection_STR=MYSERVER\MYINSTANCE

我需要将此文件解析为 PowerShell 变量。我可以使用以下内容解析字符串,但我无法创建新的 $DatabaseConnection_STR 变量(基于从 .ini 文件解析的内容)。我不想在我的脚本中对 $DatabaseConnection_STR 进行硬编码——我宁愿让脚本弄清楚,以便将来可以处理其他变量。
# This code assumes that no blank lines are in the file--a blank line will cause an early termination of the read loop

    ########################################
    #
    # Confirm that the file exists on disk
    #
    ########################################

    $IniFile_NME="C:\temp\metrics.ini"

    dir $IniFile_NME

    ########################################
    #
    # Parse the file
    #
    ########################################

    $InputFile = [System.IO.File]::OpenText("$IniFile_NME")

    while($InputRecord = $InputFile.ReadLine())
        {
            # Display the current record

            write-host "`$InputRecord=$InputRecord"
            write-host ""

            # Determine the position of the equal sign (=)

            $Pos = $InputRecord.IndexOf('=')
            write-host "`$Pos=$Pos"

            # Determine the length of the record

            $Len = $InputRecord.Length
            write-host "`$Len=$Len"

            # Parse the record

            $Variable_NME = $InputRecord.Substring(0, $Pos)
            $VariableValue_STR = $InputRecord.Substring($Pos + 1, $Len -$Pos -1)

            write-host "`$Variable_NME=$Variable_NME"
            write-host "`$VariableValue_STR=$VariableValue_STR"

            # Create a new variable based on the parsed information--**the next line fails**

            `$Variable_NME=$VariableValue_STR
        }
    $InputFile.Close()

有任何想法吗?

最佳答案

使用 split 命令可能更简单、更简洁。您还可以将配置值存储在哈希表中:

$config = @{}

Get-Content $IniFile_NME | foreach {
    $line = $_.split("=")
    $config.($line[0]) = $line[1]
}

如果不需要哈希表,您仍然可以使用相同的方法创建变量,但是使用 Powershell 的读取、循环和拆分会更容易。

关于powershell - 如何将 .ini 文件解析为 PowerShell 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5394681/

相关文章:

json - 在Powershell中遍历JSON数据

powershell - 如何在Powershell中使用Get-ChildItem将文件附加到电子邮件

powershell - 有什么方法可以使用 powershell 命令安装虚拟音频电缆应用程序而无需提示消息

powershell - 无法删除变量,因为它已被优化且不可删除 - 释放 COM 对象

json - Microsoft GRAPH 查询列出了使用端点/deviceManagement/deviceHealthScripts 检测脚本内容的不熟悉格式

powershell - 如何根据用户输入重新启动powershell程序

powershell - 对用句点分隔的编号目录进行排序

powershell - 在PowerShell脚本中从Sqlcmd获取错误

powershell - 如何替换文件名中的多个字符串

powershell - 在powershell中替换时正则表达式无效