0

I have looked at How do I automatically answer "yes" to a prompt in Powershell? but those solutions did not work.

I have tried adding -Force as a parameter but I get the error:

Get-NetAdapter : A parameter cannot be found that matches parameter name 'Force'.

I am trying to run the following powershell script in c# to disable WiFi:

using (PowerShell PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript($"get-netadapter wi-fi | disable-netadapter");
    PowerShellInstance.Invoke();
}

But when I do I get the error:

A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Are you sure you want to perform this action? Disable-NetAdapter 'Wi-Fi'"'

How can I tell the script that I do want that to happen, via c#?

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90

1 Answers1

3

Simply set the confirmation to false (you don't want it to confirm).

using (PowerShell PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript($"get-netadapter wi-fi | disable-netadapter -Confirm:$false");
    PowerShellInstance.Invoke();
}

The other method, when using C#, is to set the confirmation preference to None in the Initial Session state:

var sessionState = InitialSessionState.CreateDefault();
sessionState.Variables.Add(new SessionStateVariableEntry("ConfirmPreference", ConfirmImpact.None, ""));

using (PowerShell PowerShellInstance = PowerShell.Create(sessionState))
{
    PowerShellInstance.AddScript($"get-netadapter wi-fi | disable-netadapter");
    PowerShellInstance.Invoke();
}
HAL9256
  • 12,384
  • 1
  • 34
  • 46