在计划任务中访问映射的网络驱动器失败

时间:2014-03-15 02:52:02

标签: powershell wmi

我有以下powershell脚本检查驱动器是否空间不足,如果是这样,则停止sabnzbd下载并向我发送电子邮件:

$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)
}

当通过控制台或ISE在powershell中运行时,这非常有效,但是当我设置计划任务时,WMI查询将驱动器大小返回为0.我没有收到任何错误,任务调度程序表示任务已成功完成。我以提升的权限运行任务作为我的管理员帐户。也试过运行SYSTEM没有任何运气。很久以前我见过其他人问过类似的问题,但似乎没有得到任何答案。

1 个答案:

答案 0 :(得分:0)

使用andyb的评论我能够通过显式映射和取消映射驱动器来解决这个问题,以便Powershell可以使用它。

$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:");