單擊button1時,將執行下面的代碼,該代碼將運行PowerShell腳本以獲取當前的SQL Server實例。但是,運行此操作時,結果集(結果變量)的PowerShell輸出中的計數爲0。當我在本機PowerShell中運行相同的代碼時,它顯示3行包含實例名稱。Powershell結果集未被C#拾取
任何人都可以建議,如果我失去了一些東西?
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窗體應用程序或其他東西?如果還有別的,什麼? – TravisEz13
是的。我已經添加了WinForms標籤,謝謝。 –
檢查PowerShell對象上的['HadErrors'](https://msdn.microsoft.com/en-us/library/system.management.automation.powershell.haderrors(v = vs.85).aspx)是否合適。如果它是真的,你需要閱讀['Streams'](https://msdn.microsoft.com/en-us/library/system.management.automation.powershell.streams(v = vs.85).aspx) ['.Error'](https://msdn.microsoft.com/en-us/library/system.management.automation.psdatastreams.error(v = vs.85).aspx)屬性並檢查錯誤。 CmdLet可能寫入了一個非終止錯誤。 – TravisEz13