【问题标题】:C# running powershell command how to pass byte arrayC#运行powershell命令如何传递字节数组
【发布时间】:2017-04-28 21:16:14
【问题描述】:

我正在尝试从 c# 代码调用 powershell 命令,并且需要作为参数字节数组传递,但它转换为错误的格式。 C#代码:

var command = new Command("Set-UserPhoto");
command.Parameters.Add("Identity", login);
command.Parameters.Add("Confirm", false);
command.Parameters.Add("PictureData", pictureData); //byte array

其实是powershell:

Set-UserPhoto -Identity:'hennadiy.lebedyev@itera.no' -Confirm:$False -PictureData:'255','216','255','224',...,'0','16'

需要powershell:

Set-UserPhoto -Identity:'hennadiy.lebedyev@itera.no' -Confirm:$False -PictureData:(255,216,255,224,...,0,16)

使用函数 AddScript powershell 无法运行。

【问题讨论】:

  • 您不会使用实际的 powershell 命令来执行此操作。您将加载一个文件,将其通过管道传递给命令并使用管道对象作为参数。事实上,Set-UserPhoto 与流而不是字节缓冲区一样工作
  • 可能与您的问题正交,但您为什么使用 C# 调用 powershell?你不能直接调用你的脚本使用的任何 API,绕过所有的 powershell 限制吗?

标签: c# arrays powershell


【解决方案1】:

如果您的“Command”类相当于 System.Management.Automation.PSCommand,那么您做对了。

下面是我用来执行此操作的代码:

const string connectionUri = "https://outlook.office365.com/powershell-liveid/?proxymethod=rps";
const string schemaUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";

const string loginPassword = "password";
SecureString secpassword = new SecureString();
foreach (char c in loginPassword)
{
    secpassword.AppendChar(c);
}
PSCredential exchangeCredential = new PSCredential("demo@sample.com", secpassword);

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(connectionUri), schemaUri, exchangeCredential)
{
    MaximumConnectionRedirectionCount = 5,
    AuthenticationMechanism = AuthenticationMechanism.Basic
};

using (var remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
    remoteRunspace.Open();

    using (PowerShell powershell = PowerShell.Create())
    {
        powershell.Runspace = remoteRunspace;

        var command = new PSCommand()
            .AddCommand("Set-UserPhoto")
            .AddParameter("Identity", "user@sample.com")
            .AddParameter("PictureData", File.ReadAllBytes(@"C:\Test\MyProfilePictures\pic.jpg"))
            .AddParameter("Confirm", false);
        powershell.Commands = command;
        powershell.Invoke();
    }
}

?proxymethod=rps is important to support >10Ko files

希望有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2021-01-08
    • 2021-12-16
    • 2023-04-06
    • 1970-01-01
    • 2020-11-10
    • 2016-05-18
    相关资源
    最近更新 更多