Calling Invoke-Command from C# with different Credential RRS feed

  • Question

  • Hi everyone,

    I have a weird behavior concerning the code below. (the real command is more complex but the issue is the same)


    I want to run the "Invoke-Command -ComputerName remoteserver -Credential credential -ScriptBlock {Get-Command Get-Di*}" on the client, from C#. Then I decided to test the C# code on the localhost and it works, but it does not remotely. (FYI it works interactively in powershell). Here you are the code :

    string srvdhcp = "srvdhcp";
    string _pwdConnect = "secret";
    string _userConnect = "Administrator";
    string argumentList = "Get-Di*";
    //Create Credential Object
    SecureString secString = new SecureString();
    foreach (char c in _pwdConnect)
    PSCredential credential = new PSCredential(userName: _userConnect, password: secString);
    ScriptBlock scriptBlock = ScriptBlock.Create(@"
         Get-Command $argumentList");
    IEnumerable<PSObject> result = test(srvdhcp, scriptBlock, argumentList, credential);
    private IEnumerable<PSObject> test(string srvdhcp, ScriptBlock scriptBlock, string argumentList, PSCredential credential)
         PowerShell pShell = PowerShell.Create();
         return pShell.AddCommand("Invoke-Command")
                      .AddParameter("ComputerName", srvdhcp)
                      .AddParameter("Credential", credential)
                      .AddParameter("ScriptBlock", scriptBlock)
                      .AddParameter("ArgumentList", new object[] { argumentList })

    The key of learning is practice.

    Tuesday, May 15, 2018 8:32 PM


  • This is not a C# forum.  Post C# questions in the C# forum


    • Edited by jrv Tuesday, May 15, 2018 9:37 PM
    • Marked as answer by arnaud.helin Wednesday, May 16, 2018 1:42 AM
    Tuesday, May 15, 2018 9:36 PM