Embedded PowerShell script file on a remote server using a c#

0

Hi I am trying to execute a embedded powershell script file on a remote server using a c# method.

My powershell file contains the following:

param(
[System.Management.Automation.PSCredential]$Credential           
)

try {
    Write-Host 'Do Some work here'

}
catch{
    Write-Host  $_.Exception.Message
}

**My calling code is as follows** 

private void InvokeScript(string computerName)
{
    const string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
    var netCreds = new PSCredential(@"XXX", ConvertToSecureString("XXX"));

    var connectionInfo = new WSManConnectionInfo(false, computerName, 5985, "/wsman", shellUri, netCreds);
    using (var runspace = RunspaceFactory.CreateRunspace(connectionInfo))
    {
        var credentials = new PSCredential(@"XXX\XXX", ConvertToSecureString("XXX"));
        runspace.Open();

        var pipeline = runspace.CreatePipeline();
        var scriptCommand = new Command(GetScript());

        var commandParmeter = new CommandParameter("$Credential", credentials);
        scriptCommand.Parameters.Add(commandParmeter);
        pipeline.Commands.Add(scriptCommand);
        var results = pipeline.Invoke();
    }
}

private static string GetScript()
{
    var assembly = Assembly.GetExecutingAssembly();
    var resourceName = "TestProject.Scripts.RemoteShell.ps1";

    using (var stream = assembly.GetManifestResourceStream(resourceName))
    using (var reader = new StreamReader(stream))
    {
        var script = reader.ReadToEnd();
        return script;
    }
}

private static SecureString ConvertToSecureString(string password)
{
    var securePassword = new SecureString();

    foreach (var c in password)
    {
        securePassword.AppendChar(c);
    }

    securePassword.MakeReadOnly();
    return securePassword;
}

When i Execute i get the following exception

System.Management.Automation.RemoteException HResult=0x80131501
Message=The term 'param( [System.Management.Automation.PSCredential]$Credential )

try { Write-Host 'Adding computer to domain' } catch{ Write-Host $_.Exception.Message }

' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Source=System.Management.Automation

c#
.net
powershell
remotecommand
asked on Stack Overflow Mar 8, 2019 by MicroMan

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0