VBScript Runs Correctly From Command Prompt, But Not From SQL Server Agent Job

I'm trying to run this script on my local machine to do some post-batch cleanup and it doesn't run correctly from the scheduled job (or when I invoke the job).
Here's the script in question:
Option Explicit
Const filePath = "C:\Documents and Settings\jmunn\My Documents\Visual Studio 2008\Logs\"
Const holdDays = 6
main
Sub Main()
ClearArchive
End Sub
Sub ClearArchive()
Dim fso 'As Scripting.FileSystemObject
Dim fld 'As Scripting.Folder
Dim f 'As Scripting.File
Dim delLogName, delLogOut, delCtr
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(filePath)
delLogName = filePath & "Nightly Backup - Backup Logs Deleted" & ".txt"
Set delLogOut = fso.CreateTextFile(delLogName, True)
delLogOut.WriteLine(delLogName)
delLogOut.WriteLine("")
delLogOut.WriteLine("-- The following log files were deleted on " & DateValue(Now()) & " at " & TimeValue(Now()))
delLogOut.WriteLine("")
delCtr = 0
For Each f In fld.Files
If Left(f.Name, 48) = "Nightly Backup - SQL Server Databases_Subplan_1_" And Right(LCase(f.Name), 4) = ".txt" Then
If DateDiff("d", f.DateCreated, Date()) > holdDays Then
delLogOut.WriteLine(f.Name)
fso.DeleteFile f, True
delCtr = delCtr + 1
End If
End If
Next
If delCtr = 0 Then
delLogOut.WriteLine("No log files were deleted this run...")
End If
Set fld = Nothing
Set fso = Nothing
delLogOut.Close
End Sub
If I put the script in its own file and run it from the command prompt, it runs just fine. If the script runs from the SQL Server Agent job, the for-loop will delete the files correctly, but the filenames
do not get written to the deletion log file and the counter does not get incremented, so according to the job log, nothing was deleted. Why does the script run differently from each invocation? It can't be a permission thing, the service that logs in has full
access to the directory and the files do get deleted. Any ideas out there?
Between this and other outstanding issues, I'm quickly losing faith in SQL Server.  >=o(
Thanks in advance for your thoughts!
John
Version Info:
Microsoft SQL Server Management Studio      10.0.2531.0
Microsoft Analysis Services Client Tools      10.0.1600.22
Microsoft Data Access Components (MDAC)      3.85.1132
Microsoft MSXML      2.6 3.0 4.0 5.0 6.0
Microsoft Internet Explorer      8.0.6001.18702
Microsoft .NET Framework      2.0.50727.3603
Operating System      5.1.2600
"A bus station is where a bus stops. A train station is where a train stops. On my desk I have a workstation..."

