我有一个示例解决方案(VS 2017,C#),其中包含2个项目:
Aaa.ps1执行简单的Select查询,以检索一个值并将其传递到控制台应用程序cs并在控制台上显示。
class Program
{
static void Main(string[] args)
{
// get a ps file script path.
string pathToScriptsFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts");
string filter = "*.ps1";
string[] files = Directory.GetFiles(pathToScriptsFile, filter);
string filePath = files[0];
// read text from a ps file script.
string scriptContent = string.Empty;
using (StreamReader sr = new StreamReader(filePath))
{
scriptContent = sr.ReadToEnd();
sr.Close();
}
// get dbValue from powershell script
using (PowerShell powerShellInstance = PowerShell.Create())
{
powerShellInstance.AddScript(scriptContent);
try
{
Collection<PSObject> PSOutput = powerShellInstance.Invoke();
foreach (PSObject outputItem in PSOutput)
{
if (outputItem != null)
{
var outputValue = outputItem.BaseObject;
if (outputValue.GetType() == typeof(System.Data.DataRow))
{
var dbValue = (outputValue as System.Data.DataRow).ItemArray.FirstOrDefault();
Console.WriteLine($"Db value is:\n{dbValue}\n");
}
Console.WriteLine($"Value form powershell script is:\n{outputItem.ToString()}\n");
}
}
if (!PSOutput.Any())
{
Console.WriteLine($"No Value form powershell script is:\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"\n\n{ex}\n{ex.Message}\n{ex.InnerException}\n\n");
}
}
Console.ReadKey();
}
}
Aaa.ps1
#
# Aaa.ps1
#
# Load Npgsql dll
Add-Type -Path ".\Npgsql.dll"
# get DB connection
function getDBConnection ($MyDBServer, $MyDBPort, $MyDBName, $MyUserId, $MyPassword) {
$DBConnectionString = "server=$MyDBServer;port=$MyDBPort;user id=$MyUserId;password=$MyPassword;database=$MyDBName;pooling=false"
$DBConn = New-Object Npgsql.NpgsqlConnection;
$DBConn.ConnectionString = $DBConnectionString
$DBConn.Open()
return $DBConn
}
# close DB connection
function closeDBConnection ($DBConn)
{
$DBConn.Close
}
# DB connection string details
$MyDBServer = "xxxxxxxxxxxxxxx";
$MyDBPort = yyyy;
$MyDBName = "xxxxxxxx";
$MyUserId = "xxxxxx";
$MyPassword = "";
# execute sql query
$MyDBConnection = getDBConnection $MyDBServer $MyDBPort $MyDBName $MyUserId $MyPassword
$query = "SELECT xxxxx FROM xxxxx ..."
$DBCmd = $MyDBConnection.CreateCommand()
$DBCmd.CommandText = $query
$adapter = New-Object -TypeName Npgsql.NpgsqlDataAdapter $DBCmd
$dataset = New-Object -TypeName System.Data.DataSet
$adapter.Fill($dataset)
$dataset.Tables[0]
closeDBConnection($MyDBConnection)
及以上可以正常工作。我总是有3个项目的PSOutput集合和一个我需要从sql返回的数据。
但是,当我将相同的方法应用于更大的解决方案时,它将不起作用。我做了什么:
结果是我有两个不同的错误/行为:
有人可以告诉我我在做什么错吗?