以PowerShell形式查询SQL [英] Query SQL in PowerShell form
问题描述
我有以下代码,从Windows PowerShell ISE运行时完全正常,但是当它作为表单的一部分运行时,它不起作用。
I have the following code which when ran from Windows PowerShell ISE works perfectly fine, however when it's ran as part of a form it doesn't work.
$PCNum = "PCNUMBERHERE"
$SQLConnection = New-Object System.Data.SqlClient.SqlConnection
$SQLConnection.ConnectionString = "Server=SQLSERVER\Instance;Database=AMProd;Integrated Security=True"
$SQLCmd = New-Object System.Data.SqlClient.SqlCommand
$SQLCmd.CommandText = "Select lUserId FROM amPortfolio WHERE Code = '$PCNum'"
$Command = $SQLCmd.CommandText
$SQLCmd.Connection = $SQLConnection
$SQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SQLAdapter.SelectCommand = $SQLCmd
$DataSet = New-Object System.Data.DataSet
$SQLAdapter.Fill($DataSet)
$SQLConnection.Close()
$TableCount = $DataSet.Tables.Count
$SQLlUserId = $DataSet.Tables.lUserId
在上面的代码中,首先将变量$ PCNum设置为PC资产编号。然后,针对资产管理数据库运行SQL查询,以查找amPortfolio表上的资产编号。使用Windows PowerShell ISE运行时,我会返回一个
表,并返回lUserId对象,其中包含拥有该资产的用户的值。
In the code above, it starts by having the variable $PCNum set to a PC asset number. A SQL query is then ran against the asset management database looking for the asset number on the amPortfolio table. When ran with the Windows PowerShell ISE, I get a single table returned and the lUserId object is returned with the value of the user who owns the asset.
当相同的块时代码是以PowerShell形式运行的,我似乎还是返回了一个表,但是lUserId不存在。运行代码块时没有遇到任何错误。在代码是函数的一部分的形式中,使用表单加载
,如果这会产生影响。
When the same chunk of code is ran in a PowerShell form, I still appear to get a single table returned, however the lUserId doesn't exist. No errors encountered while running the chunk of code either. In the form the code is part of a function the loads with the form, if that makes a difference.
有没有人知道为什么我从相同的代码得到不同的结果?
Does anyone have any idea why I'm getting different results from the same code?
推荐答案
我们我需要查看失败的代码。 如果我不得不猜测,我会说你可能在某处有变量范围问题。
We'd need to see the code that's failing. If I had to guess, I'd say you probably have a variable scope issue somewhere.
这篇关于以PowerShell形式查询SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!