![](/img/trans.png)
[英]In C# running the PowerShell script first and then invoke Get-Process returns 0 result
[英]In C# running the PowerShell script first and then invoke() error
我想用 c# 制作打印機安裝程序 gui,但我給出了錯誤。 我的錯誤如下。 在此處輸入圖片說明
System.Management.Automation.CommandNotFoundException:“術語“添加”未被識別為 cmdlet、函數、腳本文件或可運行程序的名稱。 檢查名稱的拼寫,或者如果包含路徑,請驗證路徑是否正確,然后重試。
我的代碼在下面,我哪里做錯了? 我正在等待你的幫助。 我已經掙扎了 3 天,我查看了所有資源,但找不到解決方案。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace son1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ekle_Click(object sender, EventArgs e)
{
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
powershell.AddCommand("Add");
powershell.AddArgument("-");
powershell.AddArgument("PrinterPort");
powershell.AddArgument("-");
powershell.AddArgument("name");
powershell.AddArgument(printer_ip);
powershell.AddArgument("-");
powershell.AddArgument("PrinterHostAddress");
powershell.AddArgument(printer_ip);
powershell.Invoke();
}
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
powershell.AddCommand("Add");
powershell.AddArgument("-");
powershell.AddArgument("Printer");
powershell.AddArgument("-");
powershell.AddArgument("Name");
powershell.AddArgument(printer_name);
powershell.AddArgument("-");
powershell.AddArgument("PortName");
powershell.AddArgument(printer_ip);
powershell.AddArgument("-");
powershell.AddArgument("DriverName");
powershell.AddArgument("Canon Generic Plus PCL6");
powershell.Invoke();
}
System.Windows.MessageBox.Show("Success!");
}
}
}
該 API 比要求您手動輸入每個字符串標記要復雜一些。
AddCommand()
獲取整個命令名稱:
powershell.AddCommand('Add-Printer');
對於命名參數參數,使用AddParameter()
而不是AddArgument()
:
powershell.AddParameter("Name", ad);
powershell.AddParameter("PortName", ip)
// etc...
請注意,我們通常在 PowerShell 腳本中的參數名稱前面使用的-
實際上並不是名稱本身的一部分,因此不要包含它。
如果要將多個管道作為單獨的語句執行,請在對下一個管道中的第一個命令的AddCommand()
調用之間調用AddStatement()
:
using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
{
// call `Add-PrinterPort ...`
powershell.AddCommand("Add-PrinterPort");
powershell.AddParameter("Name", printer_ip);
powershell.AddParameter("PrinterHostAddress", printer_ip);
// terminate previous statement (equivalent to a newline or `;` in powershell)
powershell.AddStatement();
// then call `Add-Printer ...`
powershell.AddCommand("Add-Printer");
powershell.AddParameter("Name", printer_name);
powershell.AddParameter("PortName", printer_ip);
powershell.AddParameter("DriverName", "Canon Generic Plus PCL6");
// Invoke the whole thing at once
powershell.Invoke();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.