2017-12-22 7 views
1

초급 질문입니다. PowerShell을 사용하여 JSON에서 특정 값을 가져 오려고합니다. 특히 서비스를 나열하려고합니다. TEST00000FAKE 만 해당됩니다.Powershell로 JSON에서 값 가져 오기

TEST00000             FAKE   
---------             ----   
@{Enabled=True; Processed=2; Sent=3; Failed=4; Downloaded=5} @{Enabled=True} 

가 어떻게 서비스 만의 목록을 얻을 수 있습니다 : 나는 아래의 스크립트를 실행하면

,이 얻을?

더 중요한 것은 키/값이 인 서비스 만 나열하는 방법입니다. Enabled = True 내부에 있습니까?

$JSON = '{ 
    "Envs": { 
    "DEV": { 
     "Services": { 
     "TEST00000": { 
      "Enabled": true, 
      "Processed": 2, 
      "Sent": 3, 
      "Failed": 4, 
      "Downloaded": 5 
     }, 
     "FAKE": { 
      "Enabled": true 
     } 
     } 
    } 
    }, 
    "Component": { 
    "Digger": { 
     "Envs": { 
     "DEV": { 
      "DownloadE": 4 
     } 
     } 
    } 
    } 
}' 

$jsonobj = ConvertFrom-Json -inputObject $JSON 

$jsonobj.Envs.DEV.Services 

답변

3

Services 속성의 이름을 얻으려면. user2734259처럼 Get-Member을 사용하거나 객체에 대한 유용한 정보를 저장하는 psobject 속성을 사용할 수 있습니다.

$ServiceNames = $jsonobj.Envs.DEV.Services.psobject.properties.name 

당신이 Enabled

$jsonobj.Envs.DEV.Services.psobject.properties.name | ForEach-Object { 
    $_ | Where-Object {$jsonobj.Envs.DEV.Services.$_.Enabled -eq $True} 
} 
+0

답장을 보내 주셔서 감사합니다. 매우 재미있었습니다.이 정보를 찾으려고 많은 시간을 보냈는데, 어떻게 배웠습니까? 이것에 대해 더 자세히 읽을 수있는 곳은 어디입니까? (또는 PS 도움말 내용을 사용하는 기술을 배우고 있습니까?) – ToastMan

+1

@ ToastMan 나는 Don Jones Month of Lunches 책으로 개인적으로 시작했습니다. 숨겨진'psobject' 속성에 대해 알았으므로, 누군가의 답변에서 (내가 누군지 기억하기에는 너무 오랜 동안) 선택했습니다. – BenH

+0

흠 마지막 부분이 작동하지 않는 것 같습니다 : $ _ | Where-Object {$ jsonobj.Envs.DEV.Services. $ _. Enabled -eq 'false'} <- 어쨌든 서비스를 나열합니다 (-eq 'false'로) – ToastMan

1

이것은 관계없이 JSON에서 서비스 이름의, 동적으로 이름을 얻을 수 있도록해야합니다 : 아무것도 불분명 한 경우

$JSON = '{ 
    "Envs": { 
    "DEV": { 
     "Services": { 
     "TEST00000": { 
      "Enabled": true, 
      "Processed": 2, 
      "Sent": 3, 
      "Failed": 4, 
      "Downloaded": 5 
     }, 
     "FAKE": { 
      "Enabled": true 
     } 
     } 
    } 
    }, 
    "Component": { 
    "Digger": { 
     "Envs": { 
     "DEV": { 
      "DownloadE": 4 
     } 
     } 
    } 
    } 
}' 

$jsonobj = ConvertFrom-Json -inputObject $JSON 
$enabledServices = $NULL 
$disabledServices = $NULL 

# Since the service names are arbitrary 
# create an object that contains only 
# objects whose MemberType is NoteProperty 

$strServiceNames = @($($jsonobj.Envs.DEV.Services | Get-Member | Where { $_.MemberType -eq "NoteProperty" } | Select Name).Name) 
$pscoServiceNames = [PSCustomObject]@{Names=$strServiceNames} 
foreach($serviceName in $pscoserviceNames.Names) 
{ 
    # dynamically access the service name 
    # from $jsonobj.Envs.DEV.Services 

    $serviceStatus = $jsonobj.Envs.DEV.Services.$serviceName.Enabled 

    # parse results based on value of .Enabled 

    if($serviceStatus.ToString() -eq "True") 
    { 
     $enabledServices = [Array]$enabledServices + [PSCustomObject]@{Name = $serviceName;Enabled = $serviceStatus} 
    } 
    else 
    { 
     $disabledServices = [Array]$disabledServices + [PSCustomObject]@{Name = $serviceName;Enabled = $serviceStatus} 
    } 
} 

# Show the results 

Write-Output "`nEnabled Services`n" 
$enabledServices | Format-List 
Write-Output "`nDisabled Services`n" 
$disabledServices | Format-List 

이 알려와 여기

코드입니다 더 자세히 설명 할 수 있습니다. 희망이 도움이됩니다. 행복한 '포격!

+0

가 답장을 너무 감사합니다 하위 속성에 그들에 당신이 루프 할 수있는 이름과 필터를 일단 , 이것은 매우 흥미로웠다! – ToastMan

+0

경우 ($ serviceStatus -eq "거짓") <- 나에게 동일한 결과를 제공합니다 사용 서비스 이름 : 가짜 가 사용 : 트루을 이름 : TEST00000 사용 : 진정한 – ToastMan

+0

@toastman 나는 다시 방문 할 때 코드를 작성하고 필요한 경우 수정하고 완전성을 위해 내 대답을 편집하는 시스템으로 돌아갑니다. 유형 문제 일 수 있다고 생각하지만 확인합니다. 그 다음, 행복한 휴일 – trebleCode