我正在使用一個包含一些資訊的組態檔,如下所示。
User1:[email protected]
User1_Role:Admin
NAME:sdfdsfu4343-234324-ffsdf-34324d-dsfhdjhfd943
ID:xyz@abc-demo-test-abc-mssql
Password:rewrfsdv34354*fds*vdfg435434
我想在我的 Powershell 腳本中將每個值從 *: 拆分為換行*。我正在使用-split '[: \n]'它完全匹配,直到值中沒有 ' '。如果有一個'*',它會一直提取到那個。例如,對于 Password,它僅匹配rewrfsdv34354。這是我的代碼:
$i = 0
foreach ($keyOrValue in $Contents -split '[: *\n]') {
if ($i % 2 -eq 0) {
$varName = $keyOrValue
}
else {
Set-Variable $varName $keyOrValue
}
}
我需要將: 之后的所有字符匹配到 \n。請分享你的想法。
uj5u.com熱心網友回復:
最好在這里執行兩個單獨的拆分,如果代碼由于某種原因出錯,它會使事情變得更容易解決,盡管這$i % 2 -eq 0部分是獲取鍵/值的一種巧妙方法。
我會這樣做:
# Split the Contents variable by newline first
foreach ($line in $Contents -split '[\n]') {
# Now split each line by colon
$keyOrValue = $line -split ':'
# Then set the variables based on the parts of the colon-split
Set-Variable $keyOrValue[0] $keyOrValue[1]
}
uj5u.com熱心網友回復:
您還可以轉換為哈希表并從那里開始,例如:
$h = @{}
gc config.txt | % { $key, $value = $_ -split ' *: *'; $h[$key] = $value }
現在您可以方便地訪問鍵和值,例如:
$h
輸出:
Name Value
---- -----
Password rewrfsdv34354*fds*vdfg435434
User1 [email protected]
ID xyz@abc-demo-test-abc-mssql
NAME sdfdsfu4343-234324-ffsdf-34324d-dsfhdjhfd943
User1_Role Admin
或者只有鍵:
$h.keys
輸出:
Password
User1
ID
NAME
User1_Role
或僅值:
$h.values
輸出:
rewrfsdv34354*fds*vdfg435434
[email protected]
xyz@abc-demo-test-abc-mssql
sdfdsfu4343-234324-ffsdf-34324d-dsfhdjhfd943
Admin
或特定值:
$h['user1'] ", " $h['user1_role']
輸出:
[email protected], Admin
等等
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482794.html
