I have a multitenant Active Directory setup, and I connect to it remotely from a jumpbox server using PowerShell with the following script:
Relationship diagram
$cred = Get-Credential
$Session = New-PSSession -ComputerName XXXXXX -Credential $cred -Port XXXX
Enter-PSSession $Session
The jumpbox server has the Exchange Server Management tool (MS 0365) installed, and the Active Directories are synchronized with MS O365.
After connecting to PowerShell, I run the following commands to enable a mailbox:
Add-PSSnapin *recipientmanagementEnable-RemoteMailbox -Identity "SamAccountName" -RemoteRoutingAddress [email protected]
While the above commands work perfectly when run directly from PowerShell.
But unable to connect to PowerShell using C#. Need a equivalent code in C#.
Tried below code, need to fix this
// Create a PowerShell pipeline
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
// Create a PSSession
ps.AddCommand("New-PSSession");
//ps.AddParameter("ConfigurationName", "Microsoft.Exchange");
ps.AddParameter("ComputerName", "XXXXXXXX");
ps.AddParameter("Credential", new PSCredential("XXXXXX", ConvertPassword("XXXXXXX")));
ps.AddParameter("Port", XXXX);
var sessionResult = ps.Invoke();
ps.Commands.Clear();
// Add the Session
ps.AddCommand("Import-PSSession")
.AddParameter("Session", sessionResult[0]);
ps.Invoke();
// Add the *recipientmanagement snap-in
ps.Commands.Clear();
ps.AddCommand("Add-PSSnapin")
.AddParameter("Name", "*recipientmanagement");
ps.Invoke();
ps.Invoke();
// Enable Remote Mailbox
ps.Commands.Clear();
ps.AddCommand("Enable-RemoteMailbox");
ps.AddParameter("Identity", "SamAccountName");
ps.AddParameter("RemoteRoutingAddress", "[email protected]");
ps.Invoke();
Error:
at :// Add the Session
System.Management.Automation.CmdletInvocationException: 'Files cannot be loaded because running scripts is disabled on this system. Provide a valid certificate with which to sign the files.'
at : // Add the *recipientmanagement snap-in
System.Management.Automation.CommandNotFoundException: 'The term 'Add-PSSnapin' is not recognized as a name of a cmdlet, function, script file, or executable program.
at: // Enable Remote Mailbox
System.Management.Automation.CommandNotFoundException: 'The term 'Enable-RemoteMailbox' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.'
user26808188 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.