有一个包含此内容的文件
SomeText1
SomeCommand -parameterName abc -login def -password geh
SomeText2
您能否建议使用什么PowerShell才能将数组的变量和值(例如键/值对)读入数组
login=def
password=geh
关于该问题的具体之处在于,登录名和密码参数的顺序可能不同,因此我需要找到基于已知键名来定位键/值的方法。另外,我知道我只需要登录名和密码参数以及相关值。
提前非常感谢您的帮助!
附言我打算使用以下命令来读取文件内容,但是可以更改:
$GetFileName = "$env:userprofile\Desktop\Folder\Input.txt"
$content = [IO.File]::ReadAllText($GetFileName)
最佳答案
Select-String
cmdlet提供了使用正则表达式从文件中提取信息的便捷方法:
$inputFile = "$env:userprofile\Desktop\Folder\Input.txt"
# Extract the information of interest and output it as a hashtable.
# Use $ht = Select-String ... to capture the hashtable in a variable.
Select-String -Allmatches '(?<=-(login|password) +)[^ ]+' $inputFile |
ForEach-Object {
foreach ($match in $_.Matches) {
@{ $match.Groups[1] = $match.Value }
}
}
使用示例输入,输出是单个哈希表(如果多行匹配,则将为每行获得一个哈希表):
Name Value
---- -----
login def
password geh
-AllMatches
告诉Select-String
在每一行上搜索多个匹配项。 '(?<=-(login|password) +)[^ ]+'
捕获与参数-login
和-password
相关联的参数,同时在捕获组中捕获参数名称。foreach ($match in $_.Matches)
处理每个匹配项,并构造并输出一个哈希表(@{ ... }
),该哈希表的键是捕获的参数名称,其值是捕获的参数。