Accessing Environment Variables in a Scheduled Task

2,915

Solution 1

You do not need a machine reboot. You should terminate Taskeng.exe and the next time scheduled task is run it will get an updated environment.

Solution 2

I thought that you could reference environment variables from the Task Scheduler, but having just tried, it doesn't look like you can.

The one exception appears to be %PATH% so would it be possible to add your MyAppPath value to the %PATH% collection on each machine, then then just call MyApp.exe from the task scheduler, where the machine will be able to resolve the fully-qualified path as required?

Solution 3

On a side note, I did think about calling a BAT file and referencing the environment variable there, but that doesn't solve anything for me as the main issue is actually knowning whether the application (and the bat file too) is on C: or D: drives - inside the drive itself the path is the same.

%~d0 will expand to the drive letter of where the batch file is located. (%~dp0 for drive+directory, and so on.)

Solution 4

tsvayer's answer didn't quite work for me, on a computer running Windows 7, but it pointed me in the right direction. Task Scheduler seems to be a service on my computer; it's name is Schedule; the display name is Task Scheduler.

Besides restarting it from the Services MMC, it can be restarted with the following wmic commands run from a Command Prompt window (with administrator privileges):

wmic service where "name='Schedule'" call StopService
wmic service where "name='Schedule'" call StartService

You can of course also restart the service using sc:

sc stop Schedule
sc start Schedule

Based on trial and error, it seems sufficient to disable and then re-enable a single task, if that's all you need to affect:

schtasks /Change /TN \"The name of the task\" /DISABLE
schtasks /Change /TN \"The name of the task\" /ENABLE
Share:
2,915

Related videos on Youtube

user1566783
Author by

user1566783

Updated on September 18, 2022

Comments

  • user1566783
    user1566783 over 1 year

    Here is my chunk of code. It compiles fine and when I fire off the event I get the email, but I then get this error Email attachment ERROR on Adobe while opening(Acrobat could not open 'Att00002.pdf' because it is either not a supported file type or because the file has been damaged(for example, it was sent as an email attachment and wasnt correctly decoded.)

    string agentName = "My Name";            
    MemoryStream _output = new MemoryStream();
                PdfReader reader = new PdfReader("/pdf/Agent/Specialist_Certificate.pdf");
                using (PdfStamper stamper = new PdfStamper(reader, _output))
                {
                    AcroFields fields = stamper.AcroFields;
                // set form fields
                fields.SetField("FIELD_AGENT_NAME", agentName);
                fields.SetField("FIELD_DATE", AvalonDate);
    
                // flatten form fields and close document
                stamper.FormFlattening = true;
                SendEmail(_output);
                DownloadAsPDF(_output);
                stamper.Close();
            }
    
    private void SendEmail(MemoryStream ms)
    {
        Attachment attach = new Attachment(ms, new System.Net.Mime.ContentType("application/pdf"));
        EmailHelper.SendEMail("[email protected]", "[email protected]", null, "", "Avalon Cert", "Hope this works", EmailHelper.EmailFormat.Html,attach);
    }
    

    EDITED *************************************

            using (MemoryStream _output = new MemoryStream())
            {
                using (PdfStamper stamper = new PdfStamper(reader, _output))
                {
                    AcroFields fields = stamper.AcroFields;
                    // set form fields
                    fields.SetField("FIELD_AGENT_NAME", agentName);
                    fields.SetField("FIELD_DATE", AvalonDate);
    
                    // flatten form fields and close document
                    stamper.FormFlattening = true;
                }
                SendEmail(_output);
            }
    
    • rhens
      rhens over 8 years
      Try closing the PdfStamper before calling SendEmail. You're probably attaching only part of the PDF bytestream because not everything is flushed to output yet.
    • user1566783
      user1566783 over 8 years
      When I change it to stamper.Close(); SendEmail(_output); I get this error when sending the email System.ObjectDisposedException: Cannot access a closed Stream
  • Paul Hadfield
    Paul Hadfield over 12 years
    Interesting, I just tried with %PATH% and could not get it to work. At that point I noticed a stupid typo when I'd updated %PATH%. I fixed the typo and verified that PATH was OK in a DOS box, but task scheduled still reported the problem - indicating it was seeing the "bad" version of %PATH%. Rebooting was needed to pick up the change (as you can't restart task scheduler). At that point it turned out I could now use my original environment variable. So the upshot is that you can use environment variablees, but a full machine reboot is needed to pick up any changes/new environment variables
  • Paul Hadfield
    Paul Hadfield over 12 years
    Will mark this as the answer as you were correct that you can use them but if task scheduler has run before you modified the job / added the reference to an environment variable, it will need a reboot of the machine.
  • Ben Challenor
    Ben Challenor over 10 years
    See tsvayer's answer - you don't need to reboot the machine. Just the task scheduler process.
  • Tim
    Tim almost 10 years
    Thank you so mcuh! I've been struggling with it for days. I've been trying to restart the Scheduler service to no avail in Win7/Win2008 (need to run as SYSTEM to restart it), but this is so much simpler!
  • Chris Haas
    Chris Haas over 8 years
    I agree with this but I'd go even further and advocate for kuujinbo's full pattern which I also always use, and that's to return a byte array instead of a stream. If you need a stream later on, just wrap the byte array with a new one. Yes, there's a couple of extra CPU cycles in there but not much really. The problem with passing streams around is exactly what UncleRico is pointing to and that's that other people can mess with them by closing them or setting positions or whatever.
  • user1566783
    user1566783 over 8 years
    Ok so where would I put my SendEmail(_output); chunk then? If I put it outside the using PdfStamper I get an error saying the stream is already closed.
  • Rick Burns
    Rick Burns over 8 years
    @user1566783 I would advocate creating your stamped pdf first and closing it using the code above as a template. Then as a secondary process attach it to your e-mail using your SendEmail() method. Remember that in one case your MemoryStream is being used to write information, your attachment process is using that same MemoryStream to read from it (not really a good thing to do).
  • user1566783
    user1566783 over 8 years
    So are you saying something like this? Since the using is closing the stamper, i send the email and then the using of the memorystream is closed as well. Or like Chris said above should I try putting it into a byte arrary and then sending it out in the attachment that way?
  • Rick Burns
    Rick Burns over 8 years
    @user1566783. I like Chris' approach, however I've had success using the memorystreams as highlighted in my answer. So either would work. My own preference would be to use two memorystreams, one for the write of the new pdf and then another for the read of the resulting combined pdf for use in your e-mail.
  • user1566783
    user1566783 over 8 years
    Ok I was able to get it up and working. Thanks guys for the help!
  • Sergey Nudnov
    Sergey Nudnov about 3 years
    You cannot run any of this commands for the Schedule service even from a privileged console
  • Kenny Evitt
    Kenny Evitt about 3 years
    @SergeyNudnov Did you test on a computer running Windows 7?
  • Sergey Nudnov
    Sergey Nudnov about 3 years
    Initially I tested on Windows Server 2012 R2. But your question is fair. I have just tested on Windows 7. sc stop Schedule from privileged console gives Access Denied
  • Kenny Evitt
    Kenny Evitt about 3 years
    @SergeyNudnov My answer is over six (6) years old. It wouldn't be surprising that even the last versions of Windows 7 might behave differently. Thanks for the updates!
  • Kenny Evitt
    Kenny Evitt about 3 years
    @SergeyNudnov On newer, or server, versions of Windows, the Task Scheduler service might have a different name. I'd think that wmic and its commands still work, but it's been a few years since I've worked with Windows servers much at all.