【问题标题】:Cant get powershell script to work on button无法让 powershell 脚本在按钮上工作
【发布时间】: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


【解决方案1】:

参数化你的脚本:

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

将命令的参数传递给脚本。

【讨论】:

  • 谢谢,但我不是很明白,对不起,我是一个基本用户
  • 这是一个新脚本...执行一个名为 command 的单个参数化命令...然后您将更新您的 c# 代码以传递您要执行的命令
  • 你能给我举个例子吗?在完整的代码中?我可能会更好地理解它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 1970-01-01
相关资源
最近更新 更多