how to get the information of system log of taskscheduler under the command line with WMIC? - wmic

I need to know whether the taskscheduler has run successfully. I found difficult to get a return value by the wmic command, because they aren't included in the system, security, application hardwareevents and so on logfile. Following is my attempts:
wmic ntevent "eventcode=140" get message /value
The above code returns the message: "no instance(s) availalbe."
As I don't know which kind of logfile includes the log records of taskschedule, I select them by the eventcode.
wmic ntevent where "logfile='system' and eventcode='140'" get message /vule
No matter, logfile='appliaction' or logfile='security', at the end I can't get the result I want.
What i need to point out is the log records are allocated in Microsoft-Windows-TaskScheduler/Operational in graphical interfaces.

Unfortunately, wmic can only be used on classic logs. List them by
wmic NTEventlog get LogfileName or by powershell Get-EventLog -AsString -List:
Application
HardwareEvents
Internet Explorer
Key Management Service
PreEmptive
Security
System
TuneUp
Windows PowerShell
Switch to wevtutil: wevtutil enum-logs enumerates the available logs and
wevtutil qe Microsoft-Windows-TaskScheduler/Operational /q:"*[System[Provider[#Name='Microsoft-Windows-TaskScheduler'] and (EventID=140)]]" /uni:false /f:text
command could be a starting point for you. Pretty weird syntax and result hard do parse. Moreover:
The primary focus of WEVTUTIL is the configuration and setup of
event logs, to retrieve event log data the PowerShell cmdlet
Get-WinEvent is easier to use and more flexible:
Switch to powershell: (Get-WinEvent -ListLog *).LogName enumerates the available logs and one can simply filter and format result from next command:
Get-WinEvent -LogName Microsoft-Windows-TaskScheduler/Operational
For instance, to format the result in list view to see all properties:
Get-WinEvent -LogName Microsoft-Windows-TaskScheduler/Operational | Format-List *
Read more in Powershell and the Applications and Services Logs.

Related

Why does the Switch statement seem to ask for response before the ExecutewithResults method displays its results [duplicate]

