我正在使用一个脚本运行以下代码,该脚本应该在员工更改名称时更改Outlook帐户的用户主体名称。
当我调用ps.Invoke()
时,代码运行大约需要30-60秒,然后当我检查调试器中的results
变量时,它只包含一个空列表。然后,我检查帐户UPN是否已更改,但它没有。但是,如果我将脚本字符串复制并粘贴到PowerShell窗口中,它就会执行并正常工作。
有没有人有任何想法?
public bool RenameOutlookAccount(string originalEmail, string newEmail)
{
bool result = false;
try
{
// Set up credentials
string username = _config.AppSettings.Settings["PowershellUser"].Value;
string password = _config.AppSettings.Settings["PowershellPassword"].Value;
// Create the PowerShell object
PowerShell ps = PowerShell.Create();
// Add the script
string script = String.Format(@"$secpasswd = ConvertTo-SecureString ""{0}"" -AsPlainText -Force; $Cred = New-Object System.Management.Automation.PSCredential (""{1}"", $secpasswd); $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection; Import-PSSession $Session; Import-Module Msonline; Connect-MsolService -Credential $Cred; Set-MsolUserPrincipalName -UserPrincipalName {2} -NewUserPrincipalName {3}; Remove-PSSession $Session", password, username, originalEmail, newEmail);
ps.AddScript(script);
// Run
var results = ps.Invoke();
result = true;
}
catch (Exception ex)
{
result = false;
}
return result;
}
$secpasswd = ConvertTo-SecureString {password} -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential ({username}, $secpasswd)
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
Import-PSSession $Session
Import-Module Msonline
Connect-MsolService -Credential $Cred
Set-MsolUserPrincipalName -UserPrincipalName {oldUPN} -NewUserPrincipalName {newUPN}
Remove-PSSession $Session
答案 0 :(得分:2)
查看ps.Streams.Error
和ps.Streams.Warning
,了解其中是否有任何可能指向正确方向的内容。请注意,如果发生终止错误,您的catch将被调用。许多命令因非终止错误而失败。另一个选项是使用ErrorActionPreference
将全局变量Stop
设置为ps.Runspace.SessionStateProxy.SetVariable()
。这会将所有非终止错误转换为终止错误,然后catch语句可以捕获。