Powershell结果集未在C#中被提取

Rya*_*oly 6 c# sql-server powershell winforms

单击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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*oly 0

我通过使用 Win32_service 而不是 SQLPS 设法解决了这个问题。

Param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][string] $server)

$localInstances = @()
[array]$captions = GWMI Win32_Service -ComputerName $server | ?{$_.Name -match 'mssql *' -and $_.PathName -match 'sqlservr.exe'} | %{$_.Caption}

ForEach($caption in $captions)
{
   if ($caption -eq 'MSSQLSERVER') 
   {
       $localInstances += 'MSSQLSERVER'
   }
   else 
   {
       $temp = $caption | %{$_.split(' ')[-1]} | %{$_.trimStart('(')} | %{$_.trimEnd(')')}
       $localInstances += ""$server\$temp""
   }
}
$localInstances;
Run Code Online (Sandbox Code Playgroud)