我有一个变量$gh
,其输出如下。我的意思是我输入$gh
时。我将获得如下所示的值。
PS C:\Windows\system32>$gh
No. Department Name Environment Id Location Name Ready Status Machine Pure Status
1 EMA-MET-CAT5-KY04 Environment-k2345 EMA Enabled GREEN
2 EMA-MET-CAT5-KY03 Environment-k89 EMA Enabled GREEN
3 EMA-EFT-JIU-FC Environment-k3456 EMA Enabled GREEN
4 EMA-MET-CAT5-KY08 Environment-k7890 EMA Not Ready UNKNOWN
5 EMA-MET-CAT5-KY02-ED Environment-k9 EMA Enabled GREEN
$gh
的类型为System.String
,$gh.GetType().fullname
的类型。
我想将部门名称和环境ID中的值放入数组或变量中,以便在查询EMA-MET-CAT5-KY08时可以获取环境ID Environment-k7890。
答案 0 :(得分:1)
假设部门名称和环境ID中没有空格,我将使用正则表达式(regex)在一行的开头查找模式(数字,空格,名称,空格,id)并将其放入哈希表。
PS C:\> $lookup = @{}
PS C:\> [regex]::matches($gh, '(?m)^\d+\s+([^\s]+)\s+([^\s]+)').foreach{
$lookup[$_.groups[1].value] = $_.groups[2].value
}
PS C:\> $lookup
Name Value
---- -----
EMA-EFT-JIU-FC Environment-k3456
EMA-MET-CAT5-KY02-ED Environment-k9
EMA-MET-CAT5-KY04 Environment-k2345
EMA-MET-CAT5-KY03 Environment-k89
EMA-MET-CAT5-KY08 Environment-k7890
PS C:\> $lookup['EMA-MET-CAT5-KY08']
Environment-k7890
答案 1 :(得分:0)
ConvertFrom-Csv
和Select-Object
所需属性$gh = "No. Department Name Environment Id Location Name Ready Status Machine Pure Status
1 EMA-MET-CAT5-KY04 Environment-k2345 EMA Enabled GREEN
2 EMA-MET-CAT5-KY03 Environment-k89 EMA Enabled GREEN
3 EMA-EFT-JIU-FC Environment-k3456 EMA Enabled GREEN
4 EMA-MET-CAT5-KY08 Environment-k7890 EMA Not Ready UNKNOWN
5 EMA-MET-CAT5-KY02-ED Environment-k9 EMA Enabled GREEN
"
$Data = $gh -split [environment]::newline | ForEach-Object {
$_ -replace ' {2,}',','
} | ConvertFrom-csv | Select-Object "Department Name","Environment Id"
$Data | Where-Object 'Department Name' -eq 'EMA-MET-CAT5-KY08'
示例输出:
Department Name Environment Id
--------------- --------------
EMA-MET-CAT5-KY08 Environment-k7890