O365 Quarantine Powershell Commands does not work

81 Views Asked by At

O365 Quarantine Powershell Commands does not work when logon user for the deployed windows service is changed from Local System Account to another administrator account. The same thing happens when visual studio is run as a different user.

The test account has administratorprivilege.

There are no errors or exceptions in the code but the powershell command does not return any result. I'm getting the expected results when the code is running as administrator.

public void Process(bool ChkForMissedQuarantine = false, String AppendCondition = default(string), DateTime dtStartEx = default(DateTime), DateTime dtEndEx = default(DateTime), PowerShell powershell = null)
        {
            try
            {

                List<Mail_Properties> bunch_of_Mail_Properties = new List<Mail_Properties>();
                Dictionary<string, string> _IdentityProcessed = new Dictionary<string, string>();

                try
                {
                    int intStatus = 0;
                    DateTime DateValueFromDatabase = DateTime.Now.AddDays(-1);
                    DateTime dtEndDate = DateTime.Now.AddDays(+1);
                    if (ChkForMissedQuarantine == false)
                    {

                        //Get Lastest Date from Data Table spGetLatestQuarantineReceivedTime
                        Log.Debug(this);

                        if (QuarantineService.Globals.IsDebug == true)
                        {
                            DateValueFromDatabase = QuarantineService.Globals.gStartDate;
                            dtEndDate = QuarantineService.Globals.gEndDate.AddDays(1);
                        }
                        else
                        {
                            DateValueFromDatabase = _DataProvider.Get_Latest_Quarantine_Received_Time();
                            dtEndDate = System.DateTime.Now.AddDays(1);
                        }


                        Log.Debug(this);
                    }
                    else
                    {
                        Log.Debug(this);
                        DateValueFromDatabase = dtStartEx;
                        dtEndDate = dtEndEx;
                    }

                    // Create secure credential
                    SecureString secureString = new SecureString();
                    SecureString secureString2 = new SecureString();
                    //string myPassword = VidyatechCrypto.Decrypt(_DataProvider.AppConfig["SecureStringPWD"].ToString()); //1     2
                    string myPassword = "4rfv%TGB6yhn"; //1     2
                    string myPassword2 = "Vidyatech123"; //1     2
                    //string myPassword = "2wsx#EDC4rfv"; //1     2
                    foreach (char c in myPassword) secureString.AppendChar(c);

                    foreach (char c in myPassword2) secureString2.AppendChar(c);


                    Log.Debug(this);
                    try
                    {
                        // Make O356 Connection
                        //PSCredential credential = new PSCredential("[email protected]", (System.Security.SecureString)secureString);
                        PSCredential credential = new PSCredential("[email protected]", (System.Security.SecureString)secureString);
                        PSCredential credential2 = new PSCredential("chris", (System.Security.SecureString)secureString2);

                        bool valid = false;

                        if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened)
                            valid = true;
                        if (valid == false)
                        {
                            runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
                            Log.Debug(this);
                            powershell = PowerShell.Create();

                            PSCommand command = new PSCommand();
                            //command.AddCommand("New-PSSession");
                            //command.AddParameter("ConfigurationName", "Microsoft.Exchange");
                            //command.AddParameter("ConnectionUri", _DataProvider.AppConfig["WSManConnectionInfoURI"].ToString());
                            //command.AddParameter("Credential", credential);
                            //command.AddParameter("Authentication", "Basic");
                            //command.AddParameter("AllowRedirection");
                            //command.AddCommand("Set-ExecutionPolicy");
                            //command.AddParameter("ExecutionPolicy", "Unrestricted");
                            //command.AddParameter("ExecutionPolicy", "RemoteSigned");
                            //command.AddParameter("Scope", "LocalMachine");
                            command.AddCommand("import-module");
                            command.AddParameter("Name", "exchangeonlinemanagement");
                            Log.Debug(this);
                            if (ConfigurationManager.AppSettings["ProxySettings"] != null && !string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["ProxySettings"].ToString()))
                            {
                                Log.Debug(this);
                                string strScript = string.Format("netsh winhttp set proxy proxy-server=\"{0}\"", ConfigurationManager.AppSettings["ProxySettings"].ToString());
                                powershell.AddCommand("Invoke-Expression");
                                powershell.AddArgument(strScript);
                            }
                            Log.Debug(this);
                            powershell.Commands = command;

                            Log.Debug(this);
                            runspace.Open();
                            Log.Info(this, "Runspace opened");


                            powershell.Runspace = runspace;

                            Collection<PSSession> result = powershell.Invoke<PSSession>();
                            Log.Debug(this);
                            foreach (ErrorRecord current in powershell.Streams.Error)
                                Log.Debug("The following Error happen when opening the remote Runspace: " + current.Exception.ToString() + " | InnerException: " + current.Exception.InnerException);
                            Log.Debug(this);
                            //if (result.Count != 1)
                            //{
                            //    Exception exp = new System.Exception("Unexpected number of Remote Runspace connections returned. Or invalid credentials");
                            //    Log.Error(exp);
                            //    return;
                            //}
                            //    Log.Debug(this);
                            //    resultValue = result[0];
                            //    Log.Debug(this);
                            //    // Set the runspace as a local variable on the runspace
                            //    powershell = PowerShell.Create();
                            //    command = new PSCommand();
                            //    command.AddCommand("Set-Variable");
                            //    command.AddParameter("Name", "ra");
                            //    command.AddParameter("Value", result[0]);
                            //    powershell.Commands = command;
                            //    powershell.Runspace = runspace;
                            //    Log.Debug(this);
                            //    powershell.Invoke();
                            //    Log.Debug(this);

                            //    Log.Debug(this);
                            //}



                            _IdentityProcessed = _DataProvider.GetProcessedQurantine(DateValueFromDatabase, dtEndDate);
                            if (ChkForMissedQuarantine == false)
                            {
                                AppendCondition = "";
                            }
                            else
                            {
                                Log.Info(this, AppendCondition);
                            }

                            int _pageNo = 1;

                            powershell = PowerShell.Create();
                            string _IdentityKey = "";
                            int _Count = 0;
                            int PageSize = 50;
                            //Log.Info(this,"PageSize is : " +PageSize.ToString() + " and Page Number is : " + _pageNo.ToString()   );
                            bool bln = true;
                            while (bln == true)
                            {

                                PSCommand pscommand = new PSCommand();
                                // First import the cmdlets in the current runspace (using Import-PSSession)

                                Log.Info(this, "PageSize is : " + PageSize.ToString() + " and Page Number is : " + _pageNo.ToString());
                                pscommand = new PSCommand();
                                //string strScript = string.Format("Invoke-Command -ScriptBlock {{Get-QuarantineMessage -PageSize 1000 -Type TransportRule -Direction Outbound -QuarantineTypes TransportRule -StartReceivedDate {0} -EndReceivedDate {1} }} -Session $ra", DateValueFromDatabase.ToString("M/d/yyyy"), System.DateTime.Now.AddDays(1).ToString("M/d/yyyy"));
                                //string strScript = string.Format("Invoke-Command -ScriptBlock {{Get-QuarantineMessage -PageSize {0} -Page {1} -Type TransportRule -Direction Outbound -QuarantineTypes TransportRule -StartReceivedDate {2} -EndReceivedDate {3}{4}}} -Session $ra", PageSize.ToString(), _pageNo.ToString(), DateValueFromDatabase.ToString("M/d/yyyy"), dtEndDate.ToString("M/d/yyyy"), AppendCondition);
                                //pscommand.AddScript(strScript);
                                pscommand.AddCommand("Enter-PSSession");
                                pscommand.AddParameter("ComputerName", "localhost");
                                pscommand.AddParameter("Credential", credential2);
                                //pscommand.AddParameter("ExecutionPolicy", "Unrestricted");
                                pscommand.AddParameter("Scope", "CurrentUser");
                                //pscommand.AddParameter("ExecutionPolicy", "RemoteSigned");
                                //pscommand.AddStatement();
                                //pscommand.AddCommand("Set-ExecutionPolicy");
                                //pscommand.AddParameter("ExecutionPolicy", "RemoteSigned");
                                //pscommand.AddParameter("ExecutionPolicy", "Unrestricted");
                                //pscommand.AddParameter("Scope", "CurrentUser");
                                //pscommand.AddParameter("ExecutionPolicy", "RemoteSigned");
                                pscommand.AddStatement();
                                pscommand.AddCommand("import-module");
                                pscommand.AddParameter("Name", "exchangeonlinemanagement");
                                pscommand.AddStatement();
                                pscommand.AddCommand("connect-exchangeonline");
                                pscommand.AddParameter("Credential", credential);
                                pscommand.AddStatement();
                                pscommand.AddCommand("connect-ippssession");
                                pscommand.AddParameter("Credential", credential);
                                pscommand.AddStatement();

                                pscommand.AddCommand("Get-QuarantineMessage");
                                //pscommand.AddParameter("PageSize", PageSize.ToString());
                                //pscommand.AddParameter("Page", _pageNo.ToString());
                                pscommand.AddParameter("Type", "TransportRule");
                                pscommand.AddParameter("Direction", "Outbound");
                                pscommand.AddParameter("QuarantineTypes", "TransportRule");
                                pscommand.AddParameter("StartReceivedDate", DateValueFromDatabase.ToString("M/d/yyyy"));
                                pscommand.AddParameter("EndReceivedDate", dtEndDate.ToString("M/d/yyyy"));

                                powershell.Commands = pscommand;
                                powershell.Runspace = runspace;

                                Log.Info(this, "TESTCOMMAND" + JsonConvert.SerializeObject(powershell.Commands));
                                //Log.Info(this, "TESTRUNSPACE" + JsonConvert.SerializeObject(powershell.Runspace));
                                // Log.Info(this, "TESTPOWERSHELL" + JsonConvert.SerializeObject(powershell));
                                Log.Debug(this);
                                Collection<PSObject> results = new Collection<PSObject>();
                                Log.Debug(this);
                                results = powershell.Invoke();
                                Log.Info(this, "QuarantineMessage Count : " + results.Count.ToString());
                                Log.Debug(this);
                                _Count = results.Count;
                                int i = 0;//
                                foreach (PSObject obj in results)
                                {

                                    string id = obj.Members["Identity"].Value.ToString();
                                    _IdentityKey = id;
                                    Log.Info(this, _IdentityKey);
                                    if (_IdentityProcessed.ContainsKey(_IdentityKey))
                                    {
                                        if (ChkForMissedQuarantine == false)
                                            bln = false;
                                        if (Globals.IsDebug == false)
                                        {
                                            Log.Info(this, _IdentityKey);
                                            if (ChkForMissedQuarantine == false)
                                                break;
                                        }

                                    }
                                    else
                                    {
                                        _IdentityProcessed.Add(_IdentityKey, "True");
                                        Mail_Properties mp = new Mail_Properties();
                                        ReleaseQuarantine rq = new ReleaseQuarantine();
                                        i = i + 1;
                                        Log.Info(this, _IdentityKey);

                                        mp.Identity = obj.Members["Identity"].Value + "";
                                        mp.DlpUniqueMsgID = ExtractUniqueIDfromHeader(mp.Identity, credential);
                                        mp.ReceivedTime = Convert.ToDateTime(obj.Members["ReceivedTime"].Value); /// outputDateTimeValue;// obj.Members["ReceivedTime"].Value;
                                        mp.SenderAddress = obj.Members["SenderAddress"].Value + "";
                                        mp.RecipientAddress = obj.Members["RecipientAddress"].Value + "";
                                        mp.Subject = obj.Members["Subject"].Value + "";
                                        mp.Size = Convert.ToInt32(obj.Members["Size"].Value); //
                                        mp.Expires = Convert.ToDateTime(obj.Members["Expires"].Value);  //obj.Members["Expires"].Value.ToString() + ""; //Is it DateTime "StartExpiresDate"                  //mp.PolicyType = obj.Members["PolicyType"].Value.ToString()+"";
                                        mp.Released = Convert.ToBoolean(obj.Members["Released"].Value);
                                        mp.RecipientCount = Convert.ToInt32(obj.Members["RecipientCount"].Value);
                                        mp.QuarantinedUser = obj.Members["QuarantinedUser"].Value + "";

                                        Log.Debug(this);

                                        rq.Identity = mp.Identity;
                                        rq.ToBeRelease = false;
                                        rq.ToBeDelete = false;
                                        Log.Debug(this);

                                        intStatus = _DataProvider.Insert_Quarantine(mp, rq);
                                        if (intStatus == 0)
                                        {
                                            Log.Info(this, "function Insert_Quarantine fail");
                                        }
                                        else
                                        {
                                            Log.Info(this, "Inserted: " + mp.Identity);
                                        }
                                        Log.Debug(this);

                                    }
                                }

                                if (_Count < PageSize)
                                {
                                    bln = false;
                                    Log.Debug(this);
                                }
                                _pageNo++;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                    }
                    finally
                    {
                        Log.Debug(this);


                        if (ChkForMissedQuarantine == false)
                        {
                            Log.Debug(this);
                            powershell.Stop();
                            Log.Debug(this);
                            powershell.Runspace.Close();
                            Log.Debug(this);
                            runspace.Dispose();
                            Log.Debug(this);
                        }
                    }

                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    //System.Windows.Forms.MessageBox.Show("Quarantines insertsion fail!");
                }

            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }
0

There are 0 best solutions below