Here is an example that may help with whatever you are attempting. The code assumes PowerShell is in the path, gets the IP address without showing a window to a text file and reads back the results once the PowerShell code finishes executing using a language extension.
This method will keep a windows form responsive and if this is not needed process.WaitForExit can be used.
public static class Extensions
{
public static Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default)
{
if (process.HasExited)
{
return Task.CompletedTask;
}
var tcs = new TaskCompletionSource<object>();
process.EnableRaisingEvents = true;
process.Exited += (sender, args) => tcs.TrySetResult(null);
if (cancellationToken != default)
{
cancellationToken.Register(() => tcs.SetCanceled());
}
return process.HasExited ? Task.CompletedTask : tcs.Task;
}
}
Form code
private async void button1_Click(object sender, EventArgs e)
{
PowerShellScriptExecute();
}
private string _fileName = "ipPower.txt";
public async void PowerShellScriptExecute()
{
var start = new ProcessStartInfo
{
FileName = "powershell.exe",
UseShellExecute = false,
RedirectStandardOutput = true,
Arguments = "Invoke-RestMethod ipinfo.io/ip",
CreateNoWindow = true
};
using var process = Process.Start(start);
using var reader = process.StandardOutput;
process.EnableRaisingEvents = true;
var ipAddressResult = reader.ReadToEnd();
await File.WriteAllTextAsync(_fileName, ipAddressResult);
await process.WaitForExitAsync();
Debug.WriteLine(await File.ReadAllTextAsync(_fileName));
}