powershellvpnopenvpnnetwork-drive

Automatically connect to network drives after connecting to VPN


I have several mapped network drives that I can only access when on my company's LAN or when connected to the VPN using OpenVPN.

When I connect to the network in our office, the drives automatically connect. However, when I connect via the VPN, only two of the drives automatically connect (I tried net use /persistent:yes but that didn't seem to make a difference, so maybe I'm not understanding that command).

What's odd to me is that the rest of my drives say "unavailable" as the status when I type net use. If I click on the drive in Windows Explorer, the drive status is then blank. Those drives do not display when I use get-PSDrive. Not sure if that's related to the autoconnect or not.

Any ideas for what I can do to automatically connect to my other drives?

enter image description here


Solution

  • This the solution that ended up working for me:

    I used Task Scheduler to create a task that automatically runs when I access OpenVPN. The tasks launches a .cmd file with the following code:

    @ECHO OFF
    PowerShell -Command "Set-ExecutionPolicy -Scope CurrentUser Unrestricted" >> "C:\Users\USERNAME\AppData\Local\Temp\StartupLog.txt" 2>&1
    PowerShell -File "C:\Scripts\MapDrives.ps1" 
    

    This calls the following PowerShell script.

    $start = Get-Date
    $endTime = $start.AddMinutes(3)  # Set end time 3 minutes from start
    
    $MappedDrives = Get-SmbMapping | Where-Object { $_.Status -ne "Ok" } | Select-Object LocalPath, RemotePath, Status
    
    # Function to log messages to a file
    function LogMessage {
        param(
            [string]$Message,
            [string]$Color,
            [switch]$Display=$False
        )
    
        $logFilePath = Join-Path -Path $scriptDirectory -ChildPath "mappinglog.txt"
        Add-Content -Path $logFilePath -Value $Message
        if( $Display ) {
            Write-Host $Message -ForegroundColor $Color
        }
    }
    
    # Create or append to the log file
    $scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Definition
    $logFilePath = Join-Path -Path $scriptDirectory -ChildPath "mappinglog.txt"
    if (Test-Path $logFilePath) {
        Remove-Item -Path $logFilePath 
    }
    
    New-Item -Path $logFilePath -ItemType File | Out-Null
    
    Write-Host "Reconnecting drives...." -ForegroundColor Cyan
    Write-Host "Press the CTRL+C hot key combination to cancel." -ForegroundColor Cyan
    
    while ($MappedDrives -and (Get-Date) -lt $endTime) {
        $error.clear()
        foreach ($MappedDrive in $MappedDrives) {
            if ($MappedDrive.Status -eq "Disconnected") {
                if (Test-Path $MappedDrive.LocalPath) {
                    LogMessage "Success: $($MappedDrive.LocalPath)\ reconnected to $($MappedDrive.RemotePath)" -Color Green -Display $True
                } else {
                    LogMessage "Failed: Unable to reconnect $($MappedDrive.LocalPath)\ to $($MappedDrive.RemotePath)" -Color Red
                }
            } elseif ($MappedDrive.Status -eq "Unavailable") {
                if (Test-Path $MappedDrive.RemotePath) {
                    New-SmbMapping -LocalPath $MappedDrive.LocalPath -RemotePath $MappedDrive.RemotePath -Persistent $true
                }
    
                if (Test-Path $MappedDrive.LocalPath) {
                    LogMessage "Success: $($MappedDrive.LocalPath)\ connected to $($MappedDrive.RemotePath)" -Color Green -Display $True
                } else {
                    LogMessage "Failed: Unable to connect $($MappedDrive.LocalPath)\ to $($MappedDrive.RemotePath)" -Color Red
                }
            } elseif ($MappedDrive.Status -eq "Reconnecting") {
                LogMessage "Pending: $($MappedDrive.LocalPath)\ is automatically reconnecting to $($MappedDrive.RemotePath)" -Color White -Display $True
            }
        }
        $MappedDrives = Get-SmbMapping | Where-Object { $_.Status -ne "Ok" } | Select-Object LocalPath, RemotePath, Status
    }