0

我正在尝试使下面的 2 个功能正常工作。下面的事情,我觉得有点奇怪的是:为什么第一个Qf函数调用可以工作,而第二个为什么不行?

$global:query_output = @()
$global:query_output_filtered = @()

function Q {
    Param(
        [Parameter(Mandatory=$true)][string]$DBquery,
        $DBip = "IP" ,
        $DBusr = "username" ,
        $DBpas = "password" ,
        $DBname = "dbname"
    )
    Process {
        try {
            $SQLConnection = New-Object System.Data.SQLClient.SQLConnection
            $SQLConnection.ConnectionString ="server=$DBip;database=$DBname; User         ID = $DBusr; Password = $DBpas;"
            $SQLConnection.Open()
        } catch {
            [System.Windows.Forms.MessageBox]::Show("Failed to connect SQL     Server:")
        }

        $SQLCommand = New-Object System.Data.SqlClient.SqlCommand
        $SQLCommand.CommandText = "Use Inventory " + $DBquery
        $SQLCommand.Connection = $SQLConnection

        $SQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
        $SqlAdapter.SelectCommand = $SQLCommand
        $SQLDataset = New-Object System.Data.DataSet
        $SqlAdapter.fill($SQLDataset) | Out-Null

        $script:query_output = @()
        foreach ($data in $SQLDataset.Tables[0]) {
            $script:query_output += $data
        }
        $SQLConnection.Close()
        Write-Host ""
        Write-Host "================= query_output =======================" -ForegroundColor Green -BackgroundColor Red
        $script:query_output | Format-Table -AutoSize
        Write-Host "========================================" -ForegroundColor Green -BackgroundColor Red
    }
}

function Qf {
    Param(
        $objectsearch = "*02",
        $objectcolom = "company"
    )
    Process {
        $script:query_output_filtered = $script:query_output | Where-Object {
            $_.$objectcolom -like $objectsearch
        }
        Write-Host ""
        Write-Host "================= query_output_filtered=======================" -ForegroundColor Green -BackgroundColor Red
        $script:query_output_filtered | Format-Table -AutoSize
        Write-Host "========================================" -ForegroundColor Green -BackgroundColor Red
    }
}

Q("SELECT * FROM machine WHERE ID LIKE '%111'")

Qf("*DE")
Qf("*POS02","systemname")
4

1 回答 1

1

PowerShell 函数/cmdlet 的参数必须以空格分隔,而不是逗号分隔。后者仅用于将参数传递给对象方法。

语句Qf("*DE")首先将分组表达式计算("*DE")为字符串"*DE",然后将该字符串作为第一个参数传递给函数Qf

语句Qf("*POS02","systemname")再次首先将分组表达式计算("*POS02","systemname")为字符串数组"*POS02","systemname",然后将该数组作为第一个参数传递给函数Qf。因此,参数$objectsearch具有值"*POS02","systemname"并且参数$objectcolom具有(默认)值"company"

改变这个:

Q("SELECT * FROM machine WHERE ID LIKE '%111'")

Qf("*DE")
Qf("*POS02","systemname")

进入这个:

Q "SELECT * FROM machine WHERE ID LIKE '%111'"

Qf "*DE"
Qf "*POS02" "systemname"

问题就会消失。

于 2018-09-18T09:11:23.850 回答