Hi
jrmunn
i am trying to execute VB script to refresh my excel files.. using Vbscript file through SQL Agent job step.
i have copied VBscript in a file with the extension RefreshExcel.vbs kept in C:\RefreshExcel.vbs
Below is the script used inside the file (RefreshExcel.vbs)
//---Script code-----------------------------------------------------------------
Dim objXL, objWB
Dim FileLocation, FileName
On Error Resume Next
'lgnConn = 1
FileLocation = "F:\Reports\Reports"
Set objXL = CreateObject("Excel.Application")
objXL.DisplayAlerts = False
FileName = "ReportFile1.xlsx"
'MsgBox (FileLocation & "/" & FileName)
Set objWB = objXL.Workbooks.Open(FileLocation & "/" & FileName)
objWB.EnableConnections
objXL.CalculateUntilAsyncQueriesDone
objWB.RefreshAll
objXL.CalculateUntilAsyncQueriesDone
objWB.RefreshAll
objXL.CalculateUntilAsyncQueriesDone
objWB.Save
objWB.Close
Set objWS = Nothing
Set objWB = Nothing
objXL.Quit
Set objXL = Nothing
'MsgBox ("Refresh Completed")
---------------------------------------------------------------------------------------------------//Script complete
Now when i am trying to call this script file in SQL agent job step (as you mentioned )
as Type -cmdExec(OperatingSystem)
cscript "C:\RefreshExcel.vbs"
Issue: job step executed succesfully ,,but without performing any refresh on the excel. So i am not understandig what is going wrong. the same script file work when i am calling it through a batch file (window scheuler task). But it doesnt support
to run the file "when user is not logged in"
that is why  i want to refresh my excel file through sql agent ,which can be scheduled to any time and cab be run as SQL agent credentials.
Can you please help me on this ...i have tried all the option but nothing working .. found hope by seeing your solution.
Thanks in advance.
Please help me. :-(

Similar Messages

  • Will dynamic Excel commands in a C# Edit Script run ok as a SSISDB Package and a SQL Server Agent Job?

    I've seen some conflicting things in terms of dynamic Excel commands running in a SSISDB Package and a scheduled SQL Server Agent Job...things like that it's not supported...that it won't work...etc...
    It's a pretty simple script...to open up a .xlsx file and save it as a .xls file. I am trying to be proactive here and the reason I did it this way is because I could not source the .xlsx file and then I couldn't use OLE DB sourcing because I think the .xlsx
    file wants you to use Microsoft.ACE.OLEDB.12.0 and that entails installing the 64-bit Microsoft Access Database Engine and I cannot do that because our network version of Microsoft Office 2010 is 32-bit and in order to install the 64-bit Microsoft Access Database
    Engine 2010 it's prompting me to uninstall Microsoft Office 2010 and that is not possible.
    Ugh!
    So I'm hoping that I can promote and deploy this current SSIS Package to Production and create a SQL Server Agent Job that will successfully run this and its dynamic Excel commands.
    Do you know of any hurdles with this? Any anomalies...struggles...
    Thanks for your review and am hopeful for a reply.
    Here's the C# Script...which works perfectly client side...
    string StrFileName = (Dts.Variables["User::FileName"].Value.ToString());
    StrFileName = Path.GetFileNameWithoutExtension(StrFileName);
    string StringSourceFile = (Dts.Variables["User::FilePath"].Value.ToString()) + StrFileName + ".xlsx";
    string StringDestinationFile = (Dts.Variables["User::FilePath"].Value.ToString()) + StrFileName + ".xls";
    // This initiates the Excel Application
    Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application();
    // This Opens the Source .xlsx File from Emdeon ePaySmart
    Workbook workbook = excelApplication.Workbooks.Open(StringSourceFile, XlUpdateLinks.xlUpdateLinksNever, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    // This will Save the Source .xlsx Emdeon ePaySmart File as a .xls File...note xlFileFormat.xlExcel5
    workbook.SaveAs(StringDestinationFile, XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    // This will Close the Source
    workbook.Close(false, Type.Missing, Type.Missing);
    // This shuts down the Excel Application
    excelApplication.Quit();

    This should work if you use a proxy to run this package in the Agent; see:
    http://www.mssqltips.com/sqlservertip/2163/running-a-ssis-package-from-sql-server-agent-using-a-proxy-account/
    Arthur
    MyBlog
    Twitter

  • Query runs from command line, but not from scheduler

    We use Control-M to schedule shell scripts to be run on a Solaris server. Some of the scripts have to access an Oracle database and in that case our security team will include the DB user and password in the script, then encrypt it and the sys admin team schedules the encrypted shell script with Control-M. That works fine, but we've been trying to have the DB user and password on a separate encrypted file so that we don't have to ask for file encryption every time it's necessary to modify a script (this is a test environment).
    We have the script at ~/system_name/scripts, the query at ~/system_name/sql and the encrypted file and key at ~/system_name/keys. The SQLPlus call in the script is:
    ${ORACLE_HOME}/bin/sqlplus "`decrypt -a 3des -k ./../keys/key.3des.system -i ./../keys/login.system`"@instance_name <<EOF
    @${DIR_SQL}/TEST_QUERY.SQL
    quit
    EOF
    The security analyst has tested is successfully from command line, but when we schedule it with Control-M the job abends and we get the following in the sysout:
    + decrypt -a 3des -k ./../keys/key.3des.system -i ./../keys/login.system
    decrypt: cannot open ./../keys/key.3des.system
    decrypt: invalid key.
    + /u00/app/oracle/product/11.1.0/db_1/bin/sqlplus @instance_name
    + 0<<
    @/sistemas/hmp/system_name/sql/TEST_QUERY.SQL
    quit
    SQL*Plus: Release 11.1.0.6.0 - Production on Mon May 3 09:41:55 2010
    Copyright (c) 1982, 2007, Oracle. All rights reserved.
    SP2-0310: unable to open file "instance_name.sql"
    Enter user-name: SP2-0306: Invalid option.
    Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER|SYSASM}]
    where <logon> ::= <username>[<password>][@<connect_identifier>] [edition=valu\
    e] | /
    SP2-0306: Invalid option.
    Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER|SYSASM}]
    where <logon> ::= <username>[<password>][@<connect_identifier>] [edition=valu\
    e] | /
    Enter password:
    ERROR:
    ORA-12545: Connect failed because target host or object does not exist
    SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus
    0000000080
    Any ideas?

    Looks like the command is being split in some way - the connection to sqlplus is being made before it completes the whole string
    It appears to be seeing the @instance_name as a script to execute rather than a db to connect to.
    Is the database on the same server as the script?
    If so, try setting your environment to the correct databsae, so that you can omit the @instance_name part of the syntax and see if it helps
    Also just noticed the failure to open the decrypt script. It would appear uyou are not using a full path name. Have you checked which directroy the scheduled job starts in? You may need to look at running some environment specific scripts first.
    Edited by: LindaA on 05-May-2010 07:43

  • Processbuilder works from command line but not on deployment server

    I need to deploy my code on a 10g oc4j Oracle server. When I ssh into the server and run the following code, it works:
    import java.util.*;
    import java.io.*;
    public class Launcher {
    public static void main(String args[]) throws IOException {
    String url = "http://www.ebay.com";
    String[] commands = {"/bin/sh", "-c", "/opt/sfw/bin/firefox ", url, "-width", "1600", "-height", "1200", ":5"};
    ProcessBuilder pb = new ProcessBuilder(commands);
    env.put( "DISPLAY", ":5" );
    Process process = pb.start();
    It launches firefox and I can see the process running when I use "ps -ef | grep firefox". Firefox runs in a virtual frame buffer since this is a headless server. Originally I had problems just getting this code working by itself, but now it works fine.
    However when I deploy the exact same code via Oracle application server, it doesn't do anything. Not only do no processes show up but I have added different output statements into this code and have verified that firefox never launches. However no error is ever thrown either, even when I just test for generic Exceptions. So any ideas on what I can do to get this running?

    Caffeine0001 wrote:
    sabre150 wrote:
    Solerous wrote:
    Also, I do handle the stdIn and stdOut in the code. I was trying to pair down the code in my inclusion of it here to just give the bear minimum for running it. Here is my code for handling it if you'd like to see it:
    InputStream is = process.getInputStream();
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line;
         System.out.printf("Output of running %s is:",
         Arrays.toString(commands));
         while ((line = br.readLine()) != null) {
         System.out.println(line);
         }I don't see stderr being handled and your command array is still wrong.
    Edited by: sabre150 on Dec 10, 2008 4:48 PM
    If he were to call [ProcessBuilder.redirectErrorStream(true)|http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html#redirectErrorStream(boolean)] then all he has to handle is stdout.
    True, then that would be just one more important thing that the OP failed to post in his "*exact* same code" .

  • We wanted to perform backup from command prompt but we want

    OS: :Linux
    DB version: 10.2
    I am doing weekly hot backup.
    I used rman for my backup.
    No issue on backup.
    I just ran the backup succesufully (on 070307).
    But Enterprise Manager is not updated.
    Its still showing last backup performed on 07 Nov 2006.
    But from command prompt by using rman its showing current backup (on 070307).
    I think EM shown backup status only
    if user used EM to perform backup.
    Is it correct?
    If yes how to fix this issue, we wanted to perform backup from command prompt but we want backup status should be updated in the EM simultaneously.
    D

    Hi,
    Within EM it is assumed that a control file backup will take place unless you specifically ask it to perform through a recovery catalog. I can't remember at the moment how to do this as I am at home but when you go into the admin/maintenance side of EM there will be an option to chose recvoery catalog. However saying that, EM should still report back even if a control file backup has been carried out.
    also i think if you are using a comand prompt then EM will not know about it. You will have to define the job from EM for it to register.
    rgds
    alan

  • Couldn't find the adequate forum.  I run win 8.1 and the adobe acrobat dc ap on my computer edoesn't acess the doc  cloud.  I can´t turn the mobile link on.  I can acess the clud from my browser, but not from the desktop ap.  I can acess from my mobile ap

    couldn't find the adequate forum.  I run win 8.1 and the adobe acrobat dc app on my computer doesn't access the doc  cloud.  I can´t turn the mobile link on.  I can access the cloud from my browser, but not from the desktop app.  I can access from my mobile app.

    Can you please post a screenshot of your Acrobat DC when launched, without opening a PDF?
    Thanks,
    -Amboo

  • HP officejet Pro 8100 will print from an Iphone but not from my windows laptop

    HP officejet Pro 8100 will print from an Iphone but not from my windows laptop. I get an error stating "unable to communicate with printer"

    Hi Melatina66,
    Welcome to the HP Support forums.  I understand that when trying to print from your laptop that you get a communication error message.
    To better assist you, would you please provide some further information:
    1)       How is the printer connected (USB cable, ethernet or wireless)?
    2)      When you installed the printer on your laptop did you set it up with a USB cable?  If  yes, did you switch the connection type on the laptop from USB cable to ethernet/wireless?
    3)      What version of Windows operating system are you running on the laptop (Windows XP, Windows Vista, Windows 7, or Windows 8, etc)?
    4)      When printing from your iPhone are you using Apple's AirPrint or HP's ePrint app?
    Thank you.
    Regards,
    Happytohelp01
    Please click on the Thumbs Up on the right to say “Thanks” for helping!
    Please click “Accept as Solution ” on the post that solves your issue to help others find the solution.
    I work on behalf of HP

  • Delete emails from iPhone 5 but not from server?

    How do I delete emails from iPhone 5 but not from server?

    If its a POP account try this:
    Go to Settings>Mail, Contacts and Calendars
    Tap on your mail account
    Scroll to the bottom
    Tap on Advanced
    Tap on "Delete from server" and set it to "Never"

  • How can I delete some music from my iCloud but not from my iTunes in my computer? please??

    how can I delete some music from my iCloud but not from my iTunes in my computer? please??

    iCloud doesn't store your music.

  • How can I set Firefox 8.0 to accept 3rd party cookies ONLY from selected sites but NOT from any other sites?

    I do not like to accumulate 3rd party cookies and would simply not check the Accept 3rd Party Cookies box in Preferences. BUT in order to use my bank's web page I have to accept 3rd party cookies from a separate site that manages some of their transactions (like paying bills). This means I have to accept 3rd party cookies and then delete them by hand OR I have to check the accept box each time I use the bank's website and then uncheck it when I am done.

    Thanks, but that is not what I was trying to do. I do not want to block cookies from a single site. I do not want to block all 3rd party cookies.
    What I want to do is ACCEPT 3rd party cookies only from ONE site but NOT from any other site.

  • I have an iPad mini and an iPad 2. I can print email to my HP 6510 from the mini, but NOT from the iPad 2. Both are on the same wi-fi network. I have tried everything I can do including unplugging everything, restarting, etc.  Can anyone help?

    I have an iPad mini and an iPad 2. I can print email to my HP 6510 from the mini, but NOT from the iPad 2. Both are on the same wi-fi network. I have tried everything I can do including unplugging everything, restarting, etc.  Can anyone help?

    Thanks so much! My grandaughters played games on the iPad over Xmas and one of their moms said shed restricted their access! Guess they forgot to enable again. Thank you again! Karla

  • Using QuickTime Pro with an .mpg movie, why can I only get it to play from the beginning, but not from any other point in the video?

    Using QuickTime Pro with an .mpg movie, why can I only get it to play from the beginning, but not from any other point in the video? How can I fix this?
    Baffled in SB

    What format of MPG is this?  Is this an MPEG1 or MPEG2 video?  How was the video created?

  • My music has disappeared from my computer but not from my ipad...how do i transfer it back

    my music has disappeared from my computer but not from my ipad...how do i transfer it back

    Use a third party PC/Mac music transfer application like Senuti.

  • How do I download a home DVD video disk (-R) to iMovie where I can then edit?  I can download from a camera, but not from the disk.

    How do I download a home DVD video disk (-R) to iMovie where I can then edit?  I can download from a camera, but not from the disk.

    iPhoto pulls off new videos from my iPhone 5 just fine.  Does iPhoto automatically come up when you connect your iPhone?  If it does, you should see your iPhone under "Devices" in iPhoto and then can select the videos to transfer (select, then Import Selected), though that should happen automatically.

  • I can print from my iPhone but not from my iPad

    I Can print from my iPhone, but not from my iPad.  The options
    select a printer and number of copies are active.  The print
    button is not active ( hot ).

    Try this  - Reset the iPad by holding down on the Sleep and Home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider - let go of the buttons. (This is equivalent to rebooting your computer.) No data/files will be erased. http://support.apple.com/kb/ht1430
    AirPrint Setup and Troubleshooting
    http://www.apple.com/support/ipad/assistant/airprint/
    How to print from your new iPad using AirPrint
    http://www.imore.com/print-ipad-airprint
    AirPrint Basics
    http://support.apple.com/kb/ht4356
     Cheers, Tom

