Test-Path against JSON values

Welcome Forums General PowerShell Q&A Test-Path against JSON values

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
9 months ago.

  • Author
    Posts
  • #93745
    GS

    Participant
    Points: 1
    Rank: Member

    Hello,

    I have JSON below and I need to find out if all path in values exists on file system. What is most effective way to iterate through all the values? I need to return $false if any of the path does not exist.

    $jsonArray = '[{"privateKeyLocation" : "C:\\ProgramData\\docker\\certs.d\\key.pem"},
    {"publicKeyLocation" : "C:\\ProgramData\\docker\\certs.d\\cert.pem"},
    {"publicKeyCALocation" : "C:\\ProgramData\\docker\\certs.d\\ca.pem"}]'
    $json = convertfrom-json $jsonArray
    Test-path $json 
  • #93753

    Participant
    Points: 226
    Helping Hand
    Rank: Participant

    Of course there are several ways to do this. The below is just what I came up with.

        $jsonArray = '[{"privateKeyLocation" : "C:\\ProgramData\\docker\\certs.d\\key.pem"},
        {"publicKeyLocation" : "C:\\ProgramData\\docker\\certs.d\\cert.pem"},
        {"publicKeyCALocation" : "C:\\ProgramData\\docker\\certs.d\\ca.pem"}]'
    
        ([regex]::Matches($jsonArray,'(?< =\").:\\[^\"]+(?=\")').Value) -replace '\\\\','\' `
        | ForEach { 
                    If (Test-Path -Path $_)
                    {"path $_ found"}
                    Else {Write-Warning "Path $_ not found"}
                  }
    
        WARNING: Path C:\ProgramData\docker\certs.d\key.pem not found
        WARNING: Path C:\ProgramData\docker\certs.d\cert.pem not found
        WARNING: Path C:\ProgramData\docker\certs.d\ca.pem not found
    

The topic ‘Test-Path against JSON values’ is closed to new replies.