I am trying to run a powershell script in c# that contains among other the command: Get-Credential
I can run the file with the Process Command:
public static void RunFile(string ps1File)
{
var startInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{ps1File}\"",
UseShellExecute = false,
CreateNoWindow = true
};
try
{
Process P = Process.Start(startInfo);
P.WaitForExit();
var result = P.ExitCode;
System.Diagnostics.Debug.WriteLine("Error: " + result);
}
catch (Exception e)
{
throw;
}
}
but with that I dont get the PS return value. So I am trying the System.Management.Automation but now I have the issue that the PS windows does not come up and I get straight my error code:
public async static void RunFileTest(string ps1File) {
PowerShell ps = PowerShell.Create();
//PowerShell ps = PowerShell.Create();
if (File.Exists(ps1File)) {
ScriptBlock sb = ScriptBlock.Create(System.IO.File.ReadAllText(ps1File));
System.Diagnostics.Debug.WriteLine("SB: " + sb.ToString());
// execute the script and await the result.
//var results = await ps.InvokeAsync().ConfigureAwait(false);
//var results = ps.Invoke();
PSCommand new1 = new PSCommand();
ps.Commands = new1;
var results = ps.Invoke();
foreach (var result in results)
{
Console.WriteLine(result); //<-- result NOT results
System.Diagnostics.Debug.WriteLine("Error: " + result.ToString());
}
System.Diagnostics.Debug.WriteLine("Errors: " + results);
} else
{
System.Diagnostics.Debug.WriteLine("Error: " + "No File");
}
}
Is there a way to run a PS file and get the windows like from get-credential but without the PowerShell Window?
Thanks Stephan
Edit: It seems, that I have to use exit instead of return to set a correct exit code when I use the first function RunFile, but nevertheless, the inbuild powershell function would be prefered