【发布时间】:2018-08-17 10:21:43
【问题描述】:
在家居灯光控制应用上花费大量时间。当我在 powershell 中使用以下代码时,cmd.exe 命令会通过远程机器并执行它来关闭灯。这部分工作正常。
alllightsoff.ps1
$options=New-PSSessionOption -SkipCACheck -SkipCNCheck
Enter-PSSession -ComputerName HTPC -UseSSL -SessionOption $options
& "C:\Program Files (x86)\Home Control\HarmonyHubControl\Release\x86\HarmonyHubControl.exe" 10.90.1.8 issue_device_command 42458302 Light7
& "C:\Program Files (x86)\Home Control\HarmonyHubControl\Release\x86\HarmonyHubControl.exe" 10.90.1.8 issue_device_command 42458303 LightOff
Exit-PSSession
现在我有一个 C# 脚本,并且我之前在一台带有 ssh 的 linux 机器上运行过它。当我按下一个按钮时,这段代码被执行了。
using (var ssh = new SshClient(CreateConnectionInfo()))
{
ssh.Connect();
ssh.RunCommand("/home/iiidefconiii/HarmonyHubControl/HarmonyHubControl 10.90.1.8 issue_device_command 42458302 Light7");
ssh.RunCommand("/home/iiidefconiii/HarmonyHubControl/HarmonyHubControl 10.90.1.8 issue_device_command 42458303 LightOff");
ssh.Disconnect();
}
我移到了 Windows 计算机,而不是 ssh、linux。所以我需要从那个按钮中抛出那个powershell代码。
using System.Management.Automation;
应用了参考,所以现在应该没问题。
我发现下面的代码可以完成这项工作,但我不想为每个命令创建 *.ps1 文件,而是我希望 powershell 命令直接应用程序本身
private void Sleep_Click(object sender, EventArgs e)
{
PowerShell ps = PowerShell.Create();
ps.AddScript(@"D:\Desktop\alllightsoff.ps1");
ps.Invoke();
}
如果我插入
private void Sleep_Click(object sender, EventArgs e)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
param([string]$command)
$options = New - PSSessionOption - SkipCACheck - SkipCNCheck
Enter - PSSession - ComputerName HTPC - UseSSL - SessionOption $options
cmd.exe / c "C:\Program Files (x86)\Home Control\HarmonyHubControl\Release\x86\HarmonyHubControl.exe" 10.90.1.8 issue_device_command 42458302 $command
Exit - PSSession
}
}
我也遇到了错误
【问题讨论】:
-
您是说要将您的 powershell 代码转换为 C# 代码,并将其放入
Click事件中吗? -
不,我只是想通过 powershell 会话管道代码。我单击了一个 powershell 命令应该运行的按钮。
标签: c# visual-studio powershell button