Suggestions for how to execute file maintenance in SQL Agent Job

I need to create a SQL Agent Job (it has to be a SQL agent job) to zip all files in a directory, delete all files in the directory but the zip file and then copy the zip file to another location across a UNC path. What are some suggestions for getting
this done? 
Thanks.

This is about a previous topic ...
"1. Please close your preview thread by marking the answers that you got and not your own summary. Actualy you can mark your summary as well if you feel that this close the thread but yet, this is a summary of the answers that you got! People
that help you Invested time to help you. Feel free to
not be lazy and start you can start voting helpful responses as well :-)"
How do you mark useful answers? I have not seen how to do that.
On the left of each response you have an icon (small image).
I have asked lots of questions on the TechNet and other forums. (One day I hope to even answer some.) That was the first time I had ever marked my own as the answer. Honestly, I did not use any of those well meaning replies and did not feel that any of them
answered my question. When researching a topic I, like most people, I look at the marked answer first and assume it is the answer. Did not feel that  any of them were the answer. There is a great push on this forum to mark the answer and there are droves
of people clamoring for points (BTW - you are not one of them). I review each of my questions, always follow up on any  replies, post my solution if appropriate, and always try to close the topic. But this one was not answered.
OK, that is logic, If you dont think that you use other response as part of the answer. In my opinion (and you dont have to get it) if an answer is build from 3 responses together then we need to mark all the three (and mentioned in the summery what we have
done). If you find that those response cant be called "answer" since they do not cover enough then maybe your call was correct.
Please close the thread in the way that you feel is OK :-)
(you dont have to accept my opinion since you have your explanation, but i do think that some of the responses there are answers).
[Personal Site] [Blog] [Facebook]

