Powershell如何通过post方法存储和返回ID

时间:2018-02-19 22:22:28

标签: sql json api powershell post

好的,我写了以下代码发布到API。然后,API返回一个我需要存储回数据库的ID。我怎么会这样做我很困惑或者更好地将它存储在内存中?我觉得将它发送回sql会好得多。所以,一旦我运行脚本再次清楚,我会回复一个回复,说它添加了我想要的东西,它会给我一个ID,基本上标记添加的内容。我需要获取该ID并在将其添加到API

后将其同时发送回数据库
$DBServer = "xxxxx"
$DataBaseName = "xxxxxx"
$Connection = new-object system.data.sqlclient.sqlconnection #Set new object to connect to sql database
$Connection.ConnectionString ="server=$DBServer;database=$databasename;trusted_connection=True" # Connection string setting for local machine database with window authentication
Write-host "Connection Information:"  -foregroundcolor yellow -backgroundcolor black
$Connection  #List connection information to screen
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand #setting object to use sql commands

############ MAIN ####################################
$SqlQuery = @"
SELECT [DeviceId]
      ,[DeviceName]
  FROM [xxx].[dbo].[xxx] 
  order by 2

"@

$Connection.open()

Write-host "Connection to the $DatabaseName DB was successful." -foregroundcolor green -backgroundcolor black
$SqlCmd.CommandText = $SqlQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlCmd.Connection = $Connection
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$Connection.Close()

######  Will Creds be required??
#Web Client connection 
$WebClient = New-Object net.webclient
Add-Type -AssemblyName System.Web.Extensions

#Credentials
$userName ="xxxxxxx"
$password = "xxxxxxxx"
$pair = "$($userName):$($password)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}


#ConvertFromJson
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password)

foreach ($Row in $DataSet.Tables[0].Rows)
{
        #Note sure of the URL at this point..
        $URL = "https://xxxxxxxxx/xxxx/xx"
        $Endpoint = "/devices.json/$($Row[0])/xxxxxxxxx"
        $URLSvc = "$URL$Endpoint"

        #write-host $URLSvc + " - " + $($Row[1])
        ###########  TEST    ####################

        # Create JSON Hash
        $JsonTemplate = ConvertTo-Json @{  
                       "applicationName"= "xxx-$($Row[1])";
                       "applicationType"= "xxxxx";
                       "description1"= "xxxxx";
                       "description2"= "";
                       "passwordCompositionPolicyId"= "xxxxx"
}



        ## Write out for Display
        #ConvertFromJson!!!!!!!!!!!!!!!!!!!!
        Write-Host $JsonTemplate   -foregroundcolor Red -backgroundcolor White
        $xxx = Invoke-RestMethod -Method Post -Headers $Headers -Uri $URLSvc -Body $JsonTemplate -ContentType application/json
        Write-Host $xxx

}

0 个答案:

没有答案