Search code examples
powershellscheduled-tasksmapped-drive

Using PowerShell 5.1 on Windows 10, I successfully map a drive, but it doesn't when running by Scheduled Task


The below code successfully create a mapped drive on Windows 10 and 11. Running the script from Task Scheduler doesn't work. The task has been configured to run As System and I have tried the same admin account that is logged on as well. Task has been configured Windows 7 and 2008 R2 and I have tested for Windows 10. The Action in the task is PowerShell.exe -executionpolicy Bypass -file .ps1.

Thanks to anyone who can help. Amos

$networkSharePath = "\\iilansweepcl1\defaultpackageShare$\Post-Install\Patches"
$localPath = "C:\Windows\Patches\"
$publicDesktopPath = [Environment]::GetFolderPath("CommonDesktopDirectory")
$global:driveLetter = "f:"

If (-not (Test-Path -Path "${localPath}exclutions.txt"))
{
    New-Item -Path "${localPath}exclutions.txt"
}

$FilesOnShare = @{ }
$FilesLocal = @{ }

function decode_password()
{
    param (
        $enc_pass
    )
    return [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($enc_pass))
}

function Connect2PackageShare
{
    $UserName = "******admin"
    $password = ConvertTo-SecureString  "$(decode_password 'aW**********y')" -AsPlainText -Force
    $credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password

    try
    {
        net use $driveLetter $networkSharePath /user:*****admin ilishelpYOU2 /persistent:no | Out-Null  
        #New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root $networkSharePath -Scope Global -ErrorAction stop
    }
    catch
    {
        Try
        {
            net use $driveLetter $networkSharePath /user:*****admin ilishelpYOU2 /persistent:no | Out-Null
            #New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root $networkSharePath -Credential $credential -Scope Global -ErrorAction Stop
        }
        catch
        {
            exit
        }
    }
    
    $Files = Get-ChildItem -Path 'B:\'
    foreach ($File in $Files)
    {
        $LastWriteTime = $File.LastWriteTime
        $FilesOnShare[$File.Name] = $LastWriteTime
    }
    Return $FilesOnShare
} # Connect2PackageShare

function Get-LocalPostInstall
{
    $result =  Get-Item -Path $localPath
    if ($result)
    {
        $LFiles = Get-ChildItem -Path $localPath
        foreach ($Lfile in $Lfiles)
        {
            $LastWriteTime = $Lfile.LastWriteTime
            $FilesLocal[$Lfile.Name] = $LastWriteTime
        }
    }
    Return $FilesLocal
} # Get-LocalPostInstall

Connect2PackageShare

Solution

    • Mapped drives are a user-level concept, so you must fundamentally establish them in the context of the account(s) that should see them.

    • In the context of a scheduled task, you must further ensure that the task has network access, which is not the case if you run as SYSTEM or even if you run with the specific target user identity but have chosen the Run whether user is logged on or not option.

    Therefore, to make your script work:

    • Configure your task to run as the user or user group for which the mapping should be established.

      • For instance, use the Users group to establish the drive for all users.
    • Use the Run only when the user is logged on option.

      • Note that this means that the task invariably runs visibly. However, if you schedule it to run at logon, this may not be a problem.
    • Do NOT use the Run with highest privileges option (by default, elevated processes for a given user do not share drive mappings with non-elevated processes, and mapping established from an elevated processes do not persist).