Use PowerShell to query security log and extract specific info

Hi all,
excuse my scripting noobness :)
I need a script that queries a remote machine's security event log, filter for event_id 4624 and user "someuser" and parse the following infos:
DATE_TIME   SOURCE_IP_ADDRESS   SOURCE_PORT
then writes all into a text file.
Anyone would be so nice to help me.. i'd assume this is a simple task for the scripting gurus.
Thanks in advance
Massimo

1) how do you find out the property number to print in the format-table?
Count:
<Data Name="SubjectUserSid">S-1-5-18</Data> - 0
  <Data Name="SubjectUserName">HY-SRV$</Data> - 1
  <Data Name="SubjectDomainName">WORKGROUP</Data>
  <Data Name="SubjectLogonId">0x3e7</Data>
  <Data Name="TargetUserSid">S-1-5-18</Data>
  <Data Name="TargetUserName">SYSTEM</Data>
  <Data Name="TargetDomainName">NT AUTHORITY</Data>
  <Data Name="TargetLogonId">0x3e7</Data>
  <Data Name="LogonType">5</Data>
  <Data Name="LogonProcessName">Advapi</Data>
  <Data Name="AuthenticationPackageName">Negotiate</Data>
  <Data
Name="WorkstationName" />
  <Data Name="LogonGuid">{00000000-0000-0000-0000-000000000000}</Data>
  <Data Name="TransmittedServices">-</Data>
  <Data Name="LmPackageName">-</Data>
  <Data Name="KeyLength">0</Data>
  <Data Name="ProcessId">0x410</Data>
  <Data Name="ProcessName">C:\Windows\System32\services.exe</Data>
  <Data Name="IpAddress">-</Data> - 18
  <Data Name="IpPort">-</Data> - 19
 <Data Name="ImpersonationLevel">%%1833</Data>
2) And is it possible to just print a unique entry for each IP_ADDRESS found?
Get-WinEvent -LogName Security -FilterXpath .... | Sort {$_.properties[18].value} -Uniq | Format-Table ....

