I am trying to create an Excel AddIn, in which i need to run a powershell script inside my c# code.
The following ps script run well when launched in a console but i cannot get the output when launched in the code.
$user = 'user@domain';
$password = 'password';
$s_password = ConvertTo-SecureString $password -AsPlainText -Force;
$command = 'openfiles /query /s server /fo csv';
$p = New-Object System.Diagnostics.Process;
$p.StartInfo.FileName = 'powershell';
$p.StartInfo.UserName = $user;
$p.StartInfo.Password = $s_password;
$p.StartInfo.RedirectStandardError = $true;
$p.StartInfo.RedirectStandardOutput = $true;
$p.StartInfo.UseShellExecute = $false;
$p.StartInfo.Arguments = $command;
try{
$p.Start();
$stdout = $p.StandardOutput.ReadToEnd();
$p.WaitForExit();
}
catch {}
$stdout
Here is my c# code so far :
try
{
PowerShell ps = PowerShell.Create();
ps.AddScript(@"script here");
var results = ps.Invoke();
MessageBox.Show(results.Count.ToString());
if (results.Count > 0)
{
foreach (var psObject in results)
{
if(psObject != null) MessageBox.Show(psObject.BaseObject.ToString());
}
}
if (ps.Streams.Error.Count > 0)
{
Collection<ErrorRecord> errors = ps.Streams.Error.ReadAll();
if (errors != null || errors.Count > 0)
{
foreach (ErrorRecord er in errors)
{
MessageBox.Show(er.Exception.ToString(), "Dévérouillage Fichier", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Dévérouillage Fichier", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
When i run this, it shows that there is 0 results.