亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 C# 中使用“New-Object”cmdlet

在 C# 中使用“New-Object”cmdlet

C#
桃花長相依 2023-09-16 16:10:19
我正在嘗試在我一直在開發的 C# 程序中運行一些 Powershell cmdlet。我一直嘗試運行的 cmdlet 如下:$cred = New-Object System.Management.Automation.PSCredential (user, (ConvertTo-SecureString pass –ASPlainText –Force)); 我在 C# 程序中所做的如下:string user = textBox1.Text;            string pass = textBox2.Text;            PowerShell ps = PowerShell.Create();            ps.AddCommand("New-Object");            ps.AddArgument("System.Management.Automation.PSCredential ("+user+", (ConvertTo-SecureString "+pass+" –ASPlainText –Force))");            var cred = ps.Invoke();但是當我這樣做時,我收到以下錯誤提示:A constructor was not found. Cannot find an appropriate constructor for type System.Management.Automation.PSCredential (user, (ConvertTo-SecureString pass –ASPlainText –Force)).所以我的問題是,如何從 C# 程序運行此 Powershell cmdlet,并將結果存儲在 C# 程序內的變量中?
查看完整描述

2 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

這可以在不調用 powershell 的情況下完成。這是否有用取決于您要做什么。


var user = "username";

var pass = new System.Security.SecureString();

foreach (char c in "password")

{

    pass.AppendChar(c);

}

var cred = new System.Management.Automation.PSCredential(user, pass);


查看完整回答
反對 回復 2023-09-16
?
慕少森

TA貢獻2019條經驗 獲得超9個贊

至于你嘗試過的

您沒有將 PowerShell 命令正確轉換為 PowerShell SDK 調用。具體來說,您添加參數的方式不正確:

ps.AddArgument("System.Management.Automation.PSCredential ("+user+", (ConvertTo-SecureString "+pass+" –ASPlainText –Force))");

  • 您必須通過逐一添加參數.AddArgument(<val>),或者最好通過) 作為命名參數.AddParameter(<name>, <val>)。

  • 您不能使用嵌入式 PowerShell 命令作為參數

如果我們將獲取實例的問題SecureString放在一邊并僅使用虛擬實例,則您的語句將如下所示:

ps.AddCommand("New-Object")
??.AddParameter("TypeName",?"System.Management.Automation.PSCredential")
??.AddParameter("ArgumentList",?new?object[]?{?user,?new?System.Security.SecureString()?});

請注意參數名稱的使用以及參數-ArgumentList必須如何作為數組傳遞。


如果您確實需要通過 SDK執行PowerShell 代碼,請改用該.AddScript()方法,但請注意,您只能傳遞包含要執行的代碼的單個字符串(請注意使用插值 C# 字符串$"..."來嵌入 C# 變量值):

ps.AddScript(
??$"New-Object?PSCredential?\"{user}\",?(ConvertTo-SecureString?\"{pass}\"?–AsPlainText?–Force)"
??);

警告:與使用 - 添加的命令不同.AddCommand().AddScript()使用 - 添加的命令在執行時總是默默失敗.Invoke(),不會發生異常;你必須檢查ps.HadErrorsps.Streams.Error檢查錯誤。相比之下,.AddCommand()如果目標命令報告(語句)終止錯誤,則會拋出異常(盡管這種情況很少見;一個示例是傳遞無效的參數名稱)。


查看完整回答
反對 回復 2023-09-16
  • 2 回答
  • 0 關注
  • 117 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號