PSCommand Not Working on Windows Store Apps - c#

I am building an windows store app . I need to connect to exchange server through powershell commands. So to execute my commands i wrote the following code.
PSCommand d_cmd = new PSCommand();
d_cmd.AddCommand("$secure_string_pwd = convertto-securestring 'testpa' -asplaintext -force");
d_cmd.AddCommand("$username = 'test#email.com'");
d_cmd.AddCommand("$cred = New-Object System.Management.Automation.PSCredential $username, $secure_string_pwd");
d_cmd.AddCommand("Import-Module MSOnline");
d_cmd.AddCommand("$O365Cred = Get-Credential");
d_cmd.AddCommand("$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection");
d_cmd.AddCommand("Import-PSSession $O365Session");
When i am executing the above i am getting following error as follows..
Cannot find type System.SystemException in module mscorlib.dll.
When i removed the system.management.automation that error is gone but not executed powershell commands.
Can anybody suggest me on how we can execute powershell commands in windows store apps?

Related

Using connect-exchangeonline PS via a proxy from within C# (.NET Core 3.1)

I am developing a .NET Core 3.1 API that is trying to connect to Exchange Online by calling Powershell from behind a Proxy that you need to authenticate with.
If I run the below Powershell script in Powershell it connects without an issue and pulls back the required data:
$certthumb="xxxxxx"
$appid="xxxxxx"
$org="xxxxxx"
$proxyserver="xxxxxx:8080"
$webproxypsd = "xxxxxx"
$secureWebproxypsd = $webproxypsd | ConvertTo-SecureString -AsPlainText -Force
$proxyCredential = new-object System.Management.Automation.PSCredential ("xxxxxxx",$secureWebproxypsd)
Set-ExecutionPolicy Unrestricted -force
$proxysettings = New-PSSessionOption -ProxyAccessType IEConfig -ProxyCredential $proxyCredential -ProxyAuthentication Basic
$w=New-Object System.Net.WebClient
$w.Proxy.Credentials = $proxyCredential
import-module ExchangeOnlineManagement
Connect-exchangeonline -CertificateThumbPrint $certthumb -AppID $appid -organization $org -PSSessionOption $proxysettings
Get-MailUser "xxxxxx" |fl exchangeguid
If I try and run the same script above in a script file (c:\temp\exchangeonline.ps1) from within C# I get the following error - I have tried using C# with PS (i.e. not using a PS script file) and I get the same error:
{System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The remote server returned an error: (407) Proxy Authentication Required
The C# code is as follows:
using (Runspace localRunSpacePool = RunspaceFactory.CreateRunspace())
{
localRunSpacePool.Open();
using (var PowerShellInstance = ConnectToExchangeOnline(localRunSpacePool))
{.....}
public PowerShell ConnectToExchangeOnline(Runspace localRunSpacePool)
{
var PowerShellInstance = PowerShell.Create();
PowerShellInstance.Runspace = localRunSpacePool;
var error = localRunSpacePool.SessionStateProxy.PSVariable.GetValue("Error");
var scriptfile = "c:\\temp\\exchangeonline.ps1";
PowerShellInstance.AddScript(scriptfile);
var scriptresult = PowerShellInstance.Invoke();
error = localRunSpacePool.SessionStateProxy.PSVariable.GetValue("Error");
PowerShellInstance.Commands.Clear();
......}
The error variable shows the above error I displayed re: the proxy authentication issue..
Any ideas how I can get this working via the proxy where the proxy requires authentication? This using C# of course. Also, we have to use MFA authentication with ExchangeOnline...
Thanks,
Marcus

How to run a Powershell script with Rename-Computer in it using C#

I need to run a Powershell Script using C# with "Rename-Computer" in it on a Windows 2016 Server.
The Problem is that it is not working or executing correctly.
The remote Computer doesn't get renamed and also not in the AD.
When Executing there are no Errors. Only thing i know is that ps.HadErrors is true.
When I run the script nothing happens.
Expected Result would be the renamed Computer
Actual Result is that the computername stays the same as before
I already tried executing the Powershell Script on the Windows Server and it worked as it is supposed to. I also tried Executing a other Powershell Script in C# that is writing to a File and it worked. Another thing i tried is to add the Module and the Command to Runspace, but it also did not change anything.
This is the Code i tried:
public static readonly string script = $#"
Import-Module ActiveDirectory
$password = ConvertTo-SecureString ""passwort"" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential(""Administrator"", $password)
Rename-Computer -ComputerName ""Computer01"" -NewName ""NewComputer01"" -DomainCredential
$credential -Force";
public static void Main(string[] args)
{
try
{
InitialSessionState iss = InitialSessionState.CreateDefault();
Runspace rs = RunspaceFactory.CreateRunspace(iss);
rs.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddScript(script);
ps.Invoke();
}
catch (Exception e)
{
Console.WriteLine("Message :{0} ", e.Message);
}
}
I hope you can help and everything is clear.
The Problem was that I used an .Net Core Application so I had to use Powershell Core. Somehow it cannot make the WMI Connection when using Powershell Core, but it worked with Windows Powershell. So I had to reconfigure WMI on the Windows 10 Client and it worked!

Why does powershell not recognize cmdlets in a script called by a windows service?

We have a windows service which runs as the local system account. It calls a PowerShell script and retrieves the output for further processing. It works like a charm under windows server 2016 but now needs to be moved to a windows server 2012 R2. On this machine, it does not recognize the azure specific cmdlets.
I tried to install the specific cmdlets via -Scope AllUsers. We also logged into the PowerShell directly as local system-user; it does recognize the cmdlets (e.g. Add-AzureRMAccount) correctly.
C#:
PowerShell psInstance = PowerShell.Create();
psInstance.AddScript(scriptBase + "getVMs.ps1");
var azureVMList = psInstance.Invoke();
getVMs.ps1:
$finalPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList $accountName, $finalPassword
$trash = Add-AzureRmAccount -Credential $psCred -TenantId $tenantID -ServicePrincipal`
We don't understand why the cmdlets are working fine under the same circumstances on server 2016 and if we run them directly as the user.
Any hint is appreciated
I suggest a workaround here, in your c# code, directly import the module which contains the cmdlet.
1.you can use this command to get the module file(I'm using az module, feel free to change to azureRm module):
(Get-Module -Name az.accounts).Path
then you can see the module file path, in my side, it's "C:\Program Files\WindowsPowerShell\Modules\Az.Accounts\1.5.2\Az.Accounts".
2.in your c# code:
InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] {"the full path of Az.Accounts.psd1, if it does not work, try full path of Az.Accounts.psm1"} );
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddScript(scriptBase + "getVMs.ps1");
var azureVMList = psInstance.Invoke();

Windows Store App with powershell

I am developing a windows 8.1 store app and in that i want to get the GAL and add the GAL by using power shell script. When i tried to add the referance to System.Security.SecurityString it is giving an errors like follows.. I am trying to authenticate to with my office365 admin details but it is giving an error while building the app.
'System.Management.Automation.PSCredential' does not contain a constructor that takes 2 arguments
But it contains a constructor with two arguments , The same code works well when i build a windows forms application. What will be the wrong with windows 8.1 app?
System.Uri psURL = new Uri("https://ps.outlook.com/powershell/");
System.Security.SecureString securePassword1 = safeString("test");
System.Management.Automation.PSCredential creds1 = new System.Management.Automation.PSCredential("test", securePassword1);
Questions
1) Is System.Security.SecurityString is compatible with windows 8.1 app or this error coming from PSCredential why because when i removed the securestring referance the PSCredential error not happening but getting securestring error missing like that?
2) Is there any alternative method to connect to powershell without secure string by c# code?
System.Security.SecureString is part of the .NET Framework.
It is not visible in your example code how you convert your string to secure string:
$secure_string_pwd = convertto-securestring "P#ssW0rD!" -asplaintext -force
$username = "username#yourdomain.com"
$cred = New-Object System.Management.Automation.PSCredential $username, $secure_string_pwd
Try to connect to O365 with following code:
Import-Module MSOnline
$O365Cred = Get-Credential
$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange
-ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred
-Authentication Basic -AllowRedirection
Import-PSSession $O365Session
Connect-MsolService –Credential $O365Cred
You might also find this article interesting - the example code is taken from there...

C# \ Exchange 2010 PS1 Script

I am trying to run a PS1 script using Exchange 2010 remote powershell and c#. I can connect and run the ps1 script but there are a few places in the script that use exchange cmdlets to update necessary user information. One cmdlet the script is using is update-recipient. The script runs fine until it trys to run this cmdlet and errors saying:
The term 'update-recipient' is not recognized as the name of a cmdlet, function, script file, or operable program.
Does anyone know if there are any restrictions on running cmdlets inside of PS1 scripts from c#?
Thanks
In order to run an Exchange 2010 powershell script from the command line, you need to load the Exchange components at the beginning of the powershell script. Add these 2 lines to your .ps1 file. Substitute your Exchange server's name for EXCHANGESERVER in the first line.
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://EXCHANGESERVER/PowerShell/ -Authentication Kerberos
Import-PSSession $Session
Try this sample code ( in know it works for Exchange 2010)
PSCredential credential = new PSCredential(#"domain\user", createPassword("Pass"));
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "exchange.ibm.com", 80, "/Powershell", "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
try
{
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
Command objCommand = new Command("");
objCommand.Parameters.Add("Identity", #"dom\user");
pipeline.Commands.Add(objCommand);
Collection<PSObject> results = pipeline.Invoke();
}
catch
{
}
finally
{
runspace.Close();
}
Or try this code for Exchange 2007 from MSFT
Runspace myRunspace = RunspaceFactory.CreateRunspace();
myRunspace.Open();
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
myRunSpace.Open(rsConfig);

Categories

Resources