Similar Messages

  • Using powershell to manipulate mapi profile and PST file locations

    I have a situation whereby I need to move a bunch of PST files out of the default location in Office 2010 and change the mapi profile for the user so that the pst file location updated so the user doesn't experience any issues when launching Outlook.
    My logic flow is as follows:
    1.) locate All pst files referenced in the logged on users MAPI profile.
    2.) Move these files to a another directory eg. c:\users\%username%\OutlookFiles
    3.) Update the MAPI profile to point to the new location so that when the user launches Outlook he doesn't notice that the files have been moved.
    I know how to copy the files using powershell etc. but how on earth do you query the MAPI profile to locate the pst files and then change each entry for a PST file to point to the new location.
    Anyone got any ideas?

    What you are trying to do cannot normally be done with a script due to a whole host of reasons including differences in versions and lack of access to a users profile.
    !. Are you on Exchnage?
    2. Have you redirected the users folders with Group Policy yet?
    Outlook OST files are not movable without the use of a third party tool.  It is far easier to just have the users create a new profile.
    PST files that are attached in a user session can be moved using a script that can be run by the user.
    ¯\_(ツ)_/¯

  • How do I enable "Audit user account logons" using PowerShell, to improve security?

    With successful hacking attacks more often employing valid Active Directory user credentials, it is quite helpful when administrators can
    easily poll user logon events. Rather than query
    every domain computer for its logon events, one can alter the Default Domain Controller Policy GPO to enable "Audit user account logons" (Success and Failure) then merely poll
    only the domain controller -- quite efficient. PowerShell helpfully has its Group Policy Module, including the following two cmdlets.
    1) Get-GPO "Default Domain Controllers Policy" will retrieve the top-level GPO object, but how do I enable that specific setting?
    2) Set-GPRegistryValue might be the right tool, but I cannot find any documentation on the values I need to supply to its parameters (-Name -Key -ValueName -Type -Value) to enable "Audit user account logons" -- both Successes and Failures.
    One can manually modify this setting using the Group Policy Management console GUI on the domain controller, but I am trying to upgrade my professional work habits to use stored scripts, rather than unrecorded point & clicks, so that my actions are repeatable
    and documented.
    Any pointers to documentation or an example would be welcome. I originally posted this question in the TechNet PowerShell Forum this afternoon, but someone recommended I copy it to the TechNet Group Policy Forum.
    Jeffrey - New Orleans MCITP Enterprise Administrator, Virtualization Administrator

    Hi Jeffrey,
    >>One can manually modify this setting using the Group Policy Management console GUI on the domain controller, but I am trying to upgrade my professional work habits to use stored scripts, rather than unrecorded point & clicks, so that my actions
    are repeatable and documented.
    Before going further, although you have expressed that you don't want to use GPMC GUI to configure the audit setting, in fact, it's an easy and comparatively handy method to set the setting. Besides, based on the description, you
    want to use PowerShell to do this. However, as far as I know, PowerShell can configure registry-based policy settings and Group Policy Preferences Registry settings, but audit policy security settings are not registry keys.
    Nonetheless, if we really don't want to use GPMC console to do this, we can use Auditpol.exe to set the audit setting.
    Regarding this point, the following article can be referred to for more information.
    Auditpol
    https://technet.microsoft.com/en-in/library/cc731451.aspx
    Auditpol set
    https://technet.microsoft.com/en-in/library/cc755264.aspx
    In addition, regarding Group Policy Cmdlets in Windows PowerShell, the following article can be referred to for more information.
    Group Policy Cmdlets in Windows PowerShell
    https://technet.microsoft.com/en-us/library/ee461027.aspx
    TechNet Subscriber Support
    If you are TechNet Subscription user and have any feedback on our support quality, please send your feedback here.
    Best regards,
    Frank Shen

  • Powershell script for security groups and users for multiple share folders

    Hi scripting team,
    I need your help with powershell script for the below queries 
    1. List out the security groups for more than one server share path and output it to a file ( csv ) 
    For eg.
    If the are are two share paths 
    \\servername\foldermain\folder1
    \\servername\foldermain\folder2
    So I needs the list of security groups for each share path
    And the output needs to be under each any every path.
    2. Grab the users belongs to main security groups and it nested groups for more than one security group and listed the users under each and every group. No need to display nested groups. Just users belongs to main group and users under nested.
    Your teams help is much appreciated 
    Thank you.
    Thilochana kumararatne

    Hi Braham,
    Thanks for your quick reply.
    Are we able to do this on two stage method
    1. grab the security groups from the share paths
    if can grab the share path from a separate txt file than copying it to the <your path> location
    so i can modify the txt file
    once run the script
    if can the output like below to a CSV file
    \\servername\foldermain\folder1group 1group 2group 3\\servername\foldermain\folder2group 1group 2group 3then i know which groups belongs to which share paththen i can remove the duplicate groups and keep the common groups to grab the users belongs to itso with the second script same as the first copy the security groups to a txt file and the out put as below.what I needs is the users full name and the samaccount name ( user id )group 1user1user2user3
    group 2user1user2user3looking forward your help on thisThank you.Thilo

  • Permissions fix for secure.log and iTunes frameworks

    Aperture 1.5
    PBG4 showed minor to considerable performance improvements. Once my main library finished running on the Quad, with 6600 traction engine, I started to do some real work.
    The following is in Project View on some images with patches/healing and straighten applied.
    IT WAS UGLY. SBOD every time I touched anything (yes, all previews completed). 45 secs to open the first image (8Mb RAW from Canon 20d). 5-6 secs. for any touch on Levels or Exposure. IMPOSSIBLE.
    Switched off and reduced res. of JPG's in Preferences. No difference.
    BTW Apple Devt. Spank time> There is NO way to turn off Preview creation and run as batch later that I can see. Please fix. Agreed they render in background but why not wait until you leave focus on that image .... it's recreating a preview after every adjustment I make. C'mon guys, get real, that should be fixed asap.
    Quit Aperture, restarted. Just as bad. Aperture is the only app. running, and Activity Monitor shows 319% CPU with 480Mb RAM just with a Levels change ... sounds high. 6-7 sec. response time for anything I do and 20-40 secs for image rendering, except adjacent images. Quit Aperture.
    Decided to run Repair Permissions (RAID = 0 drive). Fixed iTunes frameworks and secure.log. I believe secure.log to be the culprit.
    Restarted Aperture and performance improvements obvious. Sliders now work real-time and image rendering a couple of seconds. Reapplied Preferences setting for Previews and no significant performance degradation (though it is interesting watching the task list pause the preview generation when you make further edits.)

    It sounds like you should just turn off Maintain Previews for the project you are on (selct prj and change state in top level gear menu in prj pane) - then make your adjustments ( your previews won't be up to date then of course) but the when you are ready to make into previews just select all the images and choose Update Preview manually from the context menu.
    LC, Classic, 8500, DP2.5, MBP2.1   Mac OS X (10.4.7)   i have a cool mousepad

  • Secure.log and log rotation problems

    I had originally posted this in the Tiger section, but now finding the Unix section which I think would be able to help me more. here is the link to the post: http://discussions.apple.com/thread.jspa?threadID=1913487&tstart=0
    Also I am getting this in my system.log, I have googled it and cannot find anything that tells me what it is:
    Feb 19 18:54:34 SamiMac kernel[0]: m378d97c0 0
    some help on this would also be appreciated.
    Message was edited by: a Mac user

    The secure.log message is explained at the bottom of Spurious Permission errors in OS X 10.4.
    For your ipfw logs, check that /etc/periodic/weekly/500.weekly contains the line
    for i in ftp.log lookupd.log lpr.log mail.log netinfo.log hwmond.log ipfw.log ppp.log secure.log; do
    (although I don't know why it wouldn't) and then check this is actually being run by looking at /var/log/weekly.out. Try
    tail -10 /var/log/weekly.out
    Let us know what you see.
    I haven't seen that kernel message before

  • Powershell to Query expiring accounts and then email

    Check: AD Notify users x days in advance that their password will expire
    A Powershell script. Sorry but I can't get a hyperlink to work in the mobile app.

    Ok, so I am looking to create a script to query expired/expiring accounts and then send an email with the new found info. The email part I have done a couple times before, works like a charm. The problem I am having is figuring out how to pipe the output from each query into a variable that I can call later on in the script to insert into the email.Powershell# Variables that we will use later$date = Get-Date $now = $date.ToFileTime() $ou = "OU=example,OU=example,DC=example,DC=com" # This section will output all expired accounts in the predefined OU "`nExpired" $root = [ADSI]"" $search = [adsisearcher]$root $search.Filter = "(&(objectclass=user)(objectcategory=user)(accountExpires>=1)(accountExpires

  • Using Sym Links for .dbf, .log, and .ctl files?  Will this work in 10g?

    Hello,
    We have an old database server we use for testing/development and it's running very low on diskspace on one of the filesystems on the box. At this point in time, adding space is not a simple option for several reasons. However, there are several other data partitions on this server with plenty of space available.
    I read a paper published by Sun Microsystems that advocates the use of symbolic links for dbf, ctl, and log files:
    http://www.sun.com/blueprints/0103/817-1048.pdf
    Are there any drawbacks/caveats we need to be aware of, or is this really as simple as just stopping the db, moving a few files to another fs, symlinking their locations, and restarting the db?
    Thanks for your input/advice.

    I think you should verify this with Oracle Support.
    This is the perfect measure to have them drop the phone on you.
    Sybrand Bakker
    Senior Oracle DBA

  • Hello! I use photoshop CS3. recently, after logging information into FILE INFO, I am unable to close out that window. I am able to save & close the image I am working on, but the window remains. I then must close out of Photoshop completely and reopen to

    Hello! I use Photoshop CS3 and Yosemite. Recently, after logging info information into the FILE INFO panel, I am unable to close out the window. I am able to save & close out the image, but then I have to completely close Photoshop and re-open the program to work on a new image. Frustrating! Any help to remedy this problem? Many thanks!

    Try resetting the Photoshop preference file: Press and hold Cmd+Opt+Shift and start Photoshop. Select "yes" when asked if you would like to continue with reset.
    Benjamin

  • Using Multiple iPods on 1 Computer and Changing Track Info on Files

    Hi - I recently had to get a new computer, so I have a Windows 7 machine. I use 2 iPods and and iPhone. I have set up separate user accounts in Windows 7 to separate music files, video files, and info for iPhone. I'm having some problems, first, with multiple accounts. When using an account in an other than administrator account, the administrator account keeps getting errors that iTunes can't be opened. So while in another account, I get error notices in the administrator account. Second, a number of CDs that I copy into iTunes come over as "Compilations." I can't make changes to the categories so the CDs appear with the artists, even though I've actually gone into the files through Windows Explorer to change them from read only. Any suggestions?

    Just plug them in.
    (60721)

  • I forgot my security questions, and the reset info won't send to my primary email

    how can I get the security reset info sent to my primary email?

    Contact Apple Account Security. See: Apple ID: Contacting Apple for help with Apple ID account security

  • How do I bulk upload documents using PowerShell and extract metadata from file name?

    I have a requirement to upload a bunch of documents into a document library. Based on the content type, the rules of updating the metadata is different...the one giving me trouble is to extract the metadata from the file name. If I have a file name like
    "part1_part2_part3.pdf" how do I extract part1, part2, part3 and tag each document being uploaded into SharePoint, using PowerShell? I have searched and have not been able to find anything to get me started.
    Has anyone done this before? Or is there a blog I can take a look at? Thanks
     

    You will have to write a PS script encompassing this logic.
    Read files from the folder using
    Get-Item cmdlet
    Determine the content type based on the path or filename.
    Split the file name to extract the tag names.
    If the metadata fields in the content type is a managed metadata field, check whether the term exists and set it.
    Updating SharePoint Managed Metadata Columns
    with PowerShell
    This post is my own opinion and does not necessarily reflect the opinion or view of Slalom.

  • AD get records of security log..

    Hello everyone:)
    i must get some records (by event id, time, etc..) of security log.
    adler_steven answer me for previous my post(http://forum.java.sun.com/thread.jspa?threadID=5292943&messageID=10238354#10238354)
    he sad look at http://forum.java.sun.com/thread.jspa?threadID=5116320&tstart=15
    I must use WMI HTTP Mapper and some WBEM library...
    Ok, i install and configure WMI HTTP Mapper and use next source for try get :) security log, by this dont work...
    connect success, but retrieving information failed
    adler_steven :) help me :)
    *EXHIBIT A - Sun Industry Standards Source License
    *"The contents of this file are subject to the Sun Industry
    *Standards Source License Version 1.2 (the "License");
    *You may not use this file except in compliance with the
    *License. You may obtain a copy of the
    *License at http://wbemservices.sourceforge.net/license.html
    *Software distributed under the License is distributed on
    *an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
    *express or implied. See the License for the specific
    *language governing rights and limitations under the License.
    *The Original Code is WBEM Services.
    *The Initial Developer of the Original Code is:
    *Sun Microsystems, Inc.
    *Portions created by: Sun Microsystems, Inc.
    *are Copyright � 2001 Sun Microsystems, Inc.
    *All Rights Reserved.
    *Contributor(s): _______________________________________
    import java.io.IOException;
    import java.util.Enumeration;
    import javax.wbem.cim.*;
    import javax.wbem.client.*;
    import javax.wbem.client.UserPrincipal;
    import javax.wbem.client.PasswordCredential;
    * This class will perform an CIMClient.execQuery using a WQL query string that
    * is passed on the command line.  If a query isn't passed on the command line,
    * the user will be prompted for the query
    public class TestQuery {
        public TestQuery(String args[]) {
            String serverName = "win2003";
            String user = "administrator";
            String pass = "welcome1";
            CIMClient cimClient = null;
            CIMObjectPath cimPath = null;
            String wbemNameSpace = "root/CIMV2";
            int wbemPortNumber = 5988;
            String wbemProtocol = CIMClient.CIM_XML;
            try {
                    System.out.println("connecting..\n");
                    String hostURL = "http://" + serverName + ":" + wbemPortNumber;
                    CIMNameSpace cimNameSpace = new CIMNameSpace(hostURL,wbemNameSpace);
                    UserPrincipal userName = new UserPrincipal(user);
                    PasswordCredential userPass = new PasswordCredential(pass);
                    cimClient = new CIMClient(cimNameSpace,userName,userPass,wbemProtocol);
            catch (CIMException e) {
                    System.err.println("Failed to access CIMOM: " + e);
            try {
                    System.out.println("get win32_ntlogevent");
                    cimPath = new CIMObjectPath("Win32_NTLogEvent");
                    System.out.println("cimPath");
                    Enumeration e = cimClient.enumerateInstances(cimPath); // this line hang
                    System.out.println("Enumeration");
                    if (e.hasMoreElements()) {
                            CIMInstance ci = (CIMInstance)e.nextElement();
                            // i think, there must be properties of Win32_NTLogEvent Class, such as message, eventid, eventcode...
                            CIMProperty cp = ci.getProperty("Message");
                            System.out.println("   Message: " + cp.getValue());
                    System.out.println("stop get win32..");
                    cimClient.close();
            catch (NullPointerException e) {
                    System.err.println("Null Pointer Exception: " + e);
            catch (CIMException e) {
                    System.err.println("Failed to enumerate WBEM Info: " + e);
        public static void main(String args[]) {
         new TestQuery(args);
    {code}
    Edited by: Jeqpbl4 on Jun 9, 2008 4:24 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I figure I've abused enough people today on the forum, that it's time to redeem myself.
    Firstly, as I've always admitted, I'm not a Java developer, so there may be better ways of doing this. Secondly, I'm not an expert on WBEM/WMI, so I'm not sure of the different classes, methods or properties that WBEM exposes. I think I recommended some references in the links mentioned in this post, so if you want to dig deeper, go read those.
    This is just a quick and dirty WBEM query that retrieves the security events. One thing I discovered is that if you have lots of events, you'll get a heap overflow exception. I guess there may be a way to retrieve pages of results, otherwise use a more refined query to return a smaller number of records.
    * WBEMQueryLog, retrieve the entries from the security log from a server
    * demonstrating the use of a WBEM Query
    import java.io.*;
    import java.util.*;
    import javax.wbem.cim.*;
    import javax.wbem.client.CIMClient;
    import javax.wbem.client.UserPrincipal;
    import javax.wbem.client.PasswordCredential;
    public class wbemquerylog {
        public static void main(String args[]) throws CIMException {
         CIMClient cc = null;
         CIMObjectPath cop = null;
         CIMInstance ci = null;
         String hostname = "myServer";
         String nameSpace = "root/CIMV2";
         int portNumber = 5988;
         String hostURL = "http://" + hostname + ":" + portNumber;
         String protocol = CIMClient.CIM_XML;
         try {
             CIMNameSpace cns = new CIMNameSpace(hostURL,nameSpace);
             UserPrincipal username = new UserPrincipal("myServer/Administrator");
             PasswordCredential password = new PasswordCredential("XXXXXX");
             cc = new CIMClient(cns,username,password,protocol);
         catch (CIMException e) {
              System.err.println("Failed to access CIMOM: " + e);
              System.exit(1);
         cop = new CIMObjectPath();
         //lets try to get the Security Log entries, using a query
         try {
              cop = new CIMObjectPath();//"Win32_NTLogEvent");
              String query = "Select * from Win32_NTLogEvent where Logfile='Security'";
              Enumeration e = cc.execQuery(cop,query,CIMClient.WQL);
              for (int i = 1;e.hasMoreElements();i++) {
                   System.out.println("Event: " + i);
                   System.out.println(e.nextElement());
         catch (CIMException e) {
              System.err.println("Failed to query security log: " + e);
              System.exit(1);
         System.exit(0);
    }If you want to retrieve specific Security Log Events, you could construct a more complex query, such as below, which will find Account Logon Failures
    String query = "Select * from Win32_NTLogEvent where Logfile='Security' And EventCode = '681'";You could also use an enumeration as you have done, the only thing I haven't bothered to work out is how to enumerate the Security log itself, rather than every event in all the logs. I guess it's just a matter of working out what the CIM Path is, if it as at all possible.
    * WBEMEnumLog, enumerate the NTEventLogs from a server
    * Should find out the full CIM Path for the security logs
    import java.io.*;
    import java.util.*;
    import javax.wbem.cim.*;
    import javax.wbem.client.CIMClient;
    import javax.wbem.client.UserPrincipal;
    import javax.wbem.client.PasswordCredential;
    public class wbemenumlog {
        public static void main(String args[]) throws CIMException {
         CIMClient cc = null;
         CIMObjectPath cop = null;
         CIMInstance ci = null;
         String hostname = "myServer";
         String nameSpace = "root/CIMV2";
         int portNumber = 5988;
         String hostURL = "http://" + hostname + ":" + portNumber;
         String protocol = CIMClient.CIM_XML;
         try {
             CIMNameSpace cns = new CIMNameSpace(hostURL,nameSpace);
             UserPrincipal username = new UserPrincipal("myServer/Administrator");
             PasswordCredential password = new PasswordCredential("XXXXXX");
             cc = new CIMClient(cns,username,password,protocol);
         catch (CIMException e) {
              System.err.println("Failed to access CIMOM: " + e);
              System.exit(1);
         cop = new CIMObjectPath();
         try {
              Enumeration en = cc.enumNameSpace(cop,true);
              if (en != null) {
                   while (en.hasMoreElements()) {
                        CIMObjectPath obj = (CIMObjectPath)(en.nextElement());
                        System.out.println("Namespace: " + obj.toString());
         catch (CIMException e) {
              System.err.println("Failed to enumerate namespace: " + e);
              System.exit(1);
         //lets try to get the event logs
         try {
              cop = new CIMObjectPath("Win32_NTLogEvent");
              System.out.println("Host: " + cop.getHost());
              System.out.println("Object Name: " + cop.getObjectName());
              String attrs[] = {"Logfile","Sourcename","EventIdentifier","EventType","TimeGenerated","Type","CategoryString","User"};
              Enumeration e = cc.enumerateInstances(cop,false,false,false,false,attrs);
              for (int i = 1;e.hasMoreElements();i++) {
                   System.out.println("Disk: " + i);
                   System.out.println(e.nextElement());
         catch (CIMException e) {
              System.err.println("Failed to enumerate Event Log: " + e);
              System.exit(1);
         System.exit(0);
    }Good luck....

  • Is there a way to get long running SQL Agent jobs information using powershell?

    Hi All,
    Is there a way to get long running SQL Agent jobs information using powershell for multiple SQL servers in the environment?
    Thanks in Advance.
    --Hunt

    I'm running SQL's to fetch the required details and store it in centralized table. 
    foreach ($svr in get-content "f:\PowerSQL\Input\LongRunningJobsPowerSQLServers.txt"){
    $dt = new-object "System.Data.DataTable"
    $cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
    $cn.Open()
    $sql = $cn.CreateCommand()
    $sql.CommandText = "SELECT
    @@SERVERNAME servername,
    j.job_id AS 'JobId',
    name AS 'JobName',
    max(start_execution_date) AS 'StartTime',
    max(stop_execution_date)AS 'StopTime',
    max(avgruntimeonsucceed),
    max(DATEDIFF(s,start_execution_date,GETDATE())) AS 'CurrentRunTime',
    max(CASE WHEN stop_execution_date IS NULL THEN
    DATEDIFF(ss,start_execution_date,stop_execution_date) ELSE 0 END) 'ActualRunTime',
    max(CASE
    WHEN stop_execution_date IS NULL THEN 'JobRunning'
    WHEN DATEDIFF(ss,start_execution_date,stop_execution_date)
    > (AvgRunTimeOnSucceed + AvgRunTimeOnSucceed * .05) THEN 'LongRunning-History'
    ELSE 'NormalRunning-History'
    END) 'JobRun',
    max(CASE
    WHEN stop_execution_date IS NULL THEN
    CASE WHEN DATEDIFF(ss,start_execution_date,GETDATE())
    > (AvgRunTimeOnSucceed + AvgRunTimeOnSucceed * .05) THEN 'LongRunning-NOW'
    ELSE 'NormalRunning-NOW'
    END
    ELSE 'JobAlreadyDone'
    END)AS 'JobRunning'
    FROM msdb.dbo.sysjobactivity ja
    INNER JOIN msdb.dbo.sysjobs j ON ja.job_id = j.job_id
    INNER JOIN (
    SELECT job_id,
    AVG
    ((run_duration/10000 * 3600) + ((run_duration%10000)/100*60) + (run_duration%10000)%100)
    +
    STDEV
    ((run_duration/10000 * 3600) + ((run_duration%10000)/100*60) + (run_duration%10000)%100) AS 'AvgRuntimeOnSucceed'
    FROM msdb.dbo.sysjobhistory
    WHERE step_id = 0 AND run_status = 1
    GROUP BY job_id) art
    ON j.job_id = art.job_id
    WHERE
    (stop_execution_date IS NULL and start_execution_date is NOT NULL) OR
    (DATEDIFF(ss,start_execution_date,stop_execution_date) > 60 and DATEDIFF(MINUTE,start_execution_date,GETDATE())>60
    AND
    CAST(LEFT(start_execution_date,11) AS DATETIME) = CAST(LEFT(GETDATE(),11) AS DATETIME) )
    --ORDER BY start_execution_date DESC
    group by j.job_id,name
    $rdr = $sql.ExecuteReader()
    $dt.Load($rdr)
    $cn.Close()
    $dt|out-Datatable
    Write-DataTable -ServerInstance 'test124' -Database "PowerSQL" -TableName "TLOG_JobLongRunning" -Data $dt}
    You can refer the below link to refer out-datatable and write-dataTable function.
    http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/01/use-powershell-to-collect-server-data-and-write-to-sql.aspx
    Once we've the table details, I'm sending one consolidated email to automatically.
    --Prashanth

  • How to Query from table and insert into another table.

    Hi
    I am using the following query in VO and all the columns are attached to EO ( table name emp_temp)
    select a.npw_number, a.person_id,b.assignment_id,a.title,a.last_name,a.first_name,a.date_of_birth,a.sex,
    b.organization_name,b.organization_id,b.job_id,b.job_name,b.position_id,b.position_name,b.supervisor_id,
    b.supervisor_name,b.location_id,b.effective_start_date,b.effective_end_date
    from per_all_people_f a,per_assignments_v b
    where a.person_id=b.person_id
    and a.npw_number=:1
    I can query the data in screen. I need into insert the data into the emp_temp.
    I don't know how to do this . Please help me.
    Thanks
    Subra

    You can create a VO based on EO on emp_temp table.....
    And u have attached a Different VO on the page... Right...
    Now what u can do is....once u click on apply....
    u can set the each attributes of EO based VO explicitly via code, from the values of second VO.... and then commit.....
    Perhaps this might help...

Maybe you are looking for

  • C90 only making audio calls

    Hello , I just purchased and setup two C90s . Calling to other endpoints or inside my network between these two I only get an audio call. I have gone over everything 100 times and I just cant seem to find the issue. I have used the C series codecs fo

  • Plant Specific Authorization of  VA42,VA02,VF03

    Hi, I have to provide authorization for Change or Display of Contract Orders,Sale Orders, Billing docs for the Users of the plant in which they were created and for other Plant users i need to restrict. For example, If a billing doc was created in Pl

  • Loading maps to nokia 2730 phone

    When I attempt to load maps to my phone 2730 a message appears stating that my phone is not equipped to accept maps I have updated my softare to no avail would the problem have anything to do with the type of sim card installed.

  • Xquery in oracle 10g

    I loaded one xmlfile into an xmltype column. I need querying in that file and typed select extract(biodata,'/biodata/personalinfo/name') from biodat_info; in sqlplus, and I didn't get any result but the query was successfull. it told that 10 rows sel

  • How to make whatsapp work in iPhone5?

    I have installed whatsapp on my new IPhone5. In contarst to previous phone-i can not view nwo who of my contacts has whatsapp? any suggestions? thanks