简体   繁体   English

如何从C#运行PowerShell代码?

[英]How to run PowerShell code from C#?

I have the following PowerShell script, that I want to run from within my C# application. 我有以下PowerShell脚本,希望从我的C#应用​​程序中运行。

$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. 到目前为止,这是我使用“ using System.Management.Automation;”进行的尝试,但是脚本无法正常工作。 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(); 看来您缺少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.) 您可以在此博客文章中找到有关执行PowerShell代码的不同方法的更多信息: https : //blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ ( “脚本/命令执行:”及以下部分。)

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; 对于那些不知道的人,此代码将禁用LMhosts查找并通过TCP / IP禁用NetBios。 remember to run it with administrative rights. 记住要以管理权限运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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