【发布时间】:2017-05-14 07:41:05
【问题描述】:
单击 button1 时,将执行以下代码,该代码将运行 PowerShell 脚本以获取当前的 SQL Server 实例。但是,当它运行时,结果集(结果变量)从 PowerShell 输出中计数为 0 行。当我在本机 PowerShell 中运行相同的代码时,它会显示 3 行的实例名称。
如果我遗漏了什么,谁能告诉我?
private void button1_Click(object sender, EventArgs e)
{
//If the logPath exists, delete the file
string logPath = "Output.Log";
if (File.Exists(logPath))
{
File.Delete(logPath);
}
string[] Servers = richTextBox1.Text.Split('\n');
//Pass each server name from the listview to the 'Server' variable
foreach (string Server in Servers)
{
//PowerShell Script
string PSScript = @"
param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][string] $server)
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force;
Import-Module SQLServer;
Try
{
Set-Location SQLServer:\\SQL\\$server -ErrorAction Stop;
Get-ChildItem | Select-Object -ExpandProperty Name;
}
Catch
{
echo 'No SQL Server Instances';
}
";
//Create PowerShell Instance
PowerShell psInstance = PowerShell.Create();
//Add PowerShell Script
psInstance.AddScript(PSScript);
//Pass the Server variable in to the $server parameter within the PS script
psInstance.AddParameter("server", Server);
//Execute Script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = psInstance.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((Object)ex.Message));
}
//Loop through each of the results in the PowerShell window
foreach (PSObject result in results)
{
File.AppendAllText(logPath, result + Environment.NewLine);
// listBox1.Items.Add(result);
}
psInstance.Dispose();
}
}
【问题讨论】:
-
这是 Windows 窗体应用程序还是其他什么?如果有别的,是什么?
-
是的。我已经添加了 WinForms 标签,谢谢。
-
HadErrors 属性在调用 powershell 脚本时返回 false @TravisEz13
-
代码看起来基本正确。我更新它以根据我使用
$server输入的路径执行Get-ChildItem,代码将输出写入output.log。你从哪里得到SQLServer模块?如果 SQL 附带 SQL 是什么版本的 SQL?是否需要安装选项才能获得它?你得到的是No SQL Server Instances还是零行?
标签: c# sql-server winforms powershell