Nagios Prescript Doesn't Work - windows

I've a problem with result of a *.cfg file, containing $prescript parameter, running by check_logfiles.exe.
My platform is MS Windows Server 2008 R2 64 bit.
I have to check in a dir, if there are *.err files. For do this job, i've write this powershell script:
$mypath="W:\nrpe\tmp\"
$logfile = $args
$logfile = Foreach-Object {$logfile -replace '\\', '_' -replace "__", "" -replace ":", ""}
$result = ls $args -Filter *.err|Measure-Object -Line | select -expand lines
echo "$result file/s present with .*err string"| out-file -filepath $mypath$logfile'.log' -append -encoding unicode
exit 0
I've chose to elaborate $logfile parameter, because i have to check more paths, and i want to use the same script.
This is the cfg file:
$scriptpath = 'C:\Windows\System32\WindowsPowerShell\v1.0';
$seekfilesdir = 'C:\nrpe\tmp';
$prescript = 'powershell.exe';
$prescriptparams = '-File C:\nrpe\libexec\check_err_file.ps1 \\\networkpath\FTP_Data\ExtraUE\Input';
$options = 'supersmartprescript';
$log='W:\nrpe\tmp\networkpath_FTP_Data_ExtraUE_Input';
#searches = (
{
tag => 'check_logfiles_test',
type => 'simple',
logfile => $log,
criticalpatterns => ['.*'],
criticalexceptions => ['0 file'],
options => 'count,noprotocol,noperfdata',
}
);
The $log file it's empity if i run checklogfiles:
C:\nrpe\libexec\check_logfiles -f C:\nrpe\cfg\check_logfiles_test.cfg
But if i Run powershell manually, it works correctly:
PS C:> C:\nrpe\libexec\check_err_file.ps1
\networkpath\FTP_Data\ExtraUE\Input
Content of W:\nrpe\tmp\networkpath_FTP_Data_ExtraUE_Input:
1 file/s present with .*err string
this is trace log:
Fri Feb 7 16:55:08 2014: call (smart) prescript powershell.exe
Fri Feb 7 16:55:08 2014: found script in C:\Windows\System32\WindowsPowerShell\v1.0/powershell.exe
Fri Feb 7 16:55:08 2014: execute C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File C:\nrpe\libexec\check_err_file.ps1 \\networkpath\FTP_Data\ExtraUE\Input
Fri Feb 7 16:57:50 2014: script said:
Fri Feb 7 16:57:50 2014: script powershell.exe exits with code 1
Fri Feb 7 16:57:50 2014: failed supersmart prescript. aborting...
ON Nagios this istance is in " CRITICAL : (Service Check Timed Out) "
Do you know what could be the problem?

Option to control how much time Nagios will allow various types of commands to execute before killing them off.
Option is available for controlling maximum time allotted for service checks. All values are in seconds.
/etc/nagios/nagios.cfg
service_check_timeout=180

Related

Powershell - Extract timestamp

