为了好玩并教育自己,我正在为Powershell编写自己的SQL Server查询包装器。请参阅下面我目前所处的位置。
我现在的主要问题是,如果您使用错误的username
,password
或servername
调用该函数,则PS需要大约一分钟才能返回大量错误。我想返回更多有用的错误消息,即
在当前函数的位置和方法中,我可以实现用于捕获和解析PS错误到有用消息的部分吗?
Function Query {
<#
.SYNOPSIS
Query a SQL Server instance
.EXAMPLE
Query -query "SELECT column FROM table"
This command returns a dataset from the SQL server.
.DESCRIPTION
This function returns different output based on the query type. DROP,
ALTER and DELETE statements are not allowed for security reasons.
.LINK
http://spark/publish-later
#>
param (
[string]$query,
[string]$server = "SQLEXPRESS",
[string]$dbase = "TEST",
[string]$user,
[string]$pass
)
if ($user) {
$connstr = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout=15" -f $server, $dbase, $user, $pass
}
else { # Windows Authentication is implied
$connstr = "Server={0};Database={1};Integrated Security=True;Connect Timeout=15" -f $server, $dbase
}
$conn = New-Object System.Data.SqlClient.SqlConnection($connstr)
try {
$conn.Open()
switch ($query.Split()[0]) {
"SELECT" {
$cmd = New-Object System.Data.SqlClient.SqlCommand($query,$conn)
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataset) | Out-Null
return $dataset.Tables[0]
}
"UPDATE" {
$cmd = New-Object System.Data.SqlClient.SqlCommand($query,$conn)
return $cmd.ExecuteNonQuery()
}
"INSERT" {
$cmd = New-Object System.Data.SqlClient.SqlCommand($query,$conn)
return $cmd.ExecuteNonQuery()
}
}
$conn.Close()
}
catch {
$ex = $_.Exception
return "$ex.Message"
continue
}
}