如何执行读取 .ini 文件的脚本以从文本文件执行命令

how to execute a script which reads an .ini file to execute a command from a text file

基本上我有一个脚本,它试图读取名为 commands.ini 的配置文件的内容,该文件重定向到一个包含要执行的命令的文本文件。

这是我的脚本内容。ps1 文件:

Param(
[Parameter(Mandatory=$true)][string]$config
)

#Function to read *.ini file and populate an hashtable
Function Get-IniFile ($file) {
  $ini = @{}

  switch -regex -file $file {
    "^\[(.+)\]$" {
  $section = $matches[1].Trim()
      $ini[$section] = @{}
    }
    "^\s*([^#].+?)\s*=\s*(.*)" {
      $name,$value = $matches[1..2]
      # skip comments that start with semicolon:
      if (!($name.StartsWith(";"))) {
        $ini[$section][$name] = $value.Trim()
      }
    }
  }
  return $ini
}

# Getting parameters from *.ini file
$ini = Get-IniFile($config)
$commands_file = $ini['COMMANDS']['commands_file']

# In case any of the files containing the commands: EXIT.
if (Test-Path $commands_file) {
    [string[]]$commands = Get-Content $commands_file
} else {
    Write-Output "# ERROR: cannot read commands_file. Please check configuration. Exiting..."
    Break
}

# This is the command I am trying to run among the various other similar command just to read the ini file 
# and execute the command from the text file which is directed to from the ini file
invoke-expression $commands_file[0]

我也做了一些改动,使用了 invoke-command 命令,但没有用。

这里是commands.ini文件的内容:

[COMMANDS]
; this is where the file to the list of commands to execute will be mentioned
;
commands_file = C:\test\Test\find\commands.txt

和commands.txt文件的内容:

'Get-Process | Where-Object { $_.Name -like "a*"}'

但无论我做了多少更改,我总是会遇到同样的错误,我确信我的哈希表的调用方式有问题或其他原因,但我无法弄清楚到底是什么导致了这个错误。

PowerShell 中显示的错误: Error

C : The term 'C' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ C
+ ~
    + CategoryInfo          : ObjectNotFound: (C:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

请大家多多指教,先谢谢了。

如果有人能详细解释脚本中的 "Getting parameters from *.ini file" 部分,我将不胜感激,我确实具备基本的 PowerShell 知识。

这部分有缺陷:

invoke-expression $commands_file[0]

$commands_file 此时包含一个字符串 "C:\test\Test\find\commands.txt",因此当它使用 [0] 对其进行索引时,它会选择第一个字符(因为可以通过索引访问字符串)。第一个字符是 C,因此它会尝试 运行 Invoke-Expression 针对它,您会收到错误消息。

仅仅删除索引 ([0]) 是不够的,您只需打开文本文件即可。要按原样使用它,您需要 运行:

Invoke-Expression (Get-Content $commands_file -Raw)

您可以简单地将 $commands_file(在 ini 中)更改为 .ps1,然后您就可以调用它而不必担心 Invoke-Expression 和 Get-Content。

ini 文件解析器相当简单。它一次读取 ini 文件一行并将内容加载到嵌套哈希表(键值对)中。每次遇到方括号 ([something]) 中的值时,它都会创建一个 "section" 哈希表。每次遇到键和值(this = that)时,它都会在该部分下添加一个新条目。你最终得到这个结构:

@{
    'COMMANDS' = @{
        'commands_file' = 'C:\stuff\working\scratch\commands.txt'
    }
}

ini 文件不是最好用的东西,现在已经过时了。 Json、CSV 和 XML 格式往往较少受到基于正则表达式的解析的困扰。