i am completely new to Powershell and I am trying to create a script to extract the timestamp for the string found in a log file. There are log files everyday and it should select the latest file. It then looks for a string in that file. Now, where it finds the string it should also return a timestamp where the string is located. I am only able to complete the first part and struggling with the 2nd bit. My script is in no way optimal but it is a start. Any help is appreciated.
Set-Location -Path "O:\xyz\0502251\logs"
$latest = (Get-ChildItem -Path $dir -Filter 'async_SPARKLE_ONITE_*.log' | Sort-Object CreationDate -Descending | Select-Object -last 1).fullname
$pattern = "Successfulyl finished running psp_dba_maint_4"
$search = (Get-Content $latest | Select-String -Pattern "psp_dba_maint_4" | Select-Object -last 1)
if($search)
{
"The overnight completed at:"
}
else
{
"Do something"
}
This looks for the latest file and extracts the string. Now Just want to know at what time this log was generated.
The log is:
Connection 1
Server message: 2022-10-15 23:56:07:020
Message number: 0, Severity 10, State 1, Line 126
Procedure 'psp_dba_locklogin'
Message String: -----> login SPRK_SVC_IRISS logged in at 23:55:45 running SRI.exe:AWAITING COMMAND on rptSPARKLE from host da-pvrep02 is still active
Connection 1
Server message: 2022-10-15 23:56:07:020
Message number: 0, Severity 10, State 1, Line 126
Procedure 'psp_dba_locklogin'
Message String: -----> login SPRK_SVC_IRISS logged in at 23:55:45 running SRI.exe:AWAITING COMMAND on rptSPARKLE from host da-pvrep05 is still active
Connection 1
Server message: 2022-10-15 23:56:07:020
Message number: 0, Severity 10, State 1, Line 126
Procedure 'psp_dba_locklogin'
Message String: -----> login SPRK_SVC_IRISS logged in at 23:55:39 running SRI.exe:SELECT on rptSPARKLE from host da-pvrep02 is still active
Connection 1
Server message: 2022-10-15 23:56:07:020
Message number: 0, Severity 10, State 1, Line 126
Procedure 'psp_dba_locklogin'
Message String: -----> login SPARKLE_CAI logged in at 23:55:37 running SPARKLE ESB (pooled):AWAITING COMMAND on A_uatSPK from host DA-UVESB01 is still active
Connection 1
Server message: 2022-10-15 23:56:07:020
Message number: 0, Severity 10, State 1, Line 355
Procedure 'psp_dba_dbrefresh'
Message String: Setting PrivShield on SPRKSZCBS OUT OF maintenance mode
Connection 1
Server message: 2022-10-15 23:56:07:022
Message number: 0, Severity 10, State 1, Line 362
Procedure 'psp_dba_dbrefresh'
Message String:
Connection 1
Server message: 2022-10-15 23:56:07:022
Message number: 0, Severity 10, State 1, Line 364
Procedure 'psp_dba_dbrefresh'
Message String: - Refresh 2 complete
Connection 1
Server message: 2022-10-15 23:56:07:028
Message number: 0, Severity 10, State 1, Line 42
Procedure 'psp_dba_maint_4'
Message String: Successfulyl finished running psp_dba_maint_4
This has different values in files generated everyday. So it should look for the latest file and return the result as The overnight completed at: 23:56.
Here is a variant using the switch statement to efficiently process the file line-by-line and test each line to match given RegEx patterns:
$found = switch -File $latest -RegEx {
'\d\d:\d\d' { $timestamp = $matches[0] }
'Successfulyl finished running psp_dba_maint_4' { $true; break }
}
if( $found ) {
"The overnight completed at: $timestamp"
}
else {
"Not found"
}
$found = switch ... assigns the output of the switch statement to the variable. The output will be $true if the pattern has been found.
\d\d:\d\d searches for the time (first occurence of a pair of two digits separated by :) within the current line. The automatic variable $matches[0] then gives the matched value, similar to the RegEx -match operator. For a detailed explanation of the RegEx pattern and the ability to experiment with it, see this Regex101.com page.
Although there is no $false output of the switch statement, an empty output evaluates to $false in a boolean context (in this case the if statement), so if the pattern isn't found, the else branch will be entered.
There is a typo in Successfulyl which I just copied from your example ;)
To complement zett42's helpful switch-based answer:
A Select-String solution, as you attempted, is possible, via the -Context parameter, which allows you to capture the lines surrounding a matching line as well:
$time =
Select-String -LiteralPath $latest -Pattern 'psp_dba_maint_4' -Context 3 |
Select-Object -Last 1 |
ForEach-Object {
# Extract and output the 'HH:mm' part of the timestamp from
# the 3rd line above the match (the first element in the pre-context array)
$_.Context.PreContext[0] -replace '^.+ (..:..).+$', '$1'
}
if ($time) {
"The overnight completed at: $time"
} else {
'Do something'
}
Note:
It is much more efficient to pass the file path of the target file to Select-String, via -LiteralPath, than it is to pass the file's content, line by line, via Get-Content.
If you had assigned the whole file-info object (System.IO.FileInfo), as emitted by Get-ChildItem, to $latest, you could alternatively have provided it via the pipeline: $latest | Select-String ...
The type of the match-information objects that Select-String emits is Microsoft.PowerShell.Commands.MatchInfo.
The regex-based -replace operator is used to extract (part of) the time-of-day string from the context line.
For an explanation of the above regex (and substitution, where $1 refers to the first and only capture group, (...)), see this regex101.com page.
As you need to get the Time information only related to the procedure psp_dba_maint_4 you can do:
#Remove empty lines, join strings and split string at "connection 1" = you keep the related information together. Next parse the array of strings for the string which matches "psp_dba_maint_4" and after that extract dateTime
$null = (((Get-Content $latest | ?{$_}) -join $null) -split "connection 1" | ?{$_ -match "psp_dba_maint_4"}) -match '\d{2}:\d{2}:\d{2}'
$Search = $matches[0]
if($search){
"The overnight completed at: $search"
}
else{
"Do something"
}
Alternatively you could parse the log an create objects, e.g.:
$obj = #(
Get-Content $latest | ?{$_} | %{
#If string is connection 1 initialize hashtable/create object
If ($_ -match 'connection 1'){
If ($attrsHT){
new-object -typename psobject -Property $attrsht
}
$attrsHt = #{}
}
Else {
#replace Procedure with Procedure, replace ": " with | and split at |
$split = (($_ -replace "Procedure","Procedure:") -replace ": ","|") -split "\|"
#add key and value to hashtable
$attrsht.add($split[0],$split[1])
}
}
)
gives you the array $obj containing the loginformation:
$obj[0] | fl *
Procedure : 'psp_dba_locklogin'
Message String : -----> login SPRK_SVC_IRISS logged in at 23:55:45 running SRI.exe:AWAITING COMMAND on
rptSPARKLE from host da-pvrep02 is still active
Server message : 2022-10-15 23:56:07:020
Message number : 0, Severity 10, State 1, Line 126
Here's another solution to add to the rest.
if ($found = Get-Content -Path $latest -ReadCount 7 | %{
if ($_ -match 'Setting PrivShield on SPRKSZCBS OUT OF maintenance mode')
{
[regex]::Match($_,'\d\d:\d\d').Value
}
}
) { "The overnight completed at: $found" }
else { 'not found' }
On another note, $latest contains the oldest file and not the newest. Specifying -Descending in your Sort-Object brings the most current files to the top. So, when you select the last one via -Last 1, that is the oldest file and not the newest.

