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

  • Therefore, to make your script work: