我在配置文件(sample.cfg)中有以下内容,
Time_Zone_Variance(Mins):300
Alert_Interval(Mins):2
Server:10.0.0.9
Port:1840
我试图通过在PowerShell中使用:
来存储split
之后的每个值。但我无法产生需要的输出。
谁能告诉我如何使用PowerShell split
解决上述问题?
您可以使用Get-Content
读取文件的内容,然后通过ForEach-Object
管道每一行,然后在每一行使用split命令,获取数组中的第二项,如下所示:
$filename = "sample.cfg"
Get-Content $filename | ForEach-Object {
$_.split(":")[1]
}
产量
300
2
10.0.0.9
1840
更新
我更喜欢@AnsgarWiechers的方法,但是如果你真的需要特定的命名值,你可以创建一个哈希表并用值替换名称:
$configValues = @{
hour = "Time_Zone_Variance(Mins)"
min = "Alert_Interval(Mins)"
server = "Server"
port = "Port"
}
Get-Content $filename | ForEach-Object {
# Courtesy of Ansgar Wiechers
$key, $value = $_ -split ':', 2
foreach($configValuesKey in $($configValues.keys)) {
if ($configValues[$configValuesKey] -eq $key)
{
$configValues[$configValuesKey] = $value
}
}
}
write-host "`nAll Values:"
$configValues
write-host "`nIndividual value:"
$configValues.port
产量
All Values:
Name Value
---- -----
port 1840
min 2
server 10.0.0.9
hour 300
Individual value:
1840
我想你不想只拆分线,但实际上是创建键/值对。这可以这样实现:
$config = @{}
Get-Content 'C:\path\to\sample.cfg' | % {
$key, $value = $_ -split ':', 2
$config[$key] = $value
}
您还可以使用ConvertFrom-StringData
cmdlet:
Get-Content 'C:\path\to\sample.cfg' | % {
ConvertFrom-StringData ($_ -replace ':','=')
}
-replace
操作是必要的,因为ConvertFrom-StringData
期望键和值由=
分开。如果您可以将配置文件中的分隔符从:
更改为=
,则可以使用ConvertFrom-StringData $_
而无需替换。
这个怎么样?
function cut {
param(
[Parameter(ValueFromPipeline=$True)] [string]$inputobject,
[string]$delimiter='\s+',
[string[]]$field
)
process {
if ($field -eq $null) { $inputobject -split $delimiter } else {
($inputobject -split $delimiter)[$field] }
}
}
PS C:\> 'hi:there' | cut -f 0 -d :
hi
PS C:\> 'hi:there' | cut -f 1 -d :
there
PS C:\> 'hi:there' | cut -f 0,1 -d :
hi
there
PS C:\> 'hi:::there' | cut -f 0 -d :+
hi
PS C:\> 'hi there' | cut
hi
there