PSobject 作为变量

PSobject as variable

我正在尝试使下面的 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")

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

语句 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"

问题就会消失。