如何使用powershell获取集合中的特定键值

How to fetch the specific key value inside the collection using powershell

下面给出的命令将输出作为对象

$output = (Invoke-AzVMRunCommand -ResourceGroupName $rgname -Name $vmname -CommandId 'RunPowerShellScript' -ScriptPath 创作。ps1).value

 Output

Mode             : Process
ContextDirectory : 
ContextFile      : 
CacheDirectory   : 
CacheFile        : 
Settings         : {}

Code          : ComponentStatus/StdOut/succeeded
Level         : Info
DisplayStatus : Provisioning succeeded
Message       : @{cluster_name=test01; status=green; timed_out=False; number_of_nodes=3; 
              number_of_data_nodes=3; 
              active_primary_shards=25; active_shards=50; relocating_shards=0; 
              initializing_shards=0; 
              unassigned_shards=0; delayed_unassigned_shards=0; number_of_pending_tasks=0; 
              number_of_in_flight_fetch=0; task_max_waiting_in_queue_millis=0; 
              active_shards_percent_as_number=100.0}
 Time          : 
 Code          : ComponentStatus/StdErr/succeeded
 Level         : Info
 DisplayStatus : Provisioning succeeded

How to get the Message ==> number_of_nodes = 3 and number_of_data_nodes=3 in some variable 所以基于这个值我需要执行一些操作。 谢谢

好的,如果你测试过 $Output.Message 是多行 string like

@{cluster_name=test01; status=green; timed_out=False; number_of_nodes=3; 
              number_of_data_nodes=3; 
              active_primary_shards=25; active_shards=50; relocating_shards=0; 
              initializing_shards=0; 
              unassigned_shards=0; delayed_unassigned_shards=0; number_of_pending_tasks=0; 
              number_of_in_flight_fetch=0; task_max_waiting_in_queue_millis=0; 
              active_shards_percent_as_number=100.0}

你可以像这样将其转换成哈希表:

$data = $Output.Message.Trim("@{}") -replace ';', [environment]::NewLine | ConvertFrom-StringData

如果您使用 $data | Format-Table -AutoSize 将其打印到屏幕上,它看起来像这样:

Name                             Value 
----                             ----- 
number_of_nodes                  3     
task_max_waiting_in_queue_millis 0     
number_of_data_nodes             3     
status                           green 
initializing_shards              0     
active_shards_percent_as_number  100.0 
cluster_name                     test01
delayed_unassigned_shards        0     
active_shards                    50    
unassigned_shards                0     
active_primary_shards            25    
number_of_in_flight_fetch        0     
timed_out                        False 
relocating_shards                0     
number_of_pending_tasks          0 

使用这种哈希表格式,可以很容易地获取不同键的值。 例如:

$data.number_of_nodes            # --> 3
$data.number_of_data_nodes       # --> 3
$data.cluster_name               # --> test01