Not able to exit from the powershell console after script execution

I am trying to create a script for my class to automatically create a folder monthDay wise and open it in Visual Studio Code. However, after the script executes the powershell console remains open until I close it manually or I close VSCode. I just want the console to go away after it executes. Here is the script: Please tell me how to do it..
# Hash table for months
$hash_month = #{1="jan";2="feb";3="mar";4="apr";5="may";6="june";7="july";8="aug";9="sep";10="oct";11="nov";12="dec"}
#extracting date
$date = (Get-Date).Day
#extracing month
$month = (Get-Date).Month
# getting month name from the hash table
$month_name= $hash_month[$month]
# Creating the Directory with monthDate
# This command will create a dir if it does not exist, or it will simply not execute if the directory exists
[System.IO.Directory]::CreateDirectory("$month_name$date")
# changing dir
cd $month_name$date
# opening the dir in vscode
code .
# currently not able to exit from console after execution of script
exit 0
I have attached the screenshot of the window, I just want the console to go away but NOT vscode.
Powershell and VSCode Screenshot
I made 2 changes here:
The path creation is handled differently, which has nothing to do with the question, but your way was not creating the path for me.
Used Start-Process with hidden window to instantiate VSCode and make the $pid kill method work.
Full script:
# Hash table for months
$hash_month = #{1 = "jan"; 2 = "feb"; 3 = "mar"; 4 = "apr"; 5 = "may"; 6 = "june"; 7 = "july"; 8 = "aug"; 9 = "sep"; 10 = "oct"; 11 = "nov"; 12 = "dec" }
#extracting date
$date = (Get-Date).Day
#extracing month
$month = (Get-Date).Month
# getting month name from the hash table
$month_name = $hash_month[$month]
# Creating the Directory with monthDate
# This command will create a dir if it does not exist, or it will simply not execute if the directory exists
$path = $month_name + $date
if (!(Test-Path $path)) {
New-Item $path -ItemType Directory
}
# # changing dir
cd $path
# # opening the dir in vscode with Start-Process
Start-Process -FilePath "code" -ArgumentList "." -WindowStyle Hidden
# # currently not able to exit from console after execution of script
Stop-Process $pid

how to fetch logs content between two dates in windows powershell?

