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

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?

Related

Using Powershell [DateTime]::ParseExact - Funny Strings?

Good afternoon Powershell wizards!
I am hoping someone can explain to me how I can fix this issue, and more importantly what the issue actually is!
I'm attempting to fix an old script I wrote years ago that searches for several dates on a files properties and picks one to use for renaming that file.
The issue I'm having is that when I use parseExact it fails for the date strings read from the files... but it works if I manually type the same string into powershell!
Please note that this script is only going to be ran on my PC and only needs to work with dates from my files formats so I'm not too worried about use of $null unless it's related.
See example below:
Write-Host "TEST 1"
$DateTime = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime # WORKS!
Write-Host "TEST 2"
$DateTime2 = [DateTime]::ParseExact("‎24‎07‎2021‏1515","ddMMyyyyHHmm",$null)
Write-Host $DateTime2 # FAILS!
Looks the same right?
Here is a more real world example of what I'm up to that fails
$file = Get-Item "C:\SomeFolder\somefile.jpg"
$shellObject = New-Object -ComObject Shell.Application
$directoryObject = $shellObject.NameSpace( $file.Directory.FullName )
$fileObject = $directoryObject.ParseName( $file.Name )
$property = 'Date taken'
for(
$index = 5;
$directoryObject.GetDetailsOf( $directoryObject.Items, $index ) -ne $property;
++$index) { }
$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)
Write-Host $photoDate # <-- This reads ‎03/‎08/‎2021 ‏‎09:15
$output = [DateTime]::ParseExact($photoDate,"dd/MM/yyyy HH:mm",$null) # <-- This fails
Write-Host $output
# If i manually type in here it works.... If I copy and paste from the Write-Host it fails...
$someInput = "03/08/2021 09:15"
$workingOutput = [DateTime]::ParseExact($someInput,"dd/MM/yyyy HH:mm",$null)
Write-Host $workingOutput
For anyone else who comes across this, it seems like there are invisible characters being added. Thanks for the spot #SantiagoSquarzon
This fixes it for my particular purposes:
$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)
$utfFree = $photoDate -replace "\u200e|\u200f", ""
I ran into this issue when I started exploring metadata with PowerShell. My solution was to create a regex "inverted whitelist" character class and delete (replace with '') all non-whitelist characters.
But then I learned of an alternate method avaiable to FolderItem obejcts: the ExtenedProperty() method.
Gets the value of a property from an item's property set. The property can be specified either by name or by the property set's format identifier (FMTID) and property identifier (PID).
It's primary strength being the feturn type corresponds to the property value type:
When this method returns, contains the value of the property, if it exists for the specified item. The value will have full typing—for example, dates are returned as dates, not strings.
Using this method to access date properties eliminates string parsing and the issues you encountered:
PS Pictures> $FileInfo = Get-Item "C:\Users\keith\Pictures\Leland\2009\Leland 191.JPG"
PS Pictures> $Shell = New-Object -ComObject shell.application
PS Pictures> $comFolder = $Shell.NameSpace($FileInfo.DirectoryName)
PS Pictures> $comFile = $comFolder.ParseName($FileInfo.Name)
PS Pictures>
PS Pictures> $comFolder.GetDetailsOf($null,12)
Date taken
PS Pictures> $comFolder.GetDetailsOf($comFile,12)
‎9/‎5/‎2009 ‏‎2:06 PM
PS Pictures> $comFolder.GetDetailsOf($comFile,12).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS Pictures> $comFile.ExtendedProperty("DateTaken")
PS Pictures> $comFile.ExtendedProperty("System.Photo.DateTaken")
Saturday, September 5, 2009 07:06:41 PM
PS Pictures> $comFile.ExtendedProperty("System.Photo.DateTaken").GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType
It also returns arrays for properties than can contain multiple values (Tags, Contributing Artists, etc/):
PS Pictures> $comFolder.GetDetailsOf($null,18)
Tags
PS Pictures> $comFolder.GetDetailsOf($comFile,18)
Leland; Tim; Jorge
PS Pictures> $comFolder.GetDetailsOf($comFile,18).GetTYpe()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS Pictures> $comFile.ExtendedProperty("System.KeyWords")
PS Pictures> $comFile.ExtendedProperty("System.Keywords")
Leland
Tim
Jorge
PS Pictures> $comFile.ExtendedProperty("System.Keywords").GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String[] System.Array
But GetDetailsOf() is still useful, particularly for values that use an EnumList:
PS Pictures> $comFolder.GetDetailsOf($null,261)
Flash mode
PS Pictures> $comFolder.GetDetailsOf($comFile,261)
No flash, auto
PS Pictures> $comFile.ExtendedProperty("System.Photo.Flash")
24
Yeah something weird is going on with that string. (paste with control v in the console) It doesn't display right in stackoverflow, but ascii only goes up to code 0x7f (127). You can see the 200e and 200f hex codes. They look like little hooks. (emoji's would require extra handling with the surrogate characters)
$string = '# <-- This reads ‎03/‎08/‎2021 ‏‎09:15'
function chardump {
param($string)
[char[]]$string |
% { [pscustomobject]#{Char = $_; Code = [int]$_ | % tostring x} }
}
chardump $string
Char Code
---- ----
# 23
20
< 3c
- 2d
- 2d
20
T 54
h 68
i 69
s 73
20
r 72
e 65
a 61
d 64
s 73
20
‎ 200e
0 30
3 33
/ 2f
‎ 200e
0 30
8 38
/ 2f
‎ 200e
2 32
0 30
2 32
1 31
20
‏ 200f
‎ 200e
0 30
9 39
: 3a
1 31
5 35
chardump $string | ? {[int]('0x' + $_.code) -gt 0x7f}
Char Code
---- ----
‎ 200e
‎ 200e
‎ 200e
‏ 200f
‎ 200e

Organizing the output of shell script into tables within the text file

I am working with a unix shell script which have an output of script like below code:
EVENT DATE: 2019-05-12
TrapLogId Severity EventTime Model Description
1604 [major] 05:59:50 14 Network Interface Down: service 1-16
1605 [major] 05:59:51 14 Network Interface Down: service 1-15
EVENT DATE: 2019-05-13
TrapLogId Severity EventTime Model Description
1619 [minor] 07:58:50 30 Delayed Subscriber Mapping
1620 [minor] 08:03:49 79 Failed Reload: File syntax
1621 [clear] 08:04:49 79 Failed Reload Cleared: File syntax
1622 [clear] 08:28:50 30 Delayed Subscriber Mapping Cleared
EVENT DATE: 2019-05-15
TrapLogId Severity EventTime Model Description
1627 [minor] 01:43:58 22 Misconfigured Network Awareness: 10.1.17.0/24
1628 [clear] 01:48:58 22 Misconfigured Network Awareness Cleared
Im trying to organize it into table like this format :
EVENT DATE TrapLogId Severity EventTime Model Description
2019-05-12 1604 [major] 05:59:50 14 Network Interface Down: service 1-16
2019-05-12 1605 [major] 05:59:51 14 Network Interface Down: service 1-15
2019-05-13 1619 [minor] 07:58:50 30 Delayed Subscriber Mapping
2019-05-13 1620 [minor] 08:03:49 79 Failed Reload: File syntax
2019-05-13 1621 [clear] 08:04:49 79 Failed Reload Cleared: File syntax
2019-05-13 1622 [clear] 08:28:50 30 Delayed Subscriber Mapping Cleared
2019-05-15 1627 [minor] 01:43:58 22 Misconfigured Network Awareness: 10.1.17.0/24
2019-05-15 1628 [clear] 01:48:58 22 Misconfigured Network Awareness Cleared
how to parse it ? how to export it into table using shell ?
the code i want to organize into table has:
event date 1
header
content 1
event date 2
header
content 2
etc
i want it as
event date (as part of the header) header
content 1
content 2
content 3
You can pipe your script to:
awk 'BEGIN {
print "EVENT DATE TrapLogId Severity EventTime Model Description"
print
}
/EVENT DATE/ {date=$3}
match($3, "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]") {
printf( "%-14s%-14s%-13s%-12s%-3s", date, $1, $2, $3, $4)
for(i=1;i<=4;i++) $i=""
print
}
'
$ cat tst.awk
BEGIN { OFS="\t"; dateTag="EVENT DATE" }
{ gsub(/^[[:space:]]+|[[:space:]]+$/,"") }
/^[^0-9]/ {
if ( $0 ~ dateTag ) {
date = $NF
}
else if ( !doneHdr++ ) {
numCols = NF
gsub(/[[:space:]]+/,OFS)
print dateTag, $0
}
}
/^[0-9]/ {
rest = desc = $0
sub("([[:space:]]+[^[:space:]]+){"(NF-numCols)+1"}$","",rest)
sub("^([^[:space:]]+[[:space:]]+){"numCols-1"}","",desc)
gsub(/[[:space:]]+/,OFS,rest)
print date, rest, desc
}
.
$ awk -f tst.awk file | column -s$'\t' -t
EVENT DATE TrapLogId Severity EventTime Model Description
2019-05-12 1604 [major] 05:59:50 14 Network Interface Down: service 1-16
2019-05-12 1605 [major] 05:59:51 14 Network Interface Down: service 1-15
2019-05-13 1619 [minor] 07:58:50 30 Delayed Subscriber Mapping
2019-05-13 1620 [minor] 08:03:49 79 Failed Reload: File syntax
2019-05-13 1621 [clear] 08:04:49 79 Failed Reload Cleared: File syntax
2019-05-13 1622 [clear] 08:28:50 30 Delayed Subscriber Mapping Cleared
2019-05-15 1627 [minor] 01:43:58 22 Misconfigured Network Awareness: 10.1.17.0/24
2019-05-15 1628 [clear] 01:48:58 22 Misconfigured Network Awareness Cleared

