I keep running in circles with trying to use PowerShell within a C# Application. I know everything I need to do is capable within PowerShell, I just want to wrap a GUI around it to make things easier.
I have PowerShell.SDK and Management.Automation installed with Nuget.
I initially created a PowerShell and tried to do the commands.
PowerShell powerShell = PowerShell.Create();
But that's when I found that this creates a basic shell and didn't have my modules or policies. I did the follwing and it errors out saying it tried to do a user interaction. How do I get it to allow user interaction? I would be done if this worked.
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
PropertyInfo[] propertyInfo = initialSessionState.GetType().GetProperties();
propertyInfo[2].SetValue(initialSessionState, ExecutionPolicy.Unrestricted, null);
initialSessionState.ImportPSModule(new string[] { "Microsoft.Online.SharePoint.PowerShell" });
Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState);
runspace.Open();
PowerShell powerShell = PowerShell.Create(runspace);
powerShell.AddCommand("Connect-SPOService").AddParameter("-Url", "<https://site admin.sharepoint.com>").AddParameter("-Credential", "name@site.com").Invoke();
I then tried to manually create the Credential needed by the connect. But it now throws exceptions in the Output Windows and does nothing. I have no way of knowing why since they happened within Invoke. How do I see the actual errors from PowerShell?
System.Security.SecureString passwordSecure = new System.Security.SecureString();
foreach (char a in "FakePassword") { passwordSecure.AppendChar(a); }
System.Management.Automation.PSCredential passwordCredential = new System.Management.Automation.PSCredential("name@site.com", passwordSecure);
runspace.SessionStateProxy.SetVariable("PasswordCredential", passwordCredential);
powerShell.AddCommand("Connect-SPOService").AddParameter("-Url", "https://site-admin.sharepoint.com").AddParameter("-Credential", "name@site.com").Invoke();
How do I create a PowerShell in C# that inherits my personal PowerShell Environment? I think dependencies are hitting me too.