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 cmd开发者_Python百科let 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);
精彩评论