Prevent duplicate or hanging Powershell processes that run from the Task Scheduler

Many automated processes we write in Powershell are scheduled on a server somewhere and run periodically.
Sometimes, the script may hang. In my experience, the task scheduler setting “Stop the task if it runs longer than:” rarely works properly when a Powershell script hangs. It either thinks it stopped the task, or is unable to.

This can result in memory hogging runaway Powershell processes, locked log files, concurrent user issues, etc etc.

If you want to prevent that from happening, add this function to your script and call it once at the start of your script. It will kill any Powershell process with the same script name that does not match the running process’s Process ID. It requires Powershell 3+:


function preventDoubleSchedule{
    try{
        $scriptFileName = split-path $MyInvocation.PSCommandPath -Leaf
    }catch{$scriptFileName = $Null}
    try{
        [Array]$psProcesses = @(Get-WmiObject Win32_Process -Filter "name like '%Powershell.exe%' and handle != '$pid'" | where {$_})
    }catch{
        Throw
    }
    if($psProcesses.Count -gt 0){
        foreach($psProcess in $psProcesses){
            if($psProcess.CommandLine -like "*$scriptFileName*" -and $scriptFileName){
                ##we've found a Powershell process that is running this script, but does not have the same process ID, lets try to kill it
                try{
                    Stop-Process -Id $psProcess.Handle -Force -Confirm:$False
                }catch{
                    Throw
                }
            }
        }
    }
}

O365GroupSync v0.50 available!

Version 0.50 is out, changes:

  • fixed a bug in using the wrong smtp prefix when searching
  • removed log spam about skipped inactive accounts
  • set managedBy after creating all groups
  • extra mail parameters to allow configuration of WHEN emails are sent (e.g. only in case of errors)
  • send error mail when log file is locked
  • reconnect to ExO each caching action
  • overwrite instead of add primary smtp
  • set mailNickName and legacyExchangeDN values when creating AD group so the group isn’t invisible in the legacy exchange console

Get it here

OnedriveMapper v2.53 released!

Version 2.53 of OneDriveMapper has been released!

  • Updated to work with changes in MS’s backend
  • Better handling of AzureAD SSO Preview

This morning I received reports that the O4B mapping was failing, but SpO ones weren’t. Digging into this I noticed that if I attempted to map the moment the script hits O4B, it did work, so OnedriveMapper now handles the timing a bit different to work with the changes Microsoft made on their end.

Get the new version here

OnedriveMapper v2.51, AADConnect SSO workaround

Hi all, I’ve just posted v2.51, which has a workaround for the Preview Version of SSO in Azure AD Connect that some people have reported not working with OnedriveMapper.

It took me a while to reproduce the issue, but v2.51 now works with Azure AD Connect SSO as long as you do not configure the 2 intranet URL’s through GPO. OnedriveMapper will handle the SSO sites in your local intranet for you, and will still prompt the user for a password once and then cache it.

I’ve got a call with Microsoft to assist on why AADConnect SSO does not generate a persistent cookie, so full compatibility may come in the future.

Changelog:

  • detect and log OS and IE version, only check for relevant KB if necessary
  • semi-compatible with Azure AD Connect SSO (bypass)

Get it here

OnedriveMapper v2.50 released!

Version 2.50 of OneDriveMapper has been released!

  • Less ‘in your face’ progress display
  • timestamped logging
  • automatically prevent IE firstrun wizard from making the script hang
  • Powershell 2 friendly version check
  • also do SSO attempt at userlookupmode 1 and 2 if offered
  • Log errors if AADConnect Preview SSO is set

Get the new version here

Copy local AD contacts to O365

Recently I needed a basic method to copy over contacts from a local AD to O365, and in cases where a read-write contact already exists; update it. The scenario made sense, as we were working with multiple source AD’s where some had contacts of each other’s mail users, causing adsync conflicts. Thus we decided to take contacts out of ADsync scope and just copy them once.

The logic of the attached script is as follows:

 

 

 

 

 

 

 

 

Note that the script ONLY imports the displayname, primary and all secondary email addresses, and sets an extra X500 address for the legacy exchangeDN to avoid outlook cache hit misses.

If you need it, here’s a download link:

O365ContactImporter.ps1

Powershell v1 and v2 friendly version of Invoke-WebRequest

If you need to use the Invoke-Webrequest on machines that are still running an older Powershell version, this function will help you out.

It sets a script-wide variable called ‘cookiejar’, which will persist any cookies during subsequent calls to this function. You can add customHeaders as a hashtable if you need to. By default the function will also attempt to respond to 401 challenges with the current user credentials.


function JosL-WebRequest{
    Param(
        $url,
        $method="GET",
        $body,
        $trySSO=1,
        $customHeaders
    )
    if($script:cookiejar -eq $Null){
        $script:cookiejar = New-Object System.Net.CookieContainer     
    }
    $maxAttempts = 3
    $attempts=0
    while($true){
        $attempts++
        try{
            $retVal = @{}
            $request = [System.Net.WebRequest]::Create($url)
            $request.TimeOut = 5000
            $request.Method = $method
            if($trySSO -eq 1){
                $request.UseDefaultCredentials = $True
            }
            if($customHeaders){
                $customHeaders.Keys | % { 
                    $request.Headers[$_] = $customHeaders.Item($_)
                }
            }
            $request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E)"
            $request.ContentType = "application/x-www-form-urlencoded"
            $request.CookieContainer = $script:cookiejar
            if($method -eq "POST"){
                $body = [byte[]][char[]]$body
                $upStream = $request.GetRequestStream()
                $upStream.Write($body, 0, $body.Length)
                $upStream.Flush()
                $upStream.Close()
            }
            $response = $request.GetResponse()
            $retVal.StatusCode = $response.StatusCode
            $retVal.StatusDescription = $response.StatusDescription
            $retVal.Headers = $response.Headers
            $stream = $response.GetResponseStream()
            $streamReader = [System.IO.StreamReader]($stream)
            $retVal.Content = $streamReader.ReadToEnd()
            $streamReader.Close()
            $response.Close()
            return $retVal
        }catch{
            if($attempts -ge $maxAttempts){Throw}else{sleep -s 2}
        }
    }
}

O365GroupSync v0.43 available!

Version 0.43 is out, changes:

  • Better nesting of groups if they get created together (due to re-caching)
  • 3x faster performance during comparison of members in a full sync
  • .NET streamwriter vs Add-Content logging (to prevent missing log entries when the filesystem is slow)
  • Changed the differential switch to ‘do a differential’ instead of ‘do only a differential’
  • Added the full switch
  • Allow X500 proxy addresses to sync

Get it here

O365GroupSync v0.37 is out!

Version 0.37 is out, changes:

  • AD group selection filter
  • Automatic version check
  • Replaced Compare-Object to increase performance
  • Replaced searchExO function to increase performance loading groups from O365
  • Enhanced ExO caching (100+x faster)
  • Optionally ignore disabled accounts (parameter)
  • Categorised logging (| seperator in logfile)
  • Bugfixes

Get it here