Quantcast
Channel: Backup – Windows and Windows Server forum
Viewing all articles
Browse latest Browse all 3323

How can we pass a powershell array of objects to console application (c sharp)

$
0
0

Hi there,

I need to execute a powershell scripy from console application (c sharp). One of the objects ($SqlInstances) in Powershell script sends a string array.

The same object ($SqlInstances) when fetched in console application shows the value as null.

Please find the attached code block that I have written. It works fine for all variables except  an array/list objects.

Please suggest.

Thanks.

PowerShell code:
$sqlInstances = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
write-output "Sql Server is installed and the sql instances are: " $sqlInstances

C sharp code-
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
Runspace.Open();

RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

PowerShell objPowershell = PowerShell.Create();
objPowershell.Runspace = runspace;

var directory = Environment.CurrentDirectory;
string filePath = System.IO.Path.Combine(directory, "Install-DIYMPS.ps1");
string scriptContents = File.ReadAllText(filePath);
objPowershell.AddScript(scriptContents);  
Collection<PSObject> psObjects; 
psObjects = objPowershell.Invoke();
objPowershell.Dispose();

StringBuilder stringBuilder = new StringBuilder();

foreach (PSObject obj in psObjects)
               {
                    if (obj != null)
                    {
                        stringBuilder.AppendLine(obj.ToString());
                        stringBuilder.AppendLine();
                    }
                }

                Console.Write(stringBuilder.ToString()); 




Viewing all articles
Browse latest Browse all 3323

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>