Search code examples
powershellwmi

Accessing Mapped Network Drive Fails In Scheduled Task


I have the following powershell script which checks a drive to see if it is low on space, and if so stops sabnzbd downloads and sends me an email:

$disk = Get-WmiObject Win32_LogicalDisk  -Filter "DeviceID='B:'" | Select-Object FreeSpace 
$gb =$disk.FreeSpace /1073741824
if($gb -lt 3)
{

    $wc = New-Object system.Net.WebClient;
    $smsResult = $wc.downloadString("http://localhost:8080/sabnzbd/api?mode=pause&apikey=XXXXXXX")
    $EmailFrom = "XXXXXXX"
    $EmailTo = "XXXXXXX" 
    $Subject = "NAS out of space <eom>" 
    $Body = "" 
    $SMTPServer = "smtp.gmail.com" 
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
    $SMTPClient.EnableSsl = $true 
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("XXXXXXX", "XXXXXXX"); 
    $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}

This works perfectly when running in powershell through the console or ISE, but when I setup a scheduled task the WMI query returns the drive size as 0. I do not get any errors and task scheduler says the task completed successfully. I run the task with elevated privileges as my administrator account. Have also tried to run as SYSTEM without any luck. I have seen other people ask similar questions a long time ago, but it does not seem like they got any answers.


Solution

  • Working off of andyb's comment I was able to fix this by mapping and unmapping the drive explicitly so that Powershell can use it.

    $net = new-object -ComObject WScript.Network
    $net.MapNetworkDrive("K:", "\\192.0.0.0\NAS", $false, "192.0.0.0\NASAdmin", "xxxxxx")
    
    $disk = Get-WmiObject Win32_LogicalDisk  -Filter "DeviceID='K:'" | Select-Object FreeSpace 
    $gb =$disk.FreeSpace /1073741824
    $gb>E:\test.txt
    
    
    if($gb -lt 3)
    {
    
        $wc = New-Object system.Net.WebClient;
        $smsResult = $wc.downloadString("http://localhost:8080/sabnzbd/api?mode=pause&apikey=xxxxxx")
        $EmailFrom = "xxxxxx"
        $EmailTo = "xxxxxx" 
        $Subject = "NAS out of space <eom>" 
        $Body = "" 
        $SMTPServer = "smtp.gmail.com" 
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
        $SMTPClient.EnableSsl = $true 
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("xxxxxx", "xxxxxx"); 
        $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
    }
    Start-Sleep 5
    $net.RemoveNetworkDrive("K:");