基本上我有一个脚本,它试图读取名为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
请提前咨询,谢谢。
如果有人可以在脚本中详细解释“从* .ini文件中获取参数”部分,我也会非常感激,我确实拥有基本的PowerShell知识。
答案 0 :(得分:1)
这部分是有缺陷的:
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])时,它就会创建一个"部分"哈希表。每次遇到键和值(this = that)时,它都会在该部分下添加一个新条目。你最终得到了这个结构:
@{
'COMMANDS' = @{
'commands_file' = 'C:\stuff\working\scratch\commands.txt'
}
}
ini文件并不是最好用的东西,现在已经很老了。 Json,CSV和XML格式往往不会受到基于正则表达式的解析的困扰。