Similar Messages

  • How to Run SSIS Package through SQL AGENT Job

    I am good with SSIS, I created a package which will load the excel files to SQL SERVER  tables. To Implement this I wrote the C# code to extract the first sheet name only, and then
    package will load the data present the first sheet only. The package working fine when i run this through BIDS. But the same package throwing error at C# code step when i am running this package through SQL AGENT JOB. When i searched for this, i have seen
    many posts saying that, this is happening becoz of using Microsoft.interop.excel references inside the c# code. Please help me with this. Is there any alternate way in c# to extract the first sheet name(not based on ascending order) of an excel file with out
    using interop. Or
    How to configure SQL AGENT job to run suceessfully when using interop inside the code.
    My UAT server is of 64 bit. And i have to run this in the same server.
    I tried creating  "Desktop" folder in "C:\Windows\System32\config\systemprofile\"
    Error:Description: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.     at ST_ecfa668f250a45e18c95639c9ffd64d4.csproj.ScriptMain.Main()
        --- End of inner exception stack trace ---     at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)    
    at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr,
    Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)     at
    System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)     at System.Type.InvokeMember(String name, BindingFlags
    invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)     at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()  End Error  Error: 2015-02-27 11:24:00.23     Code: 0x00000001
        Source: User Mail      Description: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error
    occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could
    not open a connection to SQL Server)     at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)     at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
        at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)
        at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)     at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String
    host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)     at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString
    connectionOptions, String newPassword, Boolean redirectedUserInstance)     at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword,
    SqlConnection owningObject, Boolean redirectedUserInstance)     at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)  
      at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)     at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owning...
     The package execution fa...  The step failed
    using System;
    using System.Data;
    using System.Diagnostics;
    using Microsoft.SqlServer.Dts.Runtime;
    using System.Windows.Forms;
    using System.Data.OleDb;
    using Microsoft.Office.Interop;
    using System.Runtime.InteropServices;
    namespace ST_ecfa668f250a45e18c95639c9ffd64d4.csproj
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    #region VSTA generated code
    enum ScriptResults
    Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
    Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    #endregion
    public void Main()
    { /*Passing the file path via User::File_Name Variable*/
    string FileName = Dts.Variables["User::File_Name"].Value.ToString();
    Microsoft.Office.Interop.Excel.Application xlApp = null;
    Microsoft.Office.Interop.Excel.Workbook excelBook = null;
    try
    xlApp = new Microsoft.Office.Interop.Excel.Application();
    excelBook = xlApp.Workbooks.Open(FileName, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing);
    string[] excelSheets = new string[excelBook.Worksheets.Count];
    int i = 0;
    foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in excelBook.Worksheets)
    excelSheets[i] = wSheet.Name;
    i++;
    Dts.Variables["User::WorkSheetName"].Value = excelSheets[0] + "$";
    catch (Exception ex)
    excelBook.Close(false, FileName, null);
    Marshal.ReleaseComObject(excelBook);
    string error = ex.Message;
    finally
    excelBook.Close(false, FileName, null);
    Marshal.ReleaseComObject(excelBook);
    Dts.TaskResult = (int)ScriptResults.Success;

    I installed office in my machine...but this doesn't solved my problem...
    Finally i figured out the solution for this and it is working now, Here is the solution...!
    Create the folder with name "Desktop" inside the below mentioned path
    C:\Windows\SysWOW64\config\systemprofile\   
    But i really don't understand the logic behind this. Can someone explain it pls....

  • Suggestions for how I can get the new purchases currently trapped on my iPod transferred to iTunes?

    I recently bought an iPod touch and had no trouble loading all the existing music I have in iTunes to my new iPod.  The problem is that no matter what I try I cannot transfer purchases I made on the new iPod into iTunes.  Every time I try, "Transfer Purchases" is greyed out.  As a result the seven tracks that I bought on the iPod are trapped on the device.  I can't get them into iTunes.  Does anyone have any suggestions for how I can get the seven new purchases currently trapped on my iPod transferred to iTunes?
    I've tried suggestions from multiple support forums, and nothing has worked.  Does anyone know why "Transfer Purchases" would be greyed out and how I can fix it so I can get the music purchases from the device to the computer.  Before anyone asks, this has not happened with any other Apple device I have owned, including my iPhone 4 8GB, iPod Touch 2nd Gen 32GB, iPad 1st Gen 64GB, and iPad 2 64GB.  Why is it suddenly happening now?
    My new iPod is an iPod Touch 5th generation 64GB  using iOS 7.1.2, and iTunes is version 11.
    I've never had this problem before.  It's driving me nuts.  Any help is very much appreciated.

    Does iTunes see the iPod?
    Is the computer authorized for the account that purchased the items?
    iTunes Store: Authorize or deauthorize your Mac or PC

  • Any suggestions for how to download missing artwork?

    Any suggestions for how to download missing album artwork? 

    Tried to do that, but didn't get anywhere.  Downloaded Album Artwork Assistant, but kept getting message that nothing appropriate was selected in iTunes. 

  • When I open my newsstand, it only stay open for a second then shuts down.  It started after I updated my software to 6.0. Any suggestions for how to fix this?

    When I open newsstand it only stays open for 1 second then shuts down.  This started happening after I upgraded to 6.0. Any suggestions for how to fix this?

    Try quitting Newsstand completely - double tap home button, delete it from the multitasking shelf - then launch it again.

  • How to Create a SQL Agent Job For A SSIS Package with Sql Server Authentication

    Hi ALl,
    I have a SSIS package which basically has a data flow task in which i pull the data from one server and copy it into another server and my source server is the one where i dont have windows authentication and i have to only use a sql server authentication
    . This package runs fine if i click the server connection properties type the password and save it.
    Now, my task is to set up a sql agent job which basically uses a proxy account and takes this package from the file system and runs it.But when i try to run this package, its failing with an error saying 
    "Login Failed For rpt5user" where rpt5user is the username for my sql server authentication of the source connection.
    Can someone please help me with any suggestions on how to do this?
    I have heard that we can achieve it by using xml config file which i have never used and i am trying to google around but for no luck.
    So, If someone can please throw any suggestions or ideas on this it would be great.
    Thanks

    You need to add password as a config item and set it from the file source or sql table
    see this as an example
    http://blogs.msdn.com/b/runeetv/archive/2009/12/22/ssis-package-using-sql-authentication-and-dontsavesensitive-as-protectionlevel.aspx
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • SSIS ETL does not pick the file from Share point when it execute through SQL Agent job

    I have created one SSIS packages, which pick the file from the Share point document library. its work successfully, once it execute through the VS project application. 
    But when i create a job in SQL Server Agent for this package then it does not pick the file and job getting fail. 
    Just for more update, SQL Server has been install in Cluster mode and using BIDS 2012 with SQl Server 2012.

    Hi PriyankGupta,
    SQL Server Integration Services is not cluster awareness, and does not support failover from one cluster node to another. So, in your clustered environment, make sure SSIS is installed on each node in the cluster. In other word, SSIS must be installed on
    the server where the SQL Server Agent job is created. 
    If you use any third party task/component or drivers, make sure they are installed on the SQL Server Agent job server. Besides, also pay attention to the protection level of the package as well as 32-bit or 64-bit runtime mode of the package. For more information,
    please see:
    http://social.technet.microsoft.com/Forums/systemcenter/en-US/e13c137c-1535-4475-8c2f-c7e6e7d125fc/how-do-i-troubleshoot-ssis-packages-failed-execution-in-a-sql-agent-job 
    If the issue persists, please post the error message in the job history for further analysis.
    Regards,
    Mike Yin
    TechNet Community Support

  • SQL Agent Job failing - not using credentials in the config file for Data source

    Hi
    We have an SSIS pkg, that is secheduled as SQL Agent job using proxy account. The pkg contanins data source for connecting different SQL servers and the proxy account do not have access to the external DBs. The data source credentials are stored in the Config
    file.
    Why the job is not using the credentials in the config file and try to use the proxy account and failing.
    Do the proxy account need access to all the external dbs in the pkg, and then what is the purpose of the config file.
    I am sorry, i am not SSIS person trying to understand. If any one can explain tha will be great!!
    Thank you!
    VR

    Please take a look at these URLs:
    Schedule a Package by using SQL Server Agent
    SSIS package does not run when called from a SQL Server Agent job step
    Cheers,
    Saeid Hasani
    Database Consultant
    Please feel free to contact me at [email protected] as well as on Twitter and Facebook.
    [My Writings on TechNet Wiki] [T-SQL Blog] [Curah!]
    [Twitter] [Facebook] [Email]

  • How can I edit the Alert Description for a SQL Agent Job monitor, specifically Job Duration.

    I'm setting up some sql agent job monitoring, I need to monitor for Job Duration. 
    This is easy enough, I just create the overrides and set the parameters and it alerts as expected, however there is no alert text. The alert does me no good with out an alert description. How can I change this?
    Paul Arbogast

    Paul
    It is not an easy way for your just copy that monitor and modify it. If you has interest, you may use MP2XMLDumper tool to export SQL server monitoring MP , modify relate moniotr and import it into SCOM.
    You can download  MP2XMLDumper tool  from
    http://blogs.technet.com/b/cliveeastwood/archive/2007/08/22/mp2xmldumper-version-2-0-export-opsmgr-mp-s-to-xml-using-mp-name-export-criteria.aspx 
    Roger

  • Getting Error while trying to execute SSIS package through sql agent

    Hi,
    I have created a package in SSIS 2008.
    I have created sql Agent job which runs perfectly on my Pc.
    I tried to create anew job on another pc which doesnot have SSIS.
    When i tried to run the Job,
     i am getting folowing error:
    Executed as user: LT-MAGFIH$. tion. End Error DTExec: The package execution returned DTSER_FAILURE (1). Started: 8:51:31 PM Finished: 8:51:35 PM Elapsed: 4.024 seconds. The package execution failed. The step failed.
    Please let me now how can i solve.

    Hi AjayChigurupati,
    I would suggest you check you are install or use the dtexec utility correctly:
    On a 64-bit computer, Integration Services installs a 64-bit version of the
    dtexec utility (dtexec.exe). If you have to run certain packages in 32-bit mode, you will have to install the 32-bit version of the
    dtexec utility. To install the 32-bit version of the
    dtexec utility, you must select either Client Tools or Business Intelligence Development Studio during setup.
    By default, a 64-bit computer that has both the 64-bit and 32-bit versions of an Integration Services command prompt utility installed will run the 32-bit version at the command prompt. The 32-bit version runs because the directory path for the 32-bit
    version appears in the PATH environment variable before the directory path for the 64-bit version. (Typically, the 32-bit directory path is
    <drive>:\Program Files(x86)\Microsoft SQL Server\100\DTS\Binn, while the 64-bit directory path is
    <drive>:\Program Files\Microsoft SQL Server\100\DTS\Binn.)
    For detail information, please see:
    http://technet.microsoft.com/en-us/library/ms162810(v=sql.105).aspx
    To using SQL Server Agent to Run a Package, please refer to the steps in th article below:
    http://technet.microsoft.com/en-us/library/ms138023(v=sql.105).aspx
    If you have any feedback on our support, please click
    here. 
    Elvis Long
    TechNet Community Support

  • Errors running SQL Agent Jobs for 64 bit SSIS packages on a 64 bit server, but Source server 32 bit

    Hi,
    I can able ran the SSIS package in BIDS, since set to false in Run64BitRuntime property.
    Then I created SQL server Agent job I tried the following ways
    Step 1:
    Type is set as SQL Server Integration Services Packages,
    Run as - SQL Server Agent Service Account
    Package source - FileSystem
    then Execution option tab I selected 32 bit runtime
    and then run the job I am getting the below error
    Message
    Executed as user: CIT\svc_CS_SS2008Agent. Microsoft (R) SQL Server Execute Package Utility  Version 11.0.2100.60 for 32-bit  Copyright (C) Microsoft Corporation. All rights reserved.    Started:  7:29:17 AM  Error: 2013-11-28
    07:29:18.57     Code: 0xC0014020     Source: Example Connection manager "DataSource.DataExtract"     Description: An ODBC error -1 has occurred.  End Error  Error: 2013-11-28 07:29:18.57    
    Code: 0xC0014009     Source: Imports20_OAC_Gifts Connection manager "DataSource.DataExtract"     Description: There was an error trying to establish an Open Database Connectivity (ODBC) connection with the
    database server.  End Error  Error: 2013-11-28 07:29:18.59     Code: 0x0000020F     Source: DFT_Example ODBC_SRC Example [11]     Description: The AcquireConnection method call to the connection
    manager DataSource.DataExtract failed with error code 0xC0014009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.  End Error  Error: 2013-11-28 07:29:18.59    
    Code: 0xC0047017     Source: DFT_Example SSIS.Pipeline     Description: ODBC_SRC Example failed validation and returned error code 0x80004005.  End Error  Error: 2013-11-2
    Step 2:
    Type - Operating sytem (CmdExec)
    Run as - Sql Server agent service account
    Command - C:\Program Files\Microsoft SQL Server\110\DTS\Binn\dtexec.exe /FILE "D:\Example\Example.dtsx" /x86  /CHECKPOINTING OFF /REPORTING E
    then run the job I am getting the below error
    Message
    Executed as user: MIS\svc_CS_SS2008Agent. Microsoft (R) SQL Server Execute Package Utility  Version 11.0.2100.60 for 64-bit  Copyright (C) Microsoft Corporation. All rights reserved.    Started:  6:37:58 AM  Error: 2013-11-28
    06:37:58.94     Code: 0xC0014020     Source: Example Connection manager "DataSource.DataExtract"     Description: An ODBC error -1 has occurred.  End Error  Error: 2013-11-28 06:37:58.96    
    Code: 0xC0014009     Source: Example Connection manager "DataSource.DataExtract"     Description: There was an error trying to establish an Open Database Connectivity (ODBC) connection with the database server. 
    End Error  Error: 2013-11-28 06:37:59.01     Code: 0x0000020F     Source: DFT_Example ODBC_SRC Example [11]     Description: The AcquireConnection method call to the connection manager DataSource.DataExtract
    failed with error code 0xC0014009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.  End Error  Error: 2013-11-28 06:37:59.07     Code: 0xC0047017    
    Source: DFT_Example SSIS.Pipeline     Description: ODBC_SRC Example failed validation and returned error code 0x80004005.  End Error  Error: 2013-11-28 06:37:59.12     Code: 0xC004700C    
    Source: DFT_Example SSIS.Pipeline     Description: One or more component failed validation.  End Error  Error: 2013-11-28 06:37:59.16     Code: 0xC0024107     Source: DFT_Example     
    Description: There were errors during task validation.  End Error  DTExec: The package execution returned DTSER_FAILURE (1).Started:  6:37:58 AM  Finished: 6:37:59 AM  Elapsed:  1.373 seconds.  Process Exit Code 1. 
    The step failed.
    Note:
    My source server is 32 bit and development environment in 64 bit
    if anybody have idea please share your knowledge

    Hi BIRam,
    Based on the current information, the issue may be caused by the factor that the SQL Server Agent Service Account doesn’t have access to the MySQL server. Try to create a SQL Server Agent Proxy account that has sufficient permission on the MySQL server.
    In addition, also pay attention to the package protection level setting.
    For more information, please see:
    http://social.technet.microsoft.com/Forums/sqlserver/en-US/e13c137c-1535-4475-8c2f-c7e6e7d125fc/how-do-i-troubleshoot-ssis-packages-failed-execution-in-a-sql-agent-job?forum=sqlintegrationservices.   
    Regards,
    Mike Yin
    TechNet Community Support

  • Using Powershell to execute DBCC CheckDB from SQL Agent.

    So, I have a weird situation that I think is tied tot he resource group and powershell, but I am having trouble determining if it is that or not. I run DBCC CheckDB using a resource pool and a secondary account. The account has permissions to do the work
    and if I log onto the server and run the procedure locally it runs fine in the resource pool configuration. However, when I kick it from the SQL Agent job using the powershell step, it only does checkDB on the first 3 system databases and then stops once it
    hits a user database. I am not seeing any errors or messages, it just stops. I ran profiler and I see it do the work, get to the first user database, issues this statement from DBCC, then just stops, and the job ends.
    SELECT @BlobEater = CheckIndex (ROWSET_COLUMN_FACT_BLOB)
    FROM { IRowset 0xD0936A7902000000 }
    GROUP BY ROWSET_COLUMN_FACT_KEY
    >> WITH ORDER BY
      ROWSET_COLUMN_FACT_KEY,
      ROWSET_COLUMN_SLOT_ID,
      ROWSET_COLUMN_COMBINED_ID,
      ROWSET_COLUMN_FACT_BLOB
    OPTION (ORDER GROUP)
     I am not doing anything special in my code that would limit which databases to process. As I said earlier, executing the call to the procedure from a query window runs as expected and processes all of the databases.
    Here is the Agent Code calling powershell:
    [string] $DayOfWeek = ""
    $DayOfWeek = (get-date).DayOfWeek.ToString()
    $DayOfWeek
    if ($DayOfWeek -eq 'Sunday')
    invoke-sqlcmd -database sysadm -serverinstance HQIOSQLDEV01\DEV01 "exec ConsistencyCheck.upConsistencyCheck NULL, 'N', 'Y', 'N', 'N', 'N'"
    else
    invoke-sqlcmd -database sysadm -serverinstance HQIOSQLDEV01\DEV01 "exec ConsistencyCheck.upConsistencyCheck NULL, 'Y', 'N', 'N', 'N', 'N'"
    John M. Couch

    There are 3 additional databases. The last known good is today as I am able to execute the procedure via query window just fine. It is only when executed from a SQL Agent job as above that it stops after only doing the System Databases. The largest database
    is 130GB in size, with the largest table being 62 GB.
    -- Create Procedures
    raiserror('Creating Procedure ''%s''', 0, 1, '[ConsistencyCheck].[upConsistencyCheck]')
    go
    /*==============================================================================
    Procedure: upConsistencyCheck
    Schema: ConsistencyCheck
    Database: SysAdm
    Owner: dbo
    Application: dbo
    Inputs: Catalogue : nvarchar(128) : NULL = All Databases
    Physical Only : nchar(1) : Y/N, NULL = N
    Data Purity : nchar(1) : Y/N, NULL = N
    No Index : nchar(1) : Y/N, NULL = N
    Extended Logical Checks : nchar(1) : Y/N, NULL = N
    Table Lock : nchar(1) : Y/N, NULL = N
    Outputs: (0 = Success, !=0 = failure)
    Result Set: N/A
    Usage: declare @ii_Rc int
    ,@invc_Catalogue nvarchar(128)
    ,@inc_PhysicalOnly nchar(1)
    ,@inc_DataPurity nchar(1)
    ,@inc_NoIndex nchar(1)
    ,@inc_ExtendedLogicalChecks nchar(1)
    ,@inc_TabLock nchar(1)
    select @invc_Catalogue = NULL
    ,@inc_PhysicalOnly = 'Y'
    ,@inc_DataPurity = 'N'
    ,@inc_NoIndex = 'N'
    ,@inc_ExtendedLogicalChecks = 'N'
    ,@inc_TabLock = 'N'
    exec @ii_Rc = ConsistencyCheck.upConsistencyCheck @invc_Catalogue
    , @inc_PhysicalOnly
    , @inc_DataPurity
    , @inc_NoIndex
    , @inc_ExtendedLogicalChecks
    , @inc_TabLock
    print 'Return Code: ' + convert(varchar, @ii_Rc)
    Description: This Procedure is used to run DBCC CheckDB on 1 or all Databases
    on the existing instance.
    Version: 1.00.00
    Compatability: SQL Server 2008 (100)
    Created By: John M. Couch
    Created On: 04-26-2012
    ================================================================================
    Notes
    1. Some logic was taken directly from Ola Hallengren's Maintenance Script.
    http://ola.hallengren.com
    ================================================================================
    History: (Format)
    When Who Version Code Tag What
    04-26-2012 John Couch 1.00.00 (None) Initial Revision
    ==============================================================================*/
    alter procedure ConsistencyCheck.upConsistencyCheck (@invc_Catalogue nvarchar(128)
    ,@inc_PhysicalOnly nchar(1)
    ,@inc_DataPurity nchar(1)
    ,@inc_NoIndex nchar(1)
    ,@inc_ExtendedLogicalChecks nchar(1)
    ,@inc_TabLock nchar(1)) as
    /*==============================================================================
    Variable Declarations & Temporary Tables
    ==============================================================================*/
    declare @li_Rc int = 0
    ,@lnvc_ExecutedBy nvarchar(128) = user_name()
    ,@ldt_ExecutedOn datetime = getdate()
    ,@lnvc_Catalogue nvarchar(128) = @invc_Catalogue
    ,@lnc_PhysicalOnly nchar(1) = coalesce(@inc_PhysicalOnly, 'N')
    ,@lnc_DataPurity nchar(1) = coalesce(@inc_DataPurity, 'N')
    ,@lnc_NoIndex nchar(1) = coalesce(@inc_NoIndex, 'N')
    ,@lnc_ExtendedLogicalChecks nchar(1) = coalesce(@inc_ExtendedLogicalChecks, 'N')
    ,@lnc_TabLock nchar(1) = coalesce(@inc_TabLock, 'N')
    ,@lnvc_Instance nvarchar(128) = cast(serverproperty('ServerName') as nvarchar)
    ,@lnvc_Version nvarchar(40) = cast(serverproperty('ProductVersion') as nvarchar)
    ,@lnvc_Edition nvarchar(40) = cast(serverproperty('Edition') as nvarchar)
    ,@li_Compatibility int
    ,@ldt_CreateDate datetime
    ,@lnvc_UserAccess nvarchar(35)
    ,@lnvc_StateDescription nvarchar(35)
    ,@lnvc_PageVerifyOption nvarchar(35)
    ,@lti_IsReadOnly tinyint
    ,@lti_IsInStandBy tinyint
    ,@lnvc_Recipients nvarchar(2000) = '[email protected]'
    ,@lnvc_Subject nvarchar(128)
    ,@lnvc_ErrorMessage nvarchar(4000)
    ,@lnvc_SQL nvarchar(max)
    ,@lnvc_ManualSQL nvarchar(max)
    ,@lnvc_Query nvarchar(2048)
    ,@li_ConsistencyCheckID int
    ,@ldt_ExecutionStart datetime
    ,@ldt_ExecutionFinish datetime
    declare @ltbl_Catalogue table (Catalogue sysname
    ,CompatibilityLevel int
    ,CreateDate datetime
    ,UserAccess nvarchar(35) -- MULTI_USER, SINGLE_USER, RESTRICTED_USER
    ,StateDescription nvarchar(35) -- ONLINE, RESTORING, RECOVERING, RECOVERY_PENDING, SUSPECT, EMERGENCY, OFFLINE
    ,PageVerifyOption nvarchar(35) -- NONE, TORN_PAGE_DETECTION, CHECKSUM
    ,IsReadOnly tinyint
    ,IsInStandBy tinyint
    ,IsAutoShrink tinyint
    ,IsAutoClose tinyint
    ,Flag bit default 0)
    create table #ltbl_Output (Error int,
    Level int,
    State int,
    MessageText nvarchar(max),
    RepairLevel nvarchar(30),
    Status int,
    DBID smallint,
    ObjectID int,
    IndexID smallint,
    PartitionID bigint,
    AllocunitID bigint,
    [File] int,
    Page int,
    Slot int,
    RefFile int,
    RefPage int,
    RefSlot int,
    Allocation int)
    /*==============================================================================
    Initialize Environment
    ==============================================================================*/
    set nocount on
    set quoted_identifier on
    /*==============================================================================
    Parameter Validation
    ==============================================================================*/
    -- Configure Alert Mail Subject Line
    set @lnvc_Subject = 'Check consistency parameter validation error occurred on ' + cast(@@servername as nvarchar)
    if @lnc_PhysicalOnly not in ('Y','N')
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_PhysicalOnly is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_DataPurity not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_DataPurity is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_NoIndex not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_NoIndex is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_ExtendedLogicalChecks not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_ExtendedLogicalChecks is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_TabLock not in ('Y','N') and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'The value for parameter @inc_TabLock is not supported.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_ExtendedLogicalChecks = 'Y' and @lnc_PhysicalOnly = 'Y' and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'Extended Logical Checks and Physical Only cannot be used together.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @lnc_DataPurity = 'Y' and @lnc_PhysicalOnly = 'Y' and @li_Rc = 0
    begin
    set @lnvc_ErrorMessage = N'Physical Only and Data Purity cannot be used together.' + char(13) + char(10) + ' '
    set @li_Rc = -1
    end
    if @li_Rc != 0
    goto errlog
    /*==============================================================================
    Code Section
    ==============================================================================*/
    select @lnvc_SQL = N'select d.name, d.compatibility_level, d.create_date, d.user_access_desc, d.state_desc,
    d.page_verify_option_desc, cast(d.is_in_standby as tinyint), cast(d.is_read_only as tinyint),
    cast(databasepropertyex(quotename(d.name), ''IsAutoShrink'') as tinyint),
    cast(databasepropertyex(quotename(d.name), ''IsAutoClose'') as tinyint),
    0
    from master.sys.databases d
    where d.name = ' + case when isnull(@lnvc_Catalogue, '') = '' then ' d.name'
    else '''' + @lnvc_Catalogue + ''''
    end + '
    and d.name != ''tempdb'''
    insert into @ltbl_Catalogue (Catalogue, CompatibilityLevel, CreateDate, UserAccess,
    StateDescription, PageVerifyOption, IsReadOnly, IsInStandBy,
    IsAutoShrink, IsAutoClose, Flag)
    exec sp_executesql @lnvc_SQL
    while (select top 1 1
    from @ltbl_Catalogue c
    where c.Flag = 0) = 1
    begin
    select top 1 @lnvc_Catalogue = c.Catalogue
    ,@li_Compatibility = c.CompatibilityLevel
    ,@ldt_CreateDate = c.CreateDate
    ,@lnvc_UserAccess = c.UserAccess
    ,@lnvc_StateDescription = c.StateDescription
    ,@lnvc_PageVerifyOption = c.PageVerifyOption
    ,@lti_IsReadOnly = c.IsReadOnly
    ,@lti_IsInStandBy = c.IsInStandBy
    from @ltbl_Catalogue c
    where c.Flag = 0
    select top 1 @lnvc_Catalogue
    ,@li_Compatibility
    ,@ldt_CreateDate
    ,@lnvc_UserAccess
    ,@lnvc_StateDescription
    ,@lnvc_PageVerifyOption
    ,@lti_IsReadOnly
    ,@lti_IsInStandBy
    if @lnvc_StateDescription = 'ONLINE' and @lnvc_UserAccess != 'SINGLE_USER'
    begin
    -- Build Execution String
    select @lnvc_SQL = N'dbcc checkdb (' + quotename(@lnvc_Catalogue) + ')' + case when @lnc_NoIndex = 'Y' then ', noindex'
    else ''
    end + ' with tableresults, no_infomsgs, all_errormsgs '
    + case when @lnc_PhysicalOnly = 'Y' then ', physical_only'
    else ''
    end
    + case when @lnc_DataPurity = 'Y' then ', data_purity'
    else ''
    end
    -- Option not supported with Compatibility < 100 (SQL Server 2005 and below)
    + case when @lnc_ExtendedLogicalChecks = 'Y' then
    case when @li_Compatibility = 100 then ', extended_logical_checks'
    else ''
    end
    else ''
    end
    + case when @lnc_TabLock = 'Y' then ', tablock'
    else ''
    end
    -- Prepare Processing Environment
    truncate table #ltbl_Output
    set @ldt_ExecutionFinish = null
    set @ldt_ExecutionStart = null
    -- Capture Start Time.
    set @ldt_ExecutionStart = getdate()
    -- Execute the Command.
    insert into #ltbl_Output(Error, Level, State, MessageText, RepairLevel, Status,
    DBID, ObjectID, IndexID, PartitionID, AllocunitID,
    [File], Page, Slot, RefFile, RefPage, RefSlot, Allocation)
    exec sp_executesql @lnvc_SQL
    -- Capture Completion Time.
    set @ldt_ExecutionFinish = getdate()
    -- Add Header Record to Confirm Execution.
    insert into SysAdm.ConsistencyCheck.ExecutionLog(Instance, [Version], Edition, Catalogue, PhysicalOnly,
    NoIndex, ExtendedLogicalChecks, DataPurity, [TabLock],
    Command, ExecutionStart, ExecutionFinish,
    CreatedOn, CreatedBy)
    values(@lnvc_Instance, @lnvc_Version, @lnvc_Edition, @lnvc_Catalogue, @lnc_PhysicalOnly,
    @lnc_NoIndex, @lnc_ExtendedLogicalChecks, @lnc_DataPurity, @lnc_TabLock,
    @lnvc_SQL, @ldt_ExecutionStart, @ldt_ExecutionFinish,
    @ldt_ExecutedOn, @lnvc_ExecutedBy)
    -- Capture Header Record ID
    select @li_ConsistencyCheckID = @@IDENTITY
    -- Were there errors?
    if (select top 1 1
    from #ltbl_Output t) = 1
    begin
    select @li_ConsistencyCheckID, t.Error, t.Level, t.State, t.MessageText, t.RepairLevel,
    t.Status, t.ObjectID, t.IndexID, t.PartitionID, t.AllocunitID, t.[File], t.Page,
    t.Slot, t.RefFile, t.RefPage, t.RefSlot, t.Allocation, @ldt_ExecutedOn, @lnvc_ExecutedBy
    from #ltbl_Output t
    -- Log Failure Entries
    insert into SysAdm.ConsistencyCheck.ErrorLog (ExecutionLogID, Error, Severity, [State]
    ,ErrorMessage, RepairLevel, [Status], ObjectID
    ,IndexID, PartitionID, AllocationUnitID, FileID
    ,Page, Slot, RefFileID, RefPage, RefSlot, Allocation
    ,CreatedOn, CreatedBy)
    select @li_ConsistencyCheckID, t.Error, t.Level, t.State, t.MessageText, t.RepairLevel,
    t.Status, t.ObjectID, t.IndexID, t.PartitionID, t.AllocunitID, t.[File], t.Page,
    t.Slot, t.RefFile, t.RefPage, t.RefSlot, t.Allocation, @ldt_ExecutedOn, @lnvc_ExecutedBy
    from #ltbl_Output t
    -- Configure Alert Mail Subject Line
    set @lnvc_Subject = 'Consistency Check failure for Database ' + quotename(@lnvc_Catalogue) + ' on Instance ' + quotename(@lnvc_Instance) + ' !'
    set @lnvc_ErrorMessage = 'To view more details, logon to the Instance and execute the query: ' +
    + char(13) + char(10) + char(13) + char(10) +
    'select * from sysadm.consistencycheck.ErrorLog where ExecutionLogID = ' + cast(@li_ConsistencyCheckID as varchar) + ''
    + char(13) + char(10) + char(13) + char(10) +
    'Consistency Check Output: ' +
    + char(13) + char(10)
    select @lnvc_SQL = N'set nocount on;select ltrim(rtrim(ErrorMessage)) as Message
    from SysAdm.ConsistencyCheck.ErrorLog r
    where r.ExecutionLogID = ''' + cast(@li_ConsistencyCheckID as nvarchar(128)) + ''''
    exec msdb.dbo.sp_send_dbmail @profile_name = 'SQL Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @query = @lnvc_SQL,
    @execute_query_database = @lnvc_Catalogue,
    @query_result_header = 1,
    @query_result_width = 32767,
    @query_no_truncate = 1,
    @body_format = 'TEXT',
    @importance = 'High'
    end
    end
    else
    begin
    -- If we get here, then the database was not processed due to it having a status other than ONLINE, being in SINGLE_USER mode or
    -- having a compatability level < 100
    set @lnvc_Subject = 'Unable to perform consistency checks for Database ' + quotename(@lnvc_Catalogue) + ' on ' + quotename(@lnvc_Instance) + '!'
    set @lnvc_ErrorMessage = 'One of the following conditions was not met. ' + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) +
    '* Database must be ONLINE. It''s current state is: ' + @lnvc_StateDescription + CHAR(13) + CHAR(10) +
    '* Database access level cannot be set to SINGLE_USER. It''s current access level is: ' + @lnvc_UserAccess
    exec msdb.dbo.sp_send_dbmail @profile_name = 'SQL Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @body_format = 'TEXT',
    @importance = 'High'
    end
    update t
    set Flag = 1
    from @ltbl_Catalogue t
    where t.Catalogue = @lnvc_Catalogue
    end
    /*==============================================================================
    Cleanup Temp Tables
    ==============================================================================*/
    cleanup:
    if object_id('tempdb..#ltbl_Output') is not null
    drop table #ltbl_Output
    /*==============================================================================
    Exit Procedure
    ==============================================================================*/
    quit:
    return @li_Rc
    /*==============================================================================
    Error Processing
    ==============================================================================*/
    errlog:
    -- Raise Error, and write to Application Event Log
    raiserror (@lnvc_ErrorMessage, 16, 1) with log, nowait
    -- Send Email Notification of Error
    exec msdb.dbo.sp_send_dbmail @profile_name = 'Mailbox',
    @recipients = @lnvc_Recipients,
    @subject = @lnvc_Subject,
    @body = @lnvc_ErrorMessage,
    @importance = 'High'
    goto cleanup
    go
    John M. Couch

  • Sql agent job getting file access denied error

    I'm not sure if this question belongs in this forum. Please move it if you want to.
    Here is my question. I have an ssis package that is running into an error at the file system task trying to move a file. The package is deployed to the catalog and I am running the package using the stored procedure
    [SSISDB].[catalog].[start_execution] @execution_id
    When I execute this stored proc in Management Studio while logged in under a sysadmin, everything works fine. But when I call the same TQL in SQL Agent job, I get a file access denied error. This has something to do with the id that is getting used
    to run the package and I am not sure how to track that down. Any help would be appreciated.
    I've check the windows permission on both the id that is running the SQL Agent and SQL SSIS Service. Both seem to have the right windows permission.

    Please see:
    http://support.microsoft.com/kb/918760

  • Term is not recognized when executing PowerShell Script through SQL Agent using CMDEXEC

    I am trying to simply execute a PowerShell script that is stored in a file on a network drive through SQL Agent as a job. The script is a basic copy from one directory to another.  I have run and successfully executed this from a command prompt outside
    of SQL Agent.  When I execute this through SQL Agent as a Operating System (CmdExec) command I am getting an error that the term is not recognized as the name of a cmdleet, function, script file or operable program. I have executed many different ways
    put found an article to use double quotes in the network path which I have done with no success. 
    I am executing the following command as a job in SQL Agent:
    PowerShell H:\"\PowerShell""\PS_Scripts\"\batchcopyFFLWithProgress.ps1 through SQL Agent job
    I get the following error message:
     04/21/2015 10:01:09,Copy FFL Files,Error,1,NY11266-LTW7E\JPLAPTOPSQL,Copy FFL Files,Copy FFL files,,Executed as user: NT Service\SQLAgent$JPLAPTOPSQL. H:\PowerShell\PS_Scripts\batchcopyFFLWithProgress.ps1 : The term   'H:\PowerShell\PS_Scripts\batchcopyFFLWithProgress.ps1'
    is not recognized as   the name of a cmdlet<c/> function<c/> script file<c/> or operable program. Check the   spelling of the name<c/> or if a path was included<c/> verify that the path is   correct and try again.
     At line:1 char:1  + H:"\PowerShell\PS_Scripts"\batchcopyFFLWithProgress.ps1  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      + CategoryInfo          : ObjectNotFound:
    (H:\PowerShell\P...ithProgress.p      s1:String) []<c/> CommandNotFoundException      + FullyQualifiedErrorId : CommandNotFoundException.  Process Exit Code 1.  The step failed.,00:00:03,0,0,,,,0
    Content of batchcopyFFLWithProgress.ps1 which has the PowerShell script:
    $source=ls H:\SQLTest\Script\TestData\*.*
    $i=1
    $source| %{
        [int]$percent = $i / $source.count * 100
        Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete $percent -verbose
        copy $_.fullName -Destination H:\test -Recurse
        $i++
    I have searched the internet and have not found any resolution to my error.  If someone has experienced this error and found the resolution I would greatly appreciate your help.

    I have change the service account for SQL Agent to be my domain account as I have local admin rights to my laptop.  I stopped and started the services for SQL Agent and than started the job to run which is copying locally to minimize any network drive
    issues.  I am still getting the same error message as it is showing that I am executing the job under my domain account?  Any thoughts what it could be?
    ErrorMsg
    04/23/2015 11:21:06,Copy FFL Files,Error,1,ServerName\InstanceName,Copy FFL Files,Copy FFL files,,Executed as user: Domain\DomainAccount. \\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1 : The term '\\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1'
    is   not recognized as the name of a cmdlet<c/> function<c/> script file<c/> or operable program. Check the spelling of the name<c/> or if a path was   included<c/> verify that the path is correct and try again.  At
    line:1 char:1  + \\ServerName\Test\PS_Script\batchcopyFFLWithProgress.ps1  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      + CategoryInfo          : ObjectNotFound: (\\ServerName...ithProgress.ps1:String)
    []<c/> CommandNotFoundException      + FullyQualifiedErrorId : CommandNotFoundException.  Process Exit Code 1.  The step failed.,00:00:02,0,0,,,,0
    Script
    $source=ls "\\ServerName\Test\TestData\*.*"
    $i=1
    $source| %{
        [int]$percent = $i / $source.count * 100
        Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete $percent -verbose
        copy $_.fullName -Destination "\\ServerName\Test\test" -Recurse
        $i++

  • SQL Agent jobs status for multiple servers using Powershell.

    Hi All,
    I am following website link:
    http://www.toadworld.com/platforms/sql-server/b/weblog/archive/2013/09/17/powershell-script-to-monitor-a-service-on-a-group-of-servers-html-formatted-email-output.aspx
    I require to gather status details about all the SQL Agent jobs in the environment on multiple SQL Servers.
    I tried to edit the script using:
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
    $sqlServerName = 'localhost\developer'
    $sqlServer = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlServerName)
    foreach($job in $sqlServer.JobServer.Jobs)
        $job | select Name, OwnerLoginName, IsEnabled, LastRunDate, LastRunOutcome, DateCReated, DateLastModified
    but SQL Agent jobs are not reflecting in the mail output...
    requesting help...!!
    Thanks in Advance.
    Hunt

    I've created a new script for you.  Let me know if you've any questions
    Create the function
    Function Get-SQLJobHTMLReport
    param(
    [String]$ComputerList,[string]$Outputfile,[String]$To,[String]$From,[string]$SMTPMail
    New-Item -ItemType file $Outputfile -Force
    # Function to write the HTML Header to the file
    Function writeHtmlHeader
    param($fileName)
    $date = ( get-date ).ToString(‘yyyy/MM/dd’)
    Add-Content $fileName “<html>”
    Add-Content $fileName “<head>”
    Add-Content $fileName “<meta http-equiv=’Content-Type’ content=’text/html; charset=iso-8859-1′>”
    Add-Content $fileName ‘<title>Service Status Report </title>’
    add-content $fileName ‘<STYLE TYPE=”text/css”>’
    add-content $fileName “<!–”
    add-content $fileName “td {“
    add-content $fileName “font-family: Tahoma;”
    add-content $fileName “font-size: 11px;”
    add-content $fileName “border-top: 1px solid #999999;”
    add-content $fileName “border-right: 1px solid #999999;”
    add-content $fileName “border-bottom: 1px solid #999999;”
    add-content $fileName “border-left: 1px solid #999999;”
    add-content $fileName “padding-top: 0px;”
    add-content $fileName “padding-right: 0px;”
    add-content $fileName “padding-bottom: 0px;”
    add-content $fileName “padding-left: 0px;”
    add-content $fileName “}”
    add-content $fileName “body {“
    add-content $fileName “margin-left: 5px;”
    add-content $fileName “margin-top: 5px;”
    add-content $fileName “margin-right: 0px;”
    add-content $fileName “margin-bottom: 10px;”
    add-content $fileName “”
    add-content $fileName “table {“
    add-content $fileName “border: thin solid #000000;”
    add-content $fileName “}”
    add-content $fileName “–>”
    add-content $fileName “</style>”
    Add-Content $fileName “</head>”
    Add-Content $fileName “<body>”
    add-content $fileName “<table width=’100%’>”
    add-content $fileName “<tr bgcolor=’#CCCCCC’>”
    add-content $fileName “<td colspan=’4′ height=’25′ align=’center’>”
    add-content $fileName “</td>”
    add-content $fileName “</tr>”
    add-content $fileName “</table>”
    # Function to write the HTML Header to the file
    Function writeTableHeader
    param($fileName)
    Add-Content $fileName “<tr bgcolor=#CCCCCC>”
    Add-Content $fileName “<td width=’10%’ align=’center’>ServerName</td>”
    Add-Content $fileName “<td width=’50%’ align=’center’>Name</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>OwnerLoginName</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>IsEnabled</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>LastRunDate</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>LastRunOutcome</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>DateCReated</td>”
    Add-Content $fileName “<td width=’10%’ align=’center’>DateLastModified</td>”
    Add-Content $fileName “</tr>”
    Function writeHtmlFooter
    param($fileName)
    Add-Content $fileName “</body>”
    Add-Content $fileName “</html>”
    Function writeDiskInfo
    param($filename,$Servername,$name,$OwnerLoginName,$IsEnabled,$LastRunDate,$LastRunOutcome,$DateCReated,$DateLastModified)
    Add-Content $fileName “<tr>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$servername</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$name</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$OwnerLoginName</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$IsEnabled</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$LastRunDate</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$LastRunOutcome</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$DateCReated</td>”
    Add-Content $fileName “<td bgcolor=’#FF0000′ align=left ><b>$DateLastModified</td>”
    Add-Content $fileName “</tr>”
    writeHtmlHeader $Outputfile
    Add-Content $Outputfile “<table width=’100%’><tbody>”
    Add-Content $Outputfile “<tr bgcolor=’#CCCCCC’>”
    Add-Content $Outputfile “<td width=’100%’ align=’center’ colSpan=8><font face=’tahoma’ color=’#003399′ size=’2′><center><strong> SQL Server Agent Job Details</strong></font></td>”
    Add-Content $Outputfile “</tr>”
    writeTableHeader $Outputfile
    #Change value of the following parameter as needed
    Foreach($ServerName in (Get-Content $ComputerList))
    $sqlServer = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerName)
    foreach($item in $sqlServer.JobServer.Jobs)
    Write-Host $sqlServer $item.name $item.OwnerLoginName $item.IsEnabled $item.LastRunDate $item.LastRunOutcome $item.DateCReated $item.DateLastModified
    writeDiskInfo $Outputfile $sqlServer $item.name $item.OwnerLoginName $item.IsEnabled $item.LastRunDate $item.LastRunOutcome $item.DateCReated $item.DateLastModified
    Add-Content $Outputfile “</table>”
    writeHtmlFooter $Outputfile
    Function sendEmail
    param($from,$to,$subject,$smtphost,$htmlFileName)
    [string]$receipients=”$to”
    $body = Get-Content $htmlFileName
    $body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
    $body.isBodyhtml = $true
    $smtpServer = $smtphost
    $smtp = new-object Net.Mail.SmtpClient($smtphost)
    $smtp.Send($body)
    write-output “Email Sent!!”
    $date = ( get-date ).ToString(‘yyyy/MM/dd’)
    sendEmail -from $From -to $to -subject “Service Status – $Date” -smtphost $SMTPMail -htmlfilename $Outputfile
    Get-SQLJobHTMLReport -ComputerList f:\powersql\server.txt -SMTPMail hq.abc.com -To [email protected] -From [email protected] -Outputfile F:\Powersql\jobs.htm
    --Prashanth

Maybe you are looking for

  • Email Signature or company message preset instead

    How can I preset the message of my company account such as important : this message could not forward Etc...warning message? Solved! Go to Solution.

  • In place display of folders:available?

    Hello, Is the inplace display of folders and their contents available in 3.0.8 ? currently, I use a html portlet to show the fixed tabset. But, in 3.0.7, if you go to a folder, then you lose the tabs. Any workarounds or do I have to go to 3.0.8 ? Tha

  • Database connection lost during running report

    Hello Experts, Our environment is WINDOWS2008 SERVER / ORACLE 10G / ORACLE REPORTS. The problem we are facing is , while running one of the particular reports which runs oracle reports , connection to database server gets lost. Acturally the form is

  • How do I reset Administrator password on macbook pro 10.10.1

    How do I reset the Administrator password if I have forgotten it on a macbook pro running 10.10.1 Yosimite?

  • PSE8 cannot open Adobe help viewer from organizer workspace

    This has been working fine for the past week!  Last night, I uploaded some pics from my camera, posted them on Facebook, and also a shared volume I e-mailed via photoshop.com.   Now this feature no longer works, although I can view the tutorials from