In our project, we are getting AppDynamics logs(application logs) and machine logs and sometime the the size of the logs increase which eats out the disk size. What I am trying to do it is to get the content between two dates like 10 Nov and 13 Nov and delete the rest. Since we are working in windows environment, this needs to be done in powershell. It is easier to handle such things in linux but I am not good at powershell scripting. Below is the code snippet.
[AD Thread-Metric Reporter1] 10 Nov 2019 14:47:32,899 ERROR ManagedMonitorDelegate - Error sending metrics - will requeue for later transmission
com.singularity.ee.agent.commonservices.metricgeneration.metrics.MetricSendException: Connection back off limitation in effect: /controller/instance/702/metrics
at com.singularity.ee.agent.commonservices.metricgeneration.AMetricSubscriber.publish(AMetricSubscriber.java:350)
at com.singularity.ee.agent.commonservices.metricgeneration.MetricReporter.run(MetricReporter.java:113)
at com.singularity.ee.util.javaspecific.scheduler.AgentScheduledExecutorServiceImpl$SafeRunnable.run` ]
[AD Thread-Metric Reporter1] 11 Nov 2019 14:46:32,899 ERROR ManagedMonitorDelegate - Error sending metrics - will requeue for later transmission
com.singularity.ee.agent.commonservices.metricgeneration.metrics.MetricSendException: Connection back off limitation in effect: /controller/instance/702/metrics
at com.singularity.ee.agent.commonservices.metricgeneration.AMetricSubscriber.publish(AMetricSubscriber.java:350)
at com.singularity.ee.agent.commonservices.metricgeneration.MetricReporter.run(MetricReporter.java:113)
at com.singularity.ee.util.javaspecific.scheduler.AgentScheduledExecutorServiceImpl$SafeRunnable.run` ]
[extension-scheduler-pool-5] 13 Nov 2019 18:45:40,634 INFO ReportMetricsConfigSupplier - Basic metrics will be collected and reported through the SIM extension because SIM is enabled.
[extension-scheduler-pool-8] 14 Nov 2019 18:47:18,650 INFO ReportMetricsConfigSupplier - Basic metrics will be collected and reported through the SIM extension because SIM is enabled.` ]
Code Snippet with file paths
# Get Start Time
$startDTM = (Get-Date)
$zstart = Read-Host -prompt '
Enter your start date in "10 Nov" format. Start date must be earlier than stop date.'
$zstop = Read-Host -prompt 'Enter your stop date in "13 Nov" format. Stop date must be later than start date.'
# $zstart = '10 Nov'
# $zstop = '13 Nov'
$zstart= Select-String $zstart "$env:userprofile\Desktop\machine-log.txt" | Select-Object -ExpandProperty LineNumber
$zstop= Select-String $zstop "$env:userprofile\Desktop\machine-logtxt" | Select-Object -ExpandProperty LineNumber
$AppLog = gc $env:userprofile\Desktop\machine-log.txt
$i = 0
$array = #()
foreach ($line in $AppLog){
foreach-object { $i++ }
if (($i -ge $zstart) -and ($i -le $zstop))
{$array += $line}}
$array | Out-File -encoding ascii -filepath $env:userprofile\Desktop\logfile-output.txt
The ERROR i get while executing the script.
8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943
8944 8945 8946 8947 8948". Error: "Cannot convert the "System.Object[]" value of type "System.Object[]" to
type "System.Int32"."
At C:\Users\xa_abbasmn\Documents\Logs\test.ps1:13 char:5
+ if (($i -ge $zstart) -and ($i -le $zstop))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : ComparisonFailure
Could not compare "18" to "1 15 16 17 31 45 46 47 48 62 76 77 91 105 106 107 121 135 136 137 151 152 196 210
211 225 239 240 241 255 269 270 271 285 299 300 314 315 329 330 331 332 346 390 404 447 448 449 463 477 478
492 506 507 508 522 536 537 538 552 566 567 581 582 583 627 641 642 643 657 671 685 686 687
The powershell and windows version:
Name: Windows PowerShell ISE Host - Version : 5.1.14409.1018
Name: Microsoft Windows Server 2012 R2 Standard 64bit
your help will be highly obliged.
Best regards,
Windows 10 64-bit. Powershell 5. Does not require admin privileges.
How to quickly and efficiently extract text from a large logfile from input1 to input2 using powershell 5?
Sample logfile below.
For testing purposes copy your logfile to the desktop and name it logfile.txt
What is the default text editor in Windows Server 2012 R2 Standard 64-bit? See line 42.
What program do you have associated with .txt files? See line 42.
# Get Start Time
$startDTM = (Get-Date)
$zstart = Read-Host -prompt '
Enter your start date in "10 Nov" format (w/o quotes). Start date must be earlier than stop date.'
$zstop = Read-Host -prompt 'Enter your stop date in "13 Nov" format (w/o quotes). Stop date must be later than start date.'
# $zstart = '10 Nov'
# $zstop = '13 Nov'
$zstart= Select-String $zstart "$env:userprofile\Desktop\logfile.txt" | Select-Object -ExpandProperty LineNumber
$zstop= Select-String $zstop "$env:userprofile\Desktop\logfile.txt" | Select-Object -ExpandProperty LineNumber
$AppLog = gc $env:userprofile\Desktop\logfile.txt
$i = 0
$array = #()
foreach ($line in $AppLog){
foreach-object { $i++ }
if (($i -ge $zstart) -and ($i -le $zstop))
{$array += $line}}
$array | Out-File -encoding ascii -filepath $env:userprofile\Desktop\logfile-edited.txt
# begin get file size
$y = (Get-ChildItem "$env:userprofile\Desktop\logfile.txt" | Measure-Object -property length -sum)
$y = [System.Math]::Round(($y.Sum /1KB),2)
$z = (Get-ChildItem "$env:userprofile\Desktop\logfile-edited.txt" | Measure-Object -property length -sum)
$z = [System.Math]::Round(($z.Sum /1KB),2)
# end get file size
# get Stop Time
$endDTM = (Get-Date)
Write-Host "
Extracted $z KB from $y KB. The extraction took $(($endDTM-$startDTM).totalseconds) seconds"
start-process -wait notepad $env:userprofile\Desktop\logfile-edited.txt
remove-item $env:userprofile\Desktop\logfile-edited.txt
exit
logfile.txt:
[AD Thread-Metric Reporter1] 09 Nov 2019 14:48:32,899 ERROR ManagedMonitorDelegate - Error sending metrics
com.singularity.ee.agent.commonservices.metricgeneration.metrics.MetricSendException: Connection back off limitation
at com.singularity.ee.agent.commonservices.metricgeneration.AMetricSubscriber.publish(AMetricSubscriber.java:350)
at com.singularity.ee.agent.commonservices.metricgeneration.MetricReporter.run(MetricReporter.java:113)
at com.singularity.ee.util.javaspecific.scheduler.AgentScheduledExecutorServiceImpl$SafeRunnable.run ]
[AD Thread-Metric Reporter1] 10 Nov 2019 14:47:32,899 ERROR ManagedMonitorDelegate - Error sending metrics
com.singularity.ee.agent.commonservices.metricgeneration.metrics.MetricSendException: Connection back off limitation
at com.singularity.ee.agent.commonservices.metricgeneration.AMetricSubscriber.publish(AMetricSubscriber.java:350)
at com.singularity.ee.agent.commonservices.metricgeneration.MetricReporter.run(MetricReporter.java:113)
at com.singularity.ee.util.javaspecific.scheduler.AgentScheduledExecutorServiceImpl$SafeRunnable.run ]
[AD Thread-Metric Reporter1] 11 Nov 2019 14:46:32,899 ERROR ManagedMonitorDelegate - Error sending metrics
com.singularity.ee.agent.commonservices.metricgeneration.metrics.MetricSendException: Connection back off limitation
at com.singularity.ee.agent.commonservices.metricgeneration.AMetricSubscriber.publish(AMetricSubscriber.java:350)
at com.singularity.ee.agent.commonservices.metricgeneration.MetricReporter.run(MetricReporter.java:113)
at com.singularity.ee.util.javaspecific.scheduler.AgentScheduledExecutorServiceImpl$SafeRunnable.run ]
[extension-scheduler-pool-5] 13 Nov 2019 18:45:40,634 INFO ReportMetricsConfigSupplier - Basic metrics will be collected
[extension-scheduler-pool-8] 14 Nov 2019 18:47:18,650 INFO ReportMetricsConfigSupplier - Basic metrics will be collected
Results of running script on logfile.txt:
[AD Thread-Metric Reporter1] 10 Nov 2019 14:47:32,899 ERROR ManagedMonitorDelegate - Error sending metrics
com.singularity.ee.agent.commonservices.metricgeneration.metrics.MetricSendException: Connection back off limitation
at com.singularity.ee.agent.commonservices.metricgeneration.AMetricSubscriber.publish(AMetricSubscriber.java:350)
at com.singularity.ee.agent.commonservices.metricgeneration.MetricReporter.run(MetricReporter.java:113)
at com.singularity.ee.util.javaspecific.scheduler.AgentScheduledExecutorServiceImpl$SafeRunnable.run ]
[AD Thread-Metric Reporter1] 11 Nov 2019 14:46:32,899 ERROR ManagedMonitorDelegate - Error sending metrics
com.singularity.ee.agent.commonservices.metricgeneration.metrics.MetricSendException: Connection back off limitation
at com.singularity.ee.agent.commonservices.metricgeneration.AMetricSubscriber.publish(AMetricSubscriber.java:350)
at com.singularity.ee.agent.commonservices.metricgeneration.MetricReporter.run(MetricReporter.java:113)
at com.singularity.ee.util.javaspecific.scheduler.AgentScheduledExecutorServiceImpl$SafeRunnable.run ]
[extension-scheduler-pool-5] 13 Nov 2019 18:45:40,634 INFO ReportMetricsConfigSupplier - Basic metrics will be collected
Powershell in four hours at Youtube
Parse and extract text with powershell at Bing
How to quickly and efficiently extract text from a large logfile from line x to line y using powershell 5?
How to quickly and efficiently extract text from a large logfile from date1 to date2 using powershell 5?

How do I run a PowerShell command from groovy the same way as "cmd /c <command>".execute()?

In Groovy I can run the Windows cmd shell directly and read the result like this:
def proc = "cmd /c dir".execute()
proc.wait()
println "stdout: ${proc.in.text}"
However, if I try this with PowerShell it blocks and won't return:
def proc = "powershell dir".execute()
I have tried
def proc = "powershell -NonInteractive dir".execute()
etc. - but they all block and I have to kill the Groovy script.
What's the equivalent of the /c switch for cmd that you use with PowerShell to get the result to return to the script.
Use the -command parameter:
powershell -command "dir"
You can use the List form:
['powershell', '-command', 'dir'].execute()
I used a Groovy class to execute a PowerShell script. This is a little more elaborate than just executing a command, but I thought it might be helpful.
import groovy.util.logging.Log4j
import org.springframework.stereotype.Component
#Component
#Log4j
class PowerShellUtil {
def exec(debug, command, args){
def powerShellCommand = ".\\${command} ${args}"
def shellCommand = "powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -Command \"${powerShellCommand}\""
if (debug) log.debug powerShellCommand
def process = shellCommand.execute()
def out = new StringBuffer()
def err = new StringBuffer()
process.consumeProcessOutput(out, err)
process.waitFor()
if(out.size() > 0 && debug) log.debug out
if(err.size() > 0) log.error err
}
}
Then I can execute the script with:
PowerShellUtil psUtil = new PowerShellUtil()
psUtil.exec(true, 'script.ps1','script-args')
Use this:
powershell -command dir
For a simple command like list directory:
powershell -command ls
For making a PowerShell script run in cmd you should use an encoded command like:
$script = {Get-EventLog -LogName System -Newest 10 | where { $_.Index -ge 5071811 } | sort Index}
then:
[System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes( $script))
RwBlAHQALQBFAHYAZQBuAHQATABvAGcAIAAtAEwAbwBnAE4AYQBtAGUAIABTAHkAcwB0AGUAbQAgAC0ATgBlAHcAZQBzAHQAIAAxADAAIAB8ACAAdwBoAGU
AcgBlACAAewAgACQAXwAuAEkAbgBkAGUAeAAgAC0AZwBlACAANQAwADcAMQA4ADEAMQAgAH0AIAB8ACAAcwBvAHIAdAAgAEkAbg
My result:
C:\Users\soheil>powershell -encodedcommand RwBlAHQALQBFAHYAZQBuAHQATABvAGcAIAAtA
EwAbwBnAE4AYQBtAGUAIABTAHkAcwB0AGUAbQAgAC0ATgBlAHcAZQBzAHQAIAAxADAAIAB8ACAAdwBoA
GUAcgBlACAAewAgACQAXwAuAEkAbgBkAGUAeAAgAC0AZwBlACAANQAwADcAMQA4ADEAMQAgAH0AIAB8A
CAAcwBvAHIAdAAgAEkAbgBkAGUAeAA=
Index Time EntryType Source InstanceID Message
----- ---- --------- ------ ---------- -------
5071812 Mar 10 22:39 Information Service Control M... 1073748860 The Mul...
5071813 Mar 10 22:40 Information Service Control M... 1073748860 The App...
5071814 Mar 10 22:45 Information Service Control M... 1073748860 The Mul...
5071815 Mar 10 22:48 Information Service Control M... 1073748860 The Dia...
5071816 Mar 10 22:55 Information Service Control M... 1073748860 The Mul...
5071817 Mar 10 22:58 Information Service Control M... 1073748860 The Mul...
5071818 Mar 10 22:59 Information Service Control M... 1073748860 The Goo...
5071819 Mar 10 22:59 Information Service Control M... 1073748860 The Goo...
5071820 Mar 10 23:14 Information Service Control M... 1073748860 The Mul...
5071821 Mar 10 23:30 Information Service Control M... 1073748860 The Mul...

How to display the Current Month in Plain Text Format?

Any suggestions on how I can quickly print the current month of a calendar in plain text to the clipboard or to the command in the a windows environment? To be clear here, I would like to see the full printed month, similar to what you see when you single click on the clock in the windows taskbar. I'm thinking along the lines of a a lightweight PowerShell script or perhaps there is some other pre-packaged Windows application functionality that would allow me to do this easily.
Give this a try:
function Get-Calendar($year=(Get-Date).Year,$month=(Get-Date).Month){
$dtfi = New-Object System.Globalization.DateTimeFormatInfo
$AbbreviatedDayNames=$dtfi.AbbreviatedDayNames | ForEach-Object {" {0}" -f $_.Substring(0,2)}
$header= "$($dtfi.MonthNames[$month-1]) $year"
$header=(" "*([math]::abs(21-$header.length) / 2))+$header
$header+=(" "*(21-$header.length))
Write-Host $header -BackgroundColor yellow -ForegroundColor black
Write-Host (-join $AbbreviatedDayNames) -BackgroundColor cyan -ForegroundColor black
$daysInMonth=[DateTime]::DaysInMonth($year,$month)
$dayOfWeek =(New-Object DateTime $year,$month,1).dayOfWeek.value__
$today=(Get-Date).Day
for ($i = 0; $i -lt $dayOfWeek; $i++){Write-Host (" "*3) -NoNewline}
for ($i = 1; $i -le $daysInMonth; $i++)
{
if($today -eq $i){Write-Host ("{0,3}" -f $i) -NoNewline -BackgroundColor red -ForegroundColor white}
else {Write-Host ("{0,3}" -f $i) -NoNewline -BackgroundColor white -ForegroundColor black}
if ($dayOfWeek -eq 6) {Write-Host}
$dayOfWeek = ($dayOfWeek + 1) % 7
}
if ($dayOfWeek -ne 0) {Write-Host}
}
PS> Get-Calendar
January 2013
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
A calendar (a system for breaking a linear date into day/month/year) doesn't have a current anything.
But if you mean get the month of a DateTime in a given calendar you need to look at specifying a CultureInfo which in .NET incorporates a selected calendar:
$d = Get-Date
$d.ToString('MMMM', [System.Globalization.CultureInfo]::CurrentCulture)
There are a number of ways to create a custom CultureInfo or (more generally) an instance of DateTimeFormatInfo and passing as the second parameter of DateTime.ToString().
The simplest approach is to get an instance of CultureInfo that uses the target calender, eg.:
$ci = [System.Globalization.CultureInfo]::CreatedSpecifiedCulture('jp-jp')
MSDN has a whole page on working with calendars: http://msdn.microsoft.com/en-us/library/82aak18x%28v=vs.100%29.aspx (this is the .NET 4 version for PowerShell 3).
new-alias Out-Clipboard $env:SystemRoot\system32\clip.exe
(get-date -Format MMMM) |Out-Clipboard

Resources