Tony Batista
Tony Batista

Reputation: 177

How to run PowerShell code from C#?

I have the following PowerShell script, that I want to run from within my C# application.

$adapters=(gwmi win32_networkadapterconfiguration ) 
Foreach ($adapter in $adapters){
Write-Host $adapter
  $adapter.settcpipnetbios(2)
}
$nics=([wmiclass]'Win32_NetworkAdapterConfiguration')
Foreach($nic in $nics){
 Write-Host $adapter
$nic.enablewins($false,$false)
}

This is what I tried so far, using the "using System.Management.Automation;," but the script is not working. Can someone point me in the right direction?

PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-Process");
ps.AddArgument("$adapters=(gwmi 
win32_networkadapterconfiguration )");
ps.AddArgument("Foreach($adapter in $adapters){");
ps.AddArgument(" Write - Host $adapter");
ps.AddArgument("$adapter $adapter.settcpipnetbios(2)}");
//WINS LMHOSTS lookup
ps.AddArgument("$nics = ([wmiclass]'Win32_NetworkAdapterConfiguration')");
ps.AddArgument("Foreach($nic in $nics){");
ps.AddArgument(" Write - Host $adapter");
ps.AddArgument("$nic.enablewins($false,$false)}");

Upvotes: 0

Views: 374

Answers (2)

Tony Batista
Tony Batista

Reputation: 177

thanks for the help I found a solution. To make the script work, I had to structure the code as follow.

 //Disable NetBIOS over TCP/IP - 2=disable, 1=enable, 0=DHCP default
 //And WINS LMHOSTS lookup
 string script = @"
 $adapters=(gwmi win32_networkadapterconfiguration )
 Foreach($adapter in $adapters)
 {
    Write-Host $adapter
    $adapter.settcpipnetbios(2)
  }
  $nics=([wmiclass]'Win32_NetworkAdapterConfiguration')
  Foreach($nic in $nics){
  Write-Host $adapter
  $nic.enablewins($false,$false)
  }
  ";

  PowerShell powerShell = PowerShell.Create();
  powerShell.AddScript(script);
  powerShell.Invoke();

For those who don't know, this code will disable LMhosts Lookup and Disable NetBios over TCP/IP; remember to run it with administrative rights.

Upvotes: 0

A Person
A Person

Reputation: 1112

It looks like you are missing a ps.Invoke(); at the end of your code. Or did you just leave that out of your listing?

You can find more information about the different ways to execute the PowerShell code in this blog post: https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ (Section "Script/Command Execution:" and below.)

Upvotes: 1

Related Questions