$file = 'test.properties'
$dict = @{}
foreach ($line in Get-Content $file) {
$words = $line.split('=', 2)
$dict.Add($words[0].Trim(), $words[1].Trim())
}
test.properties
dbpassword=password
dbdatabase=database
dbuser=username
我试图将属性文件读入字典,作为键和值,如下所示。
$dict = @{dbpassword='password', dbdatabase='database}
但是当我尝试运行此代码时。我得到您不能在空值表达式上调用方法。错误。我在哪里做错了?
答案 0 :(得分:1)
通过communicator/src/lib.rs
(基于您的第一个代码)针对给定数量的文件执行此操作的一种方法可能是:
--bin
如果您可以完全确定给定$args
文件中的结构,则还可以使用ConvertFrom-StringData cmdlet。
在最后一个编辑中读取单个文件的地方:
# $in is an Array of filenames, so use [string[]], not [string]
$in = [string[]]$args
$dict = @{}
# get a list of FileInfo objects for files that match the names in the $in variable
$files = @(Get-ChildItem -Filter *.properties -File | Where-Object { $_.Name -in $in })
if ($files.Count) {
$files | ForEach-Object {
foreach ($line in ($_ | Get-Content)) {
# check if this is indeed a "key=Value" line
if ($line -match '.+=.*') {
# get the key and the value and trim them at the same time
$key, $value = $line.split('=', 2).Trim()
# Decide here what to do with duplicates.
# 1) skip adding new values if the key already exists ('First one wins')
if (!($dict.ContainsKey($key))) {
$dict.Add($key, $value)
}
# or
# 2) overwrite any values for keys that already exist ('Last one wins')
# $dict[$key] = $value
}
}
}
}
else {
Write-Host "None of the given files exist"
}
我认为您从.properties
行中收到了错误消息。在那里,您应该将$file = 'test.properties'
if (Test-Path -Path $file -PathType Leaf) {
$dict = ConvertFrom-StringData -StringData (Get-Content $file -Raw)
}
else {
Write-Host "File '$file' does not exist"
}
部分放在方括号之间,如下所示:
foreach ($line in Get-Content $file) {..}
希望这会有所帮助