1

If the script finished I want a messagebox popup, but I don't know the if statement.

    using (PowerShell PowerShellInstance = PowerShell.Create())
    {
        PowerShellInstance.AddScript("cmdkey /list | ForEach-Object{if($_ -like \"*Target:*\"){cmdkey /del:($_ -replace \" \",\"\" -replace \"Target:\",\"\")}}");
        PowerShellInstance.Invoke();
        if ()
        {
            MessageBox.Show("the process was successfully completed");
        }
1
  • If you look at the documentation for Invoke, you'll see that it will "Invoke the Command synchronously and return the output PSObject collection". So there's nothing to check (except perhaps catch one or more of the 12 documented exceptions that might be thrown on failure). Commented Apr 6, 2020 at 11:40

2 Answers 2

1

As pointed out by ADyson, calling PowerShellInstance.Invoke(); is synchronous.

However, if you want to know if the command was successful or not, you can use HadErrors and read the error stream when needed:

if (!PowerShellInstance.HadErrors)
{
    MessageBox.Show("the process was successfully completed");
}
else
{
    string[] errors = PowerShellInstance.Streams.Error.Select(x => x.ToString()).ToArray();
    // Show error to user or log them...
}
Sign up to request clarification or add additional context in comments.

Comments

0

PowerShellInstance.Invoke(); is synchronous, so your script will already wait for Powershell to complete. You don't need an if statement.

If you really want asynchronous execution you can invoke the script another way using BeginInvoke(). See https://learn.microsoft.com/en-gb/archive/blogs/kebab/executing-powershell-scripts-from-c - it explains both the synchronous and asynchronous approaches.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.