I am writing a PowerShell script in version 5.1 on Windows 10 that gets certain pieces of information about a local system ( and eventually its subnets ) and outputs them into a text file. At first, I had all of the aspects in a single function. I ran into output issues when outputting getUsersAndGroups and getRunningProcesses functions, where output from getUsersAndGroups would be injected into the output of getRunningProcesses.
The two functions are:
# Powershell script to get various properties and output to a text file
Function getRunningProcesses()
{
# Running processes
Write-Host "Running Processes:
------------ START PROCESS LIST ------------
"
Get-Process | Select-Object name,fileversion,productversion,company
Write-Host "
------------- END PROCESS LIST -------------
"
}
Function getUsersAndGroups()
{
# Get Users and Groups
Write-Host "Users and Groups:"
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$adsi.Children | where {$_.SchemaClassName -eq 'user'} | Foreach-Object {
$groups = $_.Groups() | Foreach-Object {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
$_ | Select-Object #{n='Username';e={$_.Name}},#{n='Group';e={$groups -join ';'}}
}
}
getRunningProcesses
getUsersAndGroups
When I call getUsersAndGroups after getRunningProcesses, the output looks like this ( does not output getUsersAndGroups at all ):
Running Processes:
------------ START PROCESS LIST ------------
Name FileVersion ProductVersion Company
---- ----------- -------------- -------
armsvc
aswidsagenta
audiodg
AVGSvc
avgsvca
avguix 1.182.2.64574 1.182.2.64574 AVG Technologies CZ, s.r.o.
conhost 10.0.14393.0 (rs1_release.160715-1616) 10.0.14393.0 Microsoft Corporation
csrss
csrss
dasHost
dwm
explorer 10.0.14393.0 (rs1_release.160715-1616) 10.0.14393.0 Microsoft Corporation
hkcmd 8.15.10.2900 8.15.10.2900 Intel Corporation
Idle
igfxpers 8.15.10.2900 8.15.10.2900 Intel Corporation
lsass
MBAMService
mDNSResponder
Memory Compression
powershell_ise 10.0.14393.103 (rs1_release_inmarket.160819-1924) 10.0.14393.103 Microsoft Corporation
RuntimeBroker 10.0.14393.0 (rs1_release.160715-1616) 10.0.14393.0 Microsoft Corporation
SearchFilterHost
SearchIndexer
SearchProtocolHost
SearchUI 10.0.14393.953 (rs1_release_inmarket.170303-1614) 10.0.14393.953 Microsoft Corporation
services
ShellExperienceHost 10.0.14393.447 (rs1_release_inmarket.161102-0100) 10.0.14393.447 Microsoft Corporation
sihost 10.0.14393.0 (rs1_release.160715-1616) 10.0.14393.0 Microsoft Corporation
smss
spoolsv
sqlwriter
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost
svchost 10.0.14393.0 (rs1_release.160715-1616) 10.0.14393.0 Microsoft Corporation
System
taskhostw 10.0.14393.0 (rs1_release.160715-1616) 10.0.14393.0 Microsoft Corporation
ToolbarUpdater
wininit
winlogon
WtuSystemSupport
WUDFHost
------------ END PROCESS LIST ------------
Users and Groups:
When I call getUsersAndGroups before getRunningProcesses the output of getUsersAndGroups is injected in getRunningProcesses and worse, no running processes are listed at all, but rather a lot of blank lines.
How can I separate or control the output of getUsersAndGroups so that it outputs before the output of getRunningProcesses?
The output of the injected output looks like this:
Running Processes:
------------ START PROCESS LIST ------------
Username Group
-------- -----
Administrator Administrators
debug255 Administrators;Hyper-V Administrators;Performance Log Users
DefaultAccount System Managed Accounts Group
Guest Guests
------------ END PROCESS LIST ------------
Thank you so much for your help!
tl; dr:
The underlying problem affects both Windows PowerShell and PowerShell (Core) 7+, up to at least v7.3.1, and, since it is a(n unfortunate) side effect of by-design behavior, may or may not get fixed.
To prevent output from appearing out of order, force synchronous display output, by explicitly calling Format-Table or Out-Host:
getUsersAndGroups | Format-Table
getRunningProcesses | Format-Table
Both Format-Table and Out-Host fix what is primarily a display problem, but they are suboptimal solutions in that they both interfere with providing in the output as data:
Format-Table outputs formatting instructions instead of data, which are only meaningful to PowerShell's for-display output-formatting system, namely when the output goes to the display or to one of the Out-* cmdlets, notably including Out-File and therefore also >. The resulting format is not suitable for programmatic processing.
Out-Host outputs no data at all and prints directly to the display, with no ability to capture or redirect it.
Relevant GitHub issues:
GitHub issue #4594: discussion of the surprising asynchronous behavior in general.
GitHub issue #13985: potential data loss when using the CLI.
Background information:
Inside a PowerShell session:
This is primarily a display problem, and you do not need this workaround for capturing output in a variable, redirecting it to a file, or passing it on through the pipeline.
You do need it for interactive scripts that rely on display output to show in output order, which notably includes ensuring that relevant information prints before an interactive prompt is presented; e.g.:
# !! Without Format-table, the prompt shows *first*.
[pscustomobject] #{ foo = 1; bar = 2 } | Format-Table
Read-Host 'Does the above look OK?'
From the outside, when calling the PowerShell CLI (powershell -file ... or powershell -command ...):
Actual data loss may occur if Out-Host is not used, because pending asynchronous output may never get to print if the script / command ends with exit - see GitHub issue #13985; e.g.:
# !! Prints only 'first'
powershell.exe -command "'first'; [pscustomobject] #{ foo = 'bar' }; exit"
However, unlike in intra-PowerShell-session use, Format-Table or Out-Host fix both the display and the data-capturing / redirection problem, because even Out-Host's output is sent to stdout, as seen by an outside caller (but note that the for-display representations that PowerShell's output-formatting system produces aren't generally suitable for programmatic processing).[1]
Note: All of the above equally applies to PowerShell (Core) 7+ and its pwsh CLI, up to at least v7.3.1.
The explanation of PowerShell's problematic behavior in this case:
It may helpful to demonstrate the problem with an MCVE (Minimal, Complete, and Verifiable Example):
Write-Host "-- before"
[pscustomobject] #{ one = 1; two = 2; three = 3 }
Write-Host "-- after"
In PSv5+, this yields:
-- before
-- after
one two three
--- --- -----
1 2 3
What happened?
The Write-Host calls produced output synchronously.
It is worth noting that Write-Host bypasses the normal success output stream and (in effect) writes directly to the console - mostly, even though there are legitimate uses, Write-Host should be avoided.
However, note that even output objects sent to the success output stream can be displayed synchronously, and frequently are, notably objects that are instances of primitive .NET types, such as strings and numbers, as well as objects whose implicit output formatting results in non-tabular output as well as types that have explicit formatting data associated with them (see below).
The implicit output - from not capturing the output from statement [pscustomobject] #{ one = 1; two = 2; three = 3 } - was unexpectedly not synchronous:
A blank line was initially produced.
All actual output followed the final Write-Host call.
This helpful answer explains why that happens; in short:
Implicit output is formatted based on the type of objects being output; in the case at hand, Format-Table is implicitly used.
In Psv5+, implicitly applied Format-Table now waits up to 300 msecs. in order to determine suitable column widths.
Note, however, that this only applies to output objects for whose type table-formatting instructions are not predefined; if they are, they determine the column widths ahead of time, and no waiting occurs.
To test whether a given type with full name <FullTypeName> has table-formatting data associated with it, you can use the following command:
# Outputs $true, if <FullTypeName> has predefined table-formatting data.
Get-FormatData <FullTypeName> -PowerShellVersion $PSVersionTable.PSVersion |
Where-Object {
$_.FormatViewDefinition.Control.ForEach('GetType') -contains [System.Management.Automation.TableControl]
}
Unfortunately, that means that subsequent commands execute inside that time window and may produce unrelated output (via pipeline-bypassing output commands such as Write-Host) or prompt for user input before Format-Table output starts.
When the PowerShell CLI is called from the outside and exit is called inside the time window, all pending output - including subsequent synchronous output - is effectively discarded.
The problematic behavior is discussed in GitHub issue #4594; while there's still hope for a solution, there has been no activity in a long time.
Note: This answer originally incorrectly "blamed" the PSv5+ 300 msec. delay for potentially surprising standard output formatting behavior (namely that the first object sent to a pipeline determines the display format for all objects in the pipeline, if table formatting is applied - see this answer).
[1] The CLI allows you to request output in a structured text format, namely the XML-based serialization format known as CLIXML, with -OutputFormat Xml. PowerShell uses this format behind the scenes for serializing data across processes, and it is not usually known to outside programs, which is why -OutputFormat Xml is rarely used in practice. Note that when you do use it, the Format-Table / Out-Host workarounds would again not be effective, given that the original output objects are lost.

CONFIG GET command is not allowed from script

I am working in a scenario with one Redis Master and several replicas, distributed in two cities, for geographic redundancy. My point is, for some reason, in a Lua script I need to know in which city the active instance is running. I thought, quite simple :
redis.call("config", "get", "bind"), and knowing the server IP I will determine the city. Not quite:
$ cat config.lua
redis.call("config", "get", "bind")
$ redis-cli --eval config.lua
(error) ERR Error running script (call to f_9bfbf1fd7e6331d0e3ec9e46ec28836b1d40ba35): #user_script:1: #user_script: 1: This Redis command is not allowed from scripts
Why is "config" not allowed from scripts? First, even though it's no deterministic, there are no write commands.
Second, I am using version 5.0.4, and from version 5 the replication is supposed to be done by effects and not by script propagation.
Any ideas?

Why isn't handles.exe discovering my DLL while ProcessExplorer can?

The problem:
On a windows server 2012 r2 box, I'm trying to use Chef to programmatically replace a .dll command component (aka a vb 6 library that I've registered on the box using regsvr32.exe) but when I try to copy over the file, the app pool of the website has a lock on it. I'm not sure if it matters, but the w3wp process is set to run as 32 bit via IIS.
My Solution (which isn't working):
In order to fix it, I was thinking about using a command line tool to find the reference to the dll and then recycling the app pool that's using it. Unfortunately, while I can get SysInternals' process explorer to find the dll, Handles.exe (the supposed command line version of process explorer) does not return anything. I was hoping that someone might be able to tell me how I was using handles incorrectly, or if there was a better tool for this.
Process Explorer - it has found my dll ComHelper.dll
Handles via command line - it has not found my dll ComHelper.dll
-- Edit --
This is the output of handles when I point it at w3wp while running as Admin
I would suspect you are running into access issues. Are you running Handle from an elevated command prompt ? Are you able to get any output covering handles in w3wp.exe (by using the pid of the process in handle.exe command line) ?
Looking at the handle enum output of w3wp.exe it seems,
listdll.exe -d ComHelper.dll
may be what you are looking for. Handle seems to be focused on files opened not dlls loaded. listdll is a tool that can be downloaded from sysinternals.
Alright so 32 bitness did matter. I ended up having to resort to powershell as opposed to trying to use handles. The code for finding a PID that has a lock on your file is scattered around the internet, but here's the link:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/12/01/weekend-scripter-determine-process-that-locks-a-file.aspx (it's marv the robot's answer at the bottom)
For the record, this is what was suggested
$lockedFile="C:\Windows\System32\acproxy.dll"
$isLocked = $false
Get-Process | foreach{
$processVar = $_;$_.Modules | foreach{
if($_.FileName -eq $lockedFile){
$isLocked = $true
$processVar.Name + " PID:" + $processVar.id
}
}
}
This is what I had translated it into with my powershell noobishness
$lockedFile = "E:\Components\___ComHelper.dll"
$list = Get-Process
foreach ($process in $list)
{
foreach ($module in $process.Modules)
{
if ($module.FileName -ne $lockedFile) { continue }
$process.Name + " PID:" + $process.Id
}
}

tcl tcltest unknown option -run

When I run ANY test I get the same message. Here is an example test:
package require tcltest
namespace import -force ::tcltest::*
test foo-1.1 {save 1 in variable name foo} {} {
set foo 1
} {1}
I get the following output:
WARNING: unknown option -run: should be one of -asidefromdir, -constraints, -debug, -errfile, -file, -limitconstraints, -load, -loadfile, -match, -notfile, -outfile, -preservecore, -relateddir, -singleproc, -skip, -testdir, -tmpdir, or -verbose
I've tried multiple tests and nothing seems to work. Does anyone know how to get this working?
Update #1:
The above error was my fault, it was due to it being run in my script. However if I run the following at a command line I got no output:
[root#server1 ~]$ tcl
tcl>package require tcltest
2.3.3
tcl>namespace import -force ::tcltest::*
tcl>test foo-1.1 {save 1 in variable name foo} {expr 1+1} {2}
tcl>echo [test foo-1.1 {save 1 in variable name foo} {expr 1+1} {2}]
tcl>
How do I get it to output pass or fail?
You don't get any output from the test command itself (as long as the test passes, as in the example: if it fails, the command prints a "contents of test case" / "actual result" / "expected result" summary; see also the remark on configuration below). The test statistics are saved internally: you can use the cleanupTests command to print the Total/Passed/Skipped/Failed numbers (that command also resets the counters and does some cleanup).
(When you run runAllTests, it runs test files in child processes, intercepting the output from each file's cleanupTests and adding them up to a grand total.)
The internal statistics collected during testing is available in AFACT undocumented namespace variables like ::tcltest::numTests. If you want to work with the statistics yourself, you can access them before calling cleanupTests, e.g.
parray ::tcltest::numTests
array set myTestData [array get ::tcltest::numTests]
set passed $::tcltest::numTests(Passed)
Look at the source for tcltest in your library to see what variables are available.
The amount of output from the test command is configurable, and you can get output even when the test passes if you add p / pass to the -verbose option. This option can also let you have less output on failure, etc.
You can also create a command called ::tcltest::ReportToMaster which, if it exists, will be called by cleanupTests with the pertinent data as arguments. Doing so seems to suppress both output of statistics and at least most resetting and cleanup. (I didn't go very far in investigating that method.) Be aware that messing about with this is more likely to create trouble than solve problems, but if you are writing your own testing software based on tcltest you might still want to look at it.
Oh, and please use the newer syntax for the test command. It's more verbose, but you'll thank yourself later on if you get started with it.
Obligatory-but-fairly-useless (in this case) documentation link: tcltest

Powershell 4.0 - plink and table-like data

I am running PS 4.0 and the following command in interaction with a Veritas Netbackup master server on a Unix host via plink:
PS C:\batch> $testtest = c:\batch\plink blah#blersniggity -pw "blurble" "/usr/openv/netbackup/bin/admincmd/nbpemreq -due -date 01/17/2014" | Format-Table -property Status
As you can see, I attempted a "Format-Table" call at the end of this.
The resulting value of the variable ($testtest) is a string that is laid out exactly like the table in the Unix console, with Status, Job Code, Servername, Policy... all that listed in order. But, it populates the variable in Powershell as just that: a vanilla string.
I want to use this in conjunction with a stored procedure on a SQL box, which would be TONS easier if I could format it into a table. How do I use Powershell to tabulate it exactly how it is extracted from the Unix prompt via Plink?
You'll need to parse it and create PS Objects to be able to use the format-* cmdlets. I do enough of it that I wrote this to help:
http://gallery.technet.microsoft.com/scriptcenter/New-PSObjectFromMatches-87d8ce87
You'll need to be able to isolate the data and write a regex to capture the bits you want.