我正在尝试使以下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")
答案 0 :(得分: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"
问题将消失。