好的,这段代码非常完美,它可以从API中提取所需的数据。但我需要它只是插入特定的数据。我如何制作一个IF语句,只插入在Tags中命名的数据并将其插入SQL中。我对powershell很新,所以我不知道如何使这项工作。如果有人可以指导我朝正确的方向发展。
foreach($obj in $Json.devices)
{
$DeviceIdentifier = $obj.deviceId
$DeviceNombre = $obj.deviceName
$DomainNombre = $obj.domainName
$Tags =$obj.tags
Write-Host ($obj.deviceId) -BackgroundColor White -ForegroundColor darkblue
Write-Host ($obj.devicename) -BackgroundColor White -ForegroundColor red
Write-Host ($obj.domainname) -BackgroundColor White -ForegroundColor red
Write-Host ($obj.tags) -BackgroundColor White -ForegroundColor black
$cmd = $connection.CreateCommand()
$insert_stmt = "INSERT INTO [dbo].[Tags]([DeviceID],[DeviceName],[DomainName],[Tags])
VALUES ('$DeviceIdentifier','$DeviceNombre', '$DomainNombre','$tags')" -replace "\s+"," "
$cmd.CommandText = $insert_stmt
write-host $insert_stmt -BackgroundColor White -ForegroundColor DarkBlue
$cmd.ExecuteNonQuery()
}
$Connection.Close()
答案 0 :(得分:0)
您可以使用Where-Object
cmdlet将$Json.devices
过滤为仅Tags
= provisioned
的对象。
$objs = $Json.devices | Where-Object {$_.tags -eq "provisioned"}
foreach($obj in $objs)
否则您可以使用if
声明
if ($Tags -eq "provisioned) {
#Do logic here
}