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 ?