Question : Scheduling a PowerShell Script to run - the file is Blank

When I run a PowerShell script via Task Schedular the file that is attached is blank.  However when I "debug" via PowerGui the script runs fine.


Task Scheduler runs a .bat file:
Powershell -command "& 'C:\PowershellScripts\Directorysize\directorysize_email.ps1'"

I have another script that runs two hours before this one and it works fine as well.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
###Send Exchange folder size
 
###Varabiles - which can me modified
$FromAddress = Mailserver
$ToAddress = '[email protected]
$MessageSubject = "Exchange Folder Size Report"
$MessageBody = "Attached is the current exchange folder size."
$SendingServer = "mail.server.com"
$filename = "C:\PowershellScripts\Directorysize\foldersize-$(get-date -f MMddHHssyyyy).txt"
 
Get-PSSnapIn -Reg | Add-PSSnapin -ea 0
 
###This gets the folder size from the designated section and puts it in a text file
function Get-Size($dir=".")
{
    $ds = get-item $dir | % { $f = $_;    get-childitem -r $_.FullName | measure-object -property length -sum -ErrorAction SilentlyContinue | select @{Name="Name";Expression={$f}},Sum}
 
    $ds | foreach-object { if ( $_.Sum -le 999KB) {$_.Sum = ([string]::Format("{0:#.##}",($_.Sum)/1KB)) + " KB" ; $_ } elseif ( $_.Sum -le 999MB) {$_.Sum = ([string]::Format("{0:#.##}",($_.Sum)/1MB)) + " MB" ; $_ } elseif ( $_.Sum -le 999GB) {$_.Sum = ([string]::Format("{0:#.##}",($_.Sum)/1GB)) + " GB" ; $_ }}
 
} # End Get-Size
 
# set Alias of 'du' for Get-Size
Set-Alias du Get-Size
 
Get-Size e:\Exchange\* | out-file $filename
 
###Creates the mail message and adds the foldersize text file as an attachment
$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, 
$MessageSubject, $MessageBody
$Attachment = New-Object Net.Mail.Attachment($filename)
$SMTPMessage.Attachments.Add($Attachment)
 
###This sends the message
$SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
$SMTPClient.Send($SMTPMessage)
Open in New Window Select All

Answer : Scheduling a PowerShell Script to run - the file is Blank

I would trouble shoot like this:

1) Test in the IDE
2) Test from normal Powershell shell (this will allow you see errors)
3) Do a Runas on a Powershell shell and try again
4) Schedule Task

Another option would be to redirect the output of the script into a file by changing the bat file

Powershell -command C:\PowershellScripts\Directorysize\directorysize_email.ps1 2>&1 > error.log
Random Solutions  
 
programming4us programming4us