【问题标题】:Write an If statement to Insert certain data into SQL编写 If 语句将某些数据插入 SQL
【发布时间】:2017-09-11 18:22:40
【问题描述】:

好的,这段代码完美运行,它从 API 中提取我需要的所有数据。但我需要它来插入特定的数据。我如何制作一个 IF 语句,该语句只插入在标签中配置的命名数据并将其插入 SQL。我对powershell很陌生,所以我不知道如何使这项工作。如果有人能指引我正确的方向。

For 循环为对象提供变量

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

插入MYSQL数据库

        $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() 

【问题讨论】:

    标签: sql database powershell if-statement inject


    【解决方案1】:

    您可以使用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
    }
    

    【讨论】:

    • where-obj 是在我的每个语句之后还是在我的每个语句中?
    • 使用Where-Object,您可以在循环之前过滤对象。仅在剩余的元素上运行。使用if,您可以将其放入循环中并评估您循环的每个元素的条件。
    猜你喜欢
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    相关资源
    最近更新 更多