2 Answers
Best Answer
把下面代码C#转换成PowerShell
http://stackoverflow.com/questions/15292175/c-sharp-using-sendkey-function-to-send-a-key-to-another-application
荔非苔2016年9月27日更新
我还是希望每一个编写PowerShell脚本的人提高自己的动手能力,论坛和社区的目的更多是提供思路,而不是外包接活。
下面演示如何将上述连接中的C#转换成Powershell脚本:
Add-Type @"
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public class User32Helper
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
}
"@ -ReferencedAssemblies @("System.Windows.Forms")
Add-Type -AssemblyName System.Windows.Forms
#1. 手动打开cmd(代表你的后台程序)
#2. 通过Get-process过滤出目标控制台程序
$Console = Get-Process "cmd" | select -First 1
#3. 获取窗口句柄,并激活焦点
$intPtr = $Console.MainWindowHandle
[User32Helper]::SetForegroundWindow($intPtr)
#4. 输入你要执行的命令
[System.Windows.Forms.SendKeys]::SendWait("ping www.pstips.net")
#5. 按回车执行命令
[System.Windows.Forms.SendKeys]::SendWait("{Enter}")
脚本允许后的效果如下图:
非常感谢!我是从linux转到windows平台上来的,所以C#真的不熟

