locked
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)

    Context

    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)
          secString.AppendChar(c);
    PSCredential credential = new PSCredential(userName: _userConnect, password: secString);
    
    //Scriptblock
    ScriptBlock scriptBlock = ScriptBlock.Create(@"
         Param(
              $argumentList
         )
                
         Get-Command $argumentList");
    
    string argumentList = "Get-Di*";
    try
    {
    IEnumerable<PSObject> a = test(srvdhcp, scriptBlock, argumentList, credential);
                   
    foreach (PSObject obje in a)
    MessageBox.Show(obje.BaseObject.ToString());
    }
    catch (Exception e)
    {
    MessageBox.Show(e.Message);
    } private IEnumerable<PSObject> test(string srvdhcp, ScriptBlock scriptBlock, string argumentList, PSCredential credential) { PowerShell pShell = PowerShell.Create(); pShell.Commands.Clear(); return pShell.AddCommand("Invoke-Command") .AddParameter("ComputerName", srvdhcp) .AddParameter("Credential", credential) .AddParameter("ScriptBlock", scriptBlock) .AddParameter("ArgumentList", new object[] { argumentList }) .Invoke(); }



    The key of learning is practice.





    The key of learning is practice.



    Wednesday, May 16, 2018 1:41 AM

All replies

  • Did you capture any error? Probably you have to set the execution policy to remotesigned through the code.
    Wednesday, May 16, 2018 3:53 AM