0

I am trying to execute powershell commands on remote machine using the following code:

        string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
        PSCredential remoteCredential = new PSCredential("User", StringToSecureString("password"));

        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
            false, "ipaddress", 5985, "/wsman", shellUri, remoteCredential, 1 * 60 * 1000);

        Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
        runspace.Open();

        using (PowerShell ps = PowerShell.Create())
        {
            ps.Runspace = runspace;
            ps.AddCommand("get-process");

            Collection<PSObject> res = ps.Invoke();
        }

StringToSecureString method listing:

    private SecureString StringToSecureString(string str)
    {
        SecureString secureStr = new SecureString();

        foreach(char c in str)
        {
            secureStr.AppendChar(c);
        }

        return secureStr;
    }

I can succesfully execute some commands like "get-process" or "get-service".

But there some commands (e.g. "$env:username") that throw the next error:

The term is not recognized as a cmdlet, function, operable program, or script file.

But "$env:username" command will succesfully execute if I connect using powershell directly:

Enter-PSSession -ComputerName ipaddress -Credential username

There are some other commands not connected to environment variables I can't execute too (CLI app command not working using code nor powershell).

I am new to powershell and WinRM and have no idea what is wrong. Does anyone know the reason?

mklement0
  • 382,024
  • 64
  • 607
  • 775

0 Answers0