从 .ini 文件导入空设置
importing empty setting from .ini file
这很简单,但我无法理解它,
我正在尝试将 .ini 文件导入 powershell
我得到了这个列表
[IT]
\foo\bar1=123.123.123.123
\foo\bar2
[Marketing]
\foo\bar3=123.123.123.123
\foo\bar4=123.123.123.123
和这段代码
function Get-IniContent ($filePath)
{
$ini = @{}
switch -regex -file $FilePath
{
"^\[(.+)\]" # Section
{
$section = $matches[1]
$ini[$section] = @{}
$CommentCount = 0
}
"^(;.*)$" # Comment
{
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
}
"(.+?)\s*=(.*)" # Key
{
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
}
}
return $ini
}
我只是找不到正确的正则表达式只能得到“\foo\bar2”
这将匹配所有 \foo\bar
\\foo\bar\d?
如果你想匹配\foo\bar2
,使用
\\foo\bar2
你会认为你可以将 =
设为可选,一切都会很漂亮。
"(.+?)\s*=?(.*)"
然而,当您尝试使 =
可选的正则表达式“(.+?)”时,您将吞噬整个字符串,从而更难使用 $matches
逻辑拆分内容你有过。您应该更改开关,以便它只匹配每行一次。然后您可以假设默认操作将在 "key" 上执行,因为所有其他行都已经匹配。请注意下面的 continue
s
function Get-IniContent ($filePath)
{
$ini = @{}
switch -regex -file $FilePath
{
"^\[(.+)\]" # Section
{
$section = $matches[1]
$ini[$section] = @{}
$CommentCount = 0
continue
}
"^(;.*)$" # Comment
{
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
continue
}
default # Key
{
$name,$value = $_.split("=")
$ini[$section][$name] = $value
}
}
return $ini
}
示例输出
Name Value
---- -----
IT {\foo\bar1, \foo\bar2}
Marketing {\foo\bar3, \foo\bar4}
(Get-IniContent c:\temp\file.ini).IT
Name Value
---- -----
\foo\bar1 123.123.123.123
\foo\bar2
这很简单,但我无法理解它, 我正在尝试将 .ini 文件导入 powershell
我得到了这个列表
[IT] \foo\bar1=123.123.123.123 \foo\bar2 [Marketing] \foo\bar3=123.123.123.123 \foo\bar4=123.123.123.123
和这段代码
function Get-IniContent ($filePath)
{
$ini = @{}
switch -regex -file $FilePath
{
"^\[(.+)\]" # Section
{
$section = $matches[1]
$ini[$section] = @{}
$CommentCount = 0
}
"^(;.*)$" # Comment
{
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
}
"(.+?)\s*=(.*)" # Key
{
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
}
}
return $ini
}
我只是找不到正确的正则表达式只能得到“\foo\bar2”
这将匹配所有 \foo\bar
\\foo\bar\d?
如果你想匹配\foo\bar2
,使用
\\foo\bar2
你会认为你可以将 =
设为可选,一切都会很漂亮。
"(.+?)\s*=?(.*)"
然而,当您尝试使 =
可选的正则表达式“(.+?)”时,您将吞噬整个字符串,从而更难使用 $matches
逻辑拆分内容你有过。您应该更改开关,以便它只匹配每行一次。然后您可以假设默认操作将在 "key" 上执行,因为所有其他行都已经匹配。请注意下面的 continue
s
function Get-IniContent ($filePath)
{
$ini = @{}
switch -regex -file $FilePath
{
"^\[(.+)\]" # Section
{
$section = $matches[1]
$ini[$section] = @{}
$CommentCount = 0
continue
}
"^(;.*)$" # Comment
{
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
continue
}
default # Key
{
$name,$value = $_.split("=")
$ini[$section][$name] = $value
}
}
return $ini
}
示例输出
Name Value
---- -----
IT {\foo\bar1, \foo\bar2}
Marketing {\foo\bar3, \foo\bar4}
(Get-IniContent c:\temp\file.ini).IT
Name Value
---- -----
\foo\bar1 123.123.123.123
\foo\bar2