Maybe you are looking for

  • MODEL clause to process a comma separated string

    Hi, I'm trying to parse a comma separated string using SQL so that it will return the parsed values as rows; eg. 'ABC,DEF GHI,JKL' would return 3 rows; 'ABC' 'DEF GHI' 'JKL' I'm thinking that I could possibily use the MODEL clause combined with REGUL

  • How can you get an Embedded Quicktime to rewind?

    Hi there, I have been using the QTPro feature of 'Export to desktop' to create a quicktime for my web site. It works well but I was just wondering if there is a way to get the quicktime to rewind to the start after it has finished the movie and rever

  • How to put Blu Ray Dvds to Kindle Fire HD

    I'd like to transfer my Blu Ray Dvds to my Kindle Fire HD. However, while I have had no problems with the original disks, the files play fine on my device, but everything I converted has the same error message: "video cannot be played". What is the p

  • How to see SPACES/network of two macs

    I read that we can activate (see?) spaces with F8. I have a MAC BOOK so I think FN and F8. But when i press nothing happens. i am not sure I understand this. I never used shortcuts before so maybe I am missing something. Another thing. I have two Mac

  • Best way to handle session timeout

    Hello All, oracle 11g, Apex ver 3.1.2 I am bit confused about the sessoin handling mecahnism for the users . Which is the best way to handle session for the users is it programatically or by DBA admin level. What are the pros and cons going DBA Level