我试着让下面的两个功能发挥作用。下面,我发现有一点奇怪的是:为什么第一个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")发布于 2018-09-18 09:11:23
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"问题就会消失。
https://stackoverflow.com/questions/52381709
复制相似问题