[英]Powershell script not running or giving and output
我正在使用一個腳本運行以下代碼,該腳本應該在員工更改名稱時更改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
看看ps.Streams.Error
和ps.Streams.Warning
,看看是否有任何東西可能指向正確的方向。 請注意, 如果存在終止錯誤,將調用catch。 許多命令因非終止錯誤而失敗。 另一個選項是使用ps.Runspace.SessionStateProxy.SetVariable()
將全局變量ErrorActionPreference
設置為Stop
。 這會將所有非終止錯誤轉換為您的catch語句可以捕獲的終止錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.