Search code examples
powershellexchange-server

Issues with Powershell Credentials not passing through


I have made an exit script that is supposed to be automated. The script works fine except for one part; the credential object that is in the beginning part does not follow through in one of the functions.

It still takes the credentals and connects to the online Exchange Powershell, but for some reason when the script goes on to disable the MSOl account, remove licenses, etc it stops and asks for credentials; which does not make sense because the service account signs in and connects and the session imports.

the code goes:

$username = "[email protected]"

$password = 'somepassword'

$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force 

$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd

###############################################################

Set-ExecutionPolicy RemoteSigned -Force

$Session = New-PSSession -ConfigurationName Microsoft.Exchange - 
ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential 
$creds -Authentication  Basic -AllowRedirection

Import-PSSession $Session

Connect-MsolService -Credential $creds

Import-Module ActiveDirectory

########################################################################


$Exit = import-csv 'C:\File\Path\ETC'

$DisabledUserParams = @{

AccountName = $Exit.SamAccountName.Trim()

UPN = "$($Exit.SamAccountName.ToLower().Trim())@Company.com" 

}

########################################################################
#Add the scrubber function to be standard on the script
function Disable-ThisMSOLACCOUNT{

#variables

$AccountInfo = Get-MsolUser -UserPrincipalName $DisabledUserParams.UPN 

$CurrentAccountSku = $AccountInfo.Licenses.AccountSkuId

$MSOLAccountSku = Get-MsolAccountSku

$MSOLAccountLicense = $MSOLAccountSku.AccountSkuId

$DistributionGroups = Get-DistributionGroup

$DLs = $DistributionGroups.PrimarySmtpAddress

$CheckDL = Get-DistributionGroupMember -Identity $DLs

$SharedMailboxes = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails SharedMailbox

$MailDGS= Get-Recipient -ResultSize unlimited -RecipientType MailUniversalDistributionGroup

############################################################################################

foreach ($License in $MSOLAccountLicense) {

$RemoveLicense =@{

RemoveLicense = $License

}

try {

        Set-MsolUserLicense -UserPrincipalName $DisabledUserParams.UPN  RemoveLicenses $RemoveLicense.RemoveLicense -ErrorAction Continue }

       catch [Microsoft.Online.Administration.Automation.InvalidUserLicenseException,Microsoft.Online.Administration.Automation.SetUserLicense] {

        if ($_.Exception.Message -ilike "*Unable to assign this license because it is invalid") {

        Write-Host 'Error taking off License'

        Write-Host 'Run the Check at End'

        Continue

   }
   }
   } 

#####################################################################################################


foreach ($Distrolist in $DLs) {

   $RemoveDLM =@{

   RemoveGroup = $Distrolist

   Name = $CheckDL.Name

   }

        if($DisabledUserParams.AccountName -match $RemoveDLM.Name) {

            try {

            Remove-DistributionGroupMember -identity $RemoveDLM.RemoveGroup -member $DisabledUserParams.AccountName  -Confirm:$False -ErrorAction Continue }

            catch [Microsoft.Exchange.Management.RecipientTasks.RemoveDistributionGroupMember] 

            {

                if ($_.Exception.Message -ilike "*You don't have sufficient permissions") {

                Continue

                }
            }
        } 


   continue

   }


#####################################################################################################

foreach ($SM in $SharedMailboxes) {

   $RemoveSM =@{

   RemoveSM = $SM.Name

   }

    try {

           Remove-Mailboxpermission -identity $RemoveSM.RemoveSM -User $DisabledUserParams.AccountName  -Confirm:$False -ErrorAction Continue } 

    catch { 

                continue

   } 


#####################################################################################################

foreach($DGS in $mailDGS) {

    $RemoveMDGS = @{

    RemoveMDGS = $DGS.Name}

    try{
        Remove-RecipientPermission $RemoveMDGS.RemoveMDGS -Trustee $DisabledUserParams.AccountName -AccessRights SendAs -Confirm:$False} 

   catch { 

            continue

    } 

}
}
}

function Disable-ThisADACCOUNT{

$OUTransfer = "OU=Disabled Users Accounts,DC=company,DC=local"

$ADAccountPG = Get-ADPrincipalGroupMembership -Identity $DisabledUserParams.AccountName

$CurrentAdGroup = $ADAccountPG.name

Foreach($Group in $CurrentAdGroup) {

    $RemoveAdG = @{

    RemoveGroup = $group}

    Remove-ADGroupMember -Identity $RemoveAdG.RemoveGroup -Members $DisabledUserParams.AccountName -Confirm:$False -ErrorAction SilentlyContinue}


Get-ADUser $DisabledUserParams.AccountName | Move-ADObject -TargetPath $OUTransfer

}

try { Get-ADUser $DisabledUserParams.AccountName}  catch 
[Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser] {

    if ($_.Exception.Message -ilike "*Cannot find an object with identity" )     { 

    Disable-ThisMSOLACCOUNT}

        else {Disable-ThisADACCOUNT

              Disable-ThisMSOLACCOUNT

              }

              }

The code gets hung up on the Disable-ThisMSOOLACCOUNT functon. It tries to have the service account sign back in, but the PS cred object is made and the arguments are valid.

Please let me know what could be done to fix this because having a service account makes doing automated account creation/exit better.

Thank you,


Solution

  • https://social.technet.microsoft.com/Forums/en-US/2b34a686-fa2b-41a7-8155-059e2b35b393/using-pscredential-object-without-a-prompt-and-connecting-to-a-remote-registry-in-powershell?forum=ITCG

    This is the link where I found out how to get the credentials to work and not be prompted again.

    It was answered by: EIG-Wes

    The issues was with the remote signature and is fixed by running this command:

    Enable-PSRemoting -Force

    Credit to that guy but F*ck the dude who downvoted me. Seriously. Write a comment if there is an issue.

    I hope that this can help someone with their IT service accounts in PS