0

I want to open powershell from C# code like this. However, i want to set a credential to powershell when it comes up.

Process myProcess = new Process();

try
{
    myProcess.StartInfo.UseShellExecute = true;
    myProcess.StartInfo.FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
    myProcess.StartInfo.CreateNoWindow = false;
    myProcess.Start();

}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

Essentially after powershell is running i want to do a Enter-PSSession to connect to remote computer but i don't want to prompt for username and password there.

I know this can be done.

PS C:\> $C = Get-Credential
PS C:\> Enter-PsSession -ComputerName "Server01" -Credential $C

I don't want to ask the user for credentials, instead i want to set it in the variable when invoking powershell. How can i achieve this ?

Current approach is two fold,

Dump the password via C#

string cmd = "\"" + mypwd+ "\"" + @" | ConvertTo-SecureString -AsPlainText -Force | convertfrom-securestring | out-file output";
PowerShellInstance.AddScript(cmd);
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

read it in powershell

$pwd = Get-Content .\output | ConvertTo-SecureString
$localcred = New-Object -typename System.Management.Automation.PSCredential -argumentlist "myusername",$pwd

Enter-PSSession -ComputerName 192.168.2.51 -Credential $localcred

Is there a neater way ?

amarnath chatterjee
  • 1,942
  • 16
  • 15
  • Aa far as I know you can use an ICredential object in powershell (I do it all the time for Sharepoint) for a PSCredential object. Using a NetworkCredential object should also work. However, it's bad practice to hardcode credentials. – bluuf Feb 16 '17 at 07:37

1 Answers1

0

you can use credential manager and avoid the hard coding or interactive get-credential : Accessing Windows Credential Manager from PowerShell or https://gallery.technet.microsoft.com/scriptcenter/how-to-add-credentials-to-c8e9bd5f

Community
  • 1
  • 1
ClumsyPuffin
  • 3,909
  • 1
  • 17
  • 17