简体   繁体   中英

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)}");

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.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM