2016-10-20 1 views
0

Ich muss das folgende PowerShell-Skript in ein Bash-Skript konvertieren. Könnte mir jemand helfen? Ich bin wirklich neu in Bash und weiß nicht, wie man die Ausgabe von einem curl-Befehl manipuliert und dann in Json konvertiert.PowerShell in Bash konvertieren

+2

SO ist nicht eine freie Übersetzung Service. Was hast du bisher versucht? Was funktioniert nicht wie erwartet? –

Antwort

3

Powershell-Rückgabeobjektantwort von Invoke-RestMethod, aber curl return json string format. Sie müssen die Antwort von curl analysieren, um die Werte von Roles und EnvironmentIds mithilfe des JSON-Parser-Tools wie jq zu extrahieren.

sicher sein, dass Sie jq installiert

Das folgende Skript ist die Umwandlung des Skripts Powershell:

headers='{"X-Octopus-ApiKey"="<api_key>"}' 
    #$machine = Invoke-RestMethod "http://my.url/api/machines/discover?host=<ip_address>&type=ssh" -Headers $headers -Method Get 

    response=$(curl -s -X GET -H $headers "http://my.url/api/machines/discover?host=<ip_address>&type=ssh")   
    echo $response 
    Name="Myhostname" 
    Roles=$(echo $response | jq -r ".Roles") 
    echo $Roles 
    Roles+="Myrole2" 
    EnvironmentIds=$(echo $response | jq -r ".EnvironmentIds") 
    echo $EnvironmentIds 
    EnvironmentIds+="Myenvironment2" 
    echo $EnvironmentIds 
    AccountId="Myaccount_id" 
    #compose json string to be passed as a body for the next curl call 
    machine=$(printf ' 
    {"Name":"%s", 
    "Roles":"%s" , 
    "EnvironmentIds":"%s" , 
    "Endpoint" : { 
        "AccountId" : "%s"  
       } 
    }' "$Name" "$Roles" "$EnvironmentIds" "$AccountId") 
    echo $machine 

    #Invoke-RestMethod "http://my.url/api/machines" -Headers $headers -Method Post -Body ($machine | ConvertTo-Json -Depth 10) 
    response=$(curl -s -X POST -H $headers -d $machine "http://my.url/api/machines") 
    echo $response