Windows / NTFS: Two files with identical long-names in the same directory?

I have been a lurker at stackoverflow.com for many years (great site and users here), but never had the need to ask a question. Now the time has come :-) Let me begin:
OS: x64 Windows 8.0 to Windows 10 (15063.14) (the issue exists since years, but I have never pursued it fully yet, so we can exclude that it is specific to a specific Windows version)
FS: NTFS
Issue: 2 files with the same (long) name in the same directory and I cannot figure out how this is even possible. This happens to me since years whenever I manually upgrade my Email client. The main .EXE file of it (MailClient.exe) is never asking for replacement if copying the new one over to the same directory. Instead they are both placed there, with the exact same long name.
The issue has nothing to do with a specific directory, I can copy around both .EXE files to freshly created directories on the NTFS drive without issues (also getting no "overwrite" question there).
Let me show you:
C:\temp\2>dir
Volume in drive C is SSD 840 Pro
Volume Serial Number is 0C6D-D489
Directory of C:\temp\2
13.04.2017 02:29 <DIR> .
13.04.2017 02:29 <DIR> ..
21.10.2016 17:10 24.742.760 MailClient.exe
27.12.2016 03:26 24.911.872 MailCliеnt.exe
2 File(s) 49.654.632 bytes
2 Dir(s) 78.503.038.976 bytes free
However, if doing a dir /x, this comes up:
C:\temp\2>dir /x
Volume in drive C is SSD 840 Pro
Volume Serial Number is 0C6D-D489
Directory of C:\temp\2
13.04.2017 02:29 <DIR> .
13.04.2017 02:29 <DIR> ..
21.10.2016 17:10 24.742.760 MAILCL~2.EXE MailClient.exe
27.12.2016 03:26 24.911.872 MAILCL~1.EXE MailCliеnt.exe
2 File(s) 49.654.632 bytes
2 Dir(s) 78.503.038.976 bytes free
So they obviously have a different 8.3 name, OK, but the exact same long name. Here is another screenshot of the situation. Both files show the same location within the Windows "properties" dialog (right click) too. Unfortunately I am not allowed to post images just yet (it seems) - just tried. So you will have to take my word.
I cannot figure out how this is possible and this is bugging me ;) As soon as I rename both files for example to 1.exe, Windows starts telling me that there is already a file with that name in the same directory. So it obviously has something to do with the filename, but they are both exactly identical, no extra spaces, nothing, as you can see from the DIR command.
I´ve also tried to rename them and re-wrote the exact wording "MailCient.exe" manually for both, to make sure the characters are EXCACTLY the same, Windows still won´t complain, they both go there once again under the same name. However, renaming them to "Mail.exe" and "Mail.exe" will NOT work, then Windows is saying that another file with that name already exists. However, naming them both back to "MailClient.exe" is just absolutely fine, no complains by Windows with that.
Another fun fact about this, if I dir for mailclient.exe directly, this happens:
C:\temp\2>dir mailclient.exe
Volume in drive C is SSD 840 Pro
Volume Serial Number is 0C6D-D489
Directory of C:\temp\2
21.10.2016 17:10 24.742.760 MailClient.exe
1 File(s) 24.742.760 bytes
0 Dir(s) 78.501.998.592 bytes free
However, if looking for *.exe, this happens:
C:\temp\2>dir *.exe
Volume in drive C is SSD 840 Pro
Volume Serial Number is 0C6D-D489
Directory of C:\temp\2
21.10.2016 17:10 24.742.760 MailClient.exe
27.12.2016 03:26 24.911.872 MailCliеnt.exe
2 File(s) 49.654.632 bytes
0 Dir(s) 78.501.990.400 bytes free
This yields also interesting results:
C:\temp\2>ren mailclient.exe *.bak
C:\temp\2>dir
Volume in drive C is SSD 840 Pro
Volume Serial Number is 0C6D-D489
Directory of C:\temp\2
13.04.2017 02:50 <DIR> .
13.04.2017 02:50 <DIR> ..
21.10.2016 17:10 24.742.760 MailClient.bak
27.12.2016 03:26 24.911.872 MailCliеnt.exe
2 File(s) 49.654.632 bytes
2 Dir(s) 78.501.990.400 bytes free
And back:
C:\temp\2>ren mailclient.bak MailClient.exe
C:\temp\2>dir
Volume in drive C is SSD 840 Pro
Volume Serial Number is 0C6D-D489
Directory of C:\temp\2
13.04.2017 02:51 <DIR> .
13.04.2017 02:51 <DIR> ..
21.10.2016 17:10 24.742.760 MailClient.exe
27.12.2016 03:26 24.911.872 MailCliеnt.exe
2 File(s) 49.654.632 bytes
2 Dir(s) 78.501.982.208 bytes free
I´ve also checked permissions on the files and took ownership, it changes nothing. Additionally I´ve cleared the NTFS Journal and even the transaction log + run chkdsk, which reveals no errors either.
Any ideas on this mysterious situation? What am I missing?
Thanks so much:)
UPDATE #1:
I´ve just tried this: going to Windows explorer and renaming both files after each other by truncating their names. So I first renamed the first "MailClient.exe" to "MailClien.exe", then the seconds "MailClient.exe" to "MailClien.exe". Again, no message by Windows that they have the same name, it just renamed both fine. I then continued to "MailClie.exe". Worked.
However, as soon as I tried to renamed both to "MailCli.exe", Windows complained and told me that there is already another file with that name. Trying to rename both back from there to "MailClient.exe" also does not work, just for one of them, because then Windows says (and right so too) that a file with that name already exists. So it seems to come down to the "e" possibly having another ANSI-character in both filenames? I, however, wouldn´t know of another one for "e", or am I missing something?
Harry Johnston is right: one of the filenames contains a Unicode character that just looks the same as an ANSI character.
Read Naming Files, Paths, and Namespaces:
On newer file systems, such as NTFS, exFAT, UDFS, and FAT32, Windows
stores the long file names on disk in Unicode, which means that the
original long file name is always preserved. This is true even if a
long file name contains extended characters, regardless of the code
page that is active during a disk read or write operation.
Use the following PowerShell script 43381802b.ps1 to detect and show non-ANSI file names (see different calls below):
param( [string[]]$Path = '.',
[switch]$Cpp, ### list any non-ANSI character in file names like a C++ literal
### i.e. a prefix \u followed by a four digit Unicode code point
[switch]$All ### list all files including pure ANSI-encoded file names
)
Set-StrictMode -Version latest
$strArr = Get-ChildItem -path $Path
$arrDiff = #()
for ($i=0; $i -lt $strArr.Count; $i++) {
$strDiff = 'ANSI'
$strName = ''
$auxName = $strArr[$i].Name
for ( $k=0; $k -lt $auxName.Length; $k++ ) {
if ( [int][char]$auxName[$k] -gt 255 ) {
$strDiff = 'UCS2'
$strName += '\u{0:X4}' -f [int][char]$auxName[$k]
} else {
$strName += $auxName[$k]
}
}
if ( $All.IsPresent -or $strDiff -eq 'UCS2' ) {
$strArr[$i] | Add-Member NoteProperty Code $strDiff
$strArr[$i] | Add-Member NoteProperty CppName $strName
$arrDiff += $strArr[$i]
}
}
if ( $Cpp.IsPresent ) {
$arrDiff | Select-Object -Property Code, Mode, LastWriteTime, Length, CppName | ft
} else {
$arrDiff | Select-Object -Property Code, Mode, LastWriteTime, Length, Name | ft
}
Output:
PS D:\PShell> .\SO\43381802b.ps1 'C:\testC\43381802'
Code Mode LastWriteTime Length Name
---- ---- ------------- ------ ----
UCS2 -a---- 02/05/2017 11:47:53 317 MailCliеnt.txt
UCS2 -a---- 02/05/2017 11:49:04 317 МailClient.txt
UCS2 -a---- 02/05/2017 11:50:16 399 МailCliеnt.txt
PS D:\PShell> .\SO\43381802b.ps1 'C:\testC\43381802' -Cpp
Code Mode LastWriteTime Length CppName
---- ---- ------------- ------ -------
UCS2 -a---- 02/05/2017 11:47:53 317 MailCli\u0435nt.txt
UCS2 -a---- 02/05/2017 11:49:04 317 \u041CailClient.txt
UCS2 -a---- 02/05/2017 11:50:16 399 \u041CailCli\u0435nt.txt
PS D:\PShell> .\SO\43381802b.ps1 'C:\testC\43381802' -Cpp -All
Code Mode LastWriteTime Length CppName
---- ---- ------------- ------ -------
ANSI -a---- 02/05/2017 11:44:05 235 MailClient.txt
UCS2 -a---- 02/05/2017 11:47:53 317 MailCli\u0435nt.txt
UCS2 -a---- 02/05/2017 11:49:04 317 \u041CailClient.txt
UCS2 -a---- 02/05/2017 11:50:16 399 \u041CailCli\u0435nt.txt
Use the following 43381802a.ps1 script to get more info about non-ANSI characters (see the first call bellow) and their position in file names (see the latter call bellow with -Detail switch):
param( [string[]] $strArr = #('ΗGreek', 'НCyril', 'HLatin'),
[switch]$Detail )
Set-StrictMode -Version latest
$auxArr = #()
if ( ( Get-Command -Name Get-CharInfo -ErrorAction SilentlyContinue ) -and
( -not $Detail.IsPresent ) ) {
$auxArr = $strArr | Get-CharInfo |
Where-Object { [int]$_.Codepoint.Replace('U+', '0x') -ge 128 }
} else {
foreach ($strStr in $strArr) {
for ($i = 0; $i -lt $strStr.Length; $i++ ) {
if ( [int][char]$strStr[$i] -ge 128 ) {
$auxArr += [PSCustomObject] #{
Char = $strStr[$i]
CodePoint = 'U+{0:x4}' -f [int][char]$strStr[$i]
Category = $i + 1 ### 1-based index
Description = $strStr ### string itself
}
}
}
}
}
$auxArr
Output:
PS D:\PShell> .\SO\43381802a.ps1 ( Get-childitem -path 'C:\testC\43381802' ).Name
Char CodePoint Category Description
---- --------- -------- -----------
е U+0435 LowercaseLetter Cyrillic Small Letter Ie
М U+041C UppercaseLetter Cyrillic Capital Letter Em
М U+041C UppercaseLetter Cyrillic Capital Letter Em
е U+0435 LowercaseLetter Cyrillic Small Letter Ie
PS D:\PShell> .\SO\43381802a.ps1 ( Get-childitem -path 'C:\testC\43381802' ).Name -detail
Char CodePoint Category Description
---- --------- -------- -----------
е U+0435 8 MailCliеnt.txt
М U+041c 1 МailClient.txt
М U+041c 1 МailCliеnt.txt
е U+0435 8 МailCliеnt.txt
Tested on files:
==> dir /-C /X /A-D C:\testC\43381802\
Volume in drive C has no label.
Volume Serial Number is …
Directory of C:\testC\43381802
02/05/2017 11:44 235 MAILCL~1.TXT MailClient.txt
02/05/2017 11:47 317 MAILCL~2.TXT MailCliеnt.txt
02/05/2017 11:49 317 AILCLI~1.TXT МailClient.txt
02/05/2017 11:50 399 AILCLI~2.TXT МailCliеnt.txt
4 File(s) 1268 bytes
0 Dir(s) 69914857472 bytes free
==>

Nagios Prescript Doesn't Work

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

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