TL;DR from [WayBack] Automating the world one-liner at a time… Boolean Values and Operators:
In PowerShell use the built-in constants $false and $true, as strings will be converted to booleans with results you don’t like
–jeroen
Posted by jpluimers on 2019/09/26
TL;DR from [WayBack] Automating the world one-liner at a time… Boolean Values and Operators:
In PowerShell use the built-in constants $false and $true, as strings will be converted to booleans with results you don’t like
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/09/25
In production, somehow an application started to misbehave, so would spit out a lot of Windows EventLog entries for Applications you can see in the EventViewer. This small script helped counting it (it takes about 10 seconds on a log having a total of 77k entries):
$tenMinutes = New-TimeSpan -Minutes 10
$now = Get-Date
$tenMinutesAgo = $now - $tenMinutes
$eventLogEntries = Get-EventLog -After $tenMinutesAgo -LogName "Application"
$count = ($eventLogEntries | Measure-Object).Count
Write-Host $count
Related:
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | 1 Comment »
Posted by jpluimers on 2019/09/03
A very concise way for [WayBack] how to filter name/value pairs under a registry key by name and value in PowerShell?:
$path = 'hkcu:\Software\Microsoft\Windows\CurrentVersion\Extensions'
(Get-ItemProperty $path).PSObject.Properties |
Where-Object { $_.Name -match '^xls' ` -or $_.Value -match 'msaccess.exe$' } |
Select-Object Name, Value
Thanks montonero for getting me on that path and pointing me to the hidden PSObject property which by itself has Properties, and making me find these links with background information:
PSObject being hiddenPSObject is revealed when calling Get-Member with the -Force parameter.More in-depth information:
Get-Member cmdlet gets the members, the properties and methods, of objects. To specify the object, use the InputObject parameter or pipe an object to Get-Member. To get information about static members, the members of the class, not of the instance, use the Static parameter. To get only certain types of members, such as NoteProperties, use the MemberType parameter.-ForceAdds the intrinsic members (PSBase, PSAdapted, PSObject, PSTypeNames) and the compiler-generated get_ and set_ methods to the display. By default, Get-Member gets these properties in all views other than Base and Adapted, but it does not display them.
The following list describes the properties that are added when you use the Force parameter:
Property collection, or the members that are actually properties.PSMemberInfoCollection<PSPropertyInfo>PSObject or MemberSet–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/08/15
The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic.
Every now and then I bump into the above error. The reason is this:
Confused? #MeToo
The problem: [WayBack] about_Parameters_Default_Values | Microsoft Docs
Based on [WayBack] Powershell function won’t work.
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/08/14
I learned this the hard way: [WayBack] Different result when using -ReadCount with Get-Content: because -ReadCount delivers data in chunks, the filter after [WayBack] Get-Content (Microsoft.PowerShell.Management) it will only filter on those chunks. If the filter isn’t prepared for that, it might only filter the last chunk.
So do not use for instance [WayBack] Select-String (Microsoft.PowerShell.Utility) on it, but perform your own [WayBack] ForEach-Object (Microsoft.PowerShell.Core) aliased as foreach like in [WayBack] Get all lines containing a string in a huge text file – as fast as possible?:
Get-Content myfile.txt -ReadCount 1000 | foreach { $_ -match "my_string" }
A more elaborate example is at [WayBack] How can I make this PowerShell script parse large files faster?.
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/08/13
[WayBack] In Powershell, what kind of data type is [string[]] and when would you use it? (thanks cignul9 and arco444!): basically it forces an array of string.
It defines an array of strings. Consider the following ways of initialising an array:
[PS] > [string[]]$s1 = "foo","bar","one","two",3,4 [PS] > $s2 = "foo","bar","one","two",3,4 [PS] > $s1.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String[] System.Array [PS] > $s2.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.ArrayBy default, a powershell array is an array of objects that it will cast to a particular type if necessary. Look at how it’s decided what types the 5th element of each of these are:
[PS] > $s1[4].gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object [PS] > $s2[4].gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType [PS] > $s1[4] 3 [PS] > $s2[4] 3The use of
[string[]]when creating$s1has meant that a raw3passed to the array has been converted to aStringtype in contrast to anInt32when stored in anObjectarray.
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/08/01
I’ve learned the hard way that both .NET and PowerShell version information isn’t always accurate or usable for two reasons which I later found in various other blog and forum posts:
FileVersion and ProductVersion are sometimes obtained from the MUI ([WayBack] Multilingual User Interface – Wikipedia) which isn’t always updated when the PE file is. However, the integer typed properties are.The easiest is to use these numbers to create a [WayBack] Version Class (System) instance using the [WayBack] Version Constructor (Int32, Int32, Int32, Int32) constructor. This has the added benefit that you directly compare versions with each other.
Sometimes it makes even sense to take the highest version from Product and File.
In PowerShell, this is the way to do that, assuming $imagePath points to a [WayBack] Portable Executable:
try {
$VersionInfo = (Get-Item $imagePath).VersionInfo
$FileVersion = [version]("{0}.{1}.{2}.{3}" -f $VersionInfo.FileMajorPart, $VersionInfo.FileMinorPart, $VersionInfo.FileBuildPart, $VersionInfo.FilePrivatePart)
$ProductVersion = [version]("{0}.{1}.{2}.{3}" -f $VersionInfo.ProductMajorPart, $VersionInfo.ProductMinorPart, $VersionInfo.ProductBuildPart, $VersionInfo.ProductPrivatePart)
$ActualVersion = $(if ($ProductVersion -gt $FileVersion) { $ProductVersion } else { $FileVersion })
}
catch {
$ActualVersion = [version]("0.0.0.0")
}
Background information:
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/31
I like this built-in construct by fbehrens most:
$result = If ($condition) {"true"} Else {"false"}Everything else is incidental complexity and thus to be avoided.
For use in or as an expression, not just an assignment, wrap it in
$(), thus:
write-host $(If ($condition) {"true"} Else {"false"})
There are even more elegant constructs, but those require setting up an alias before using them.
Source: [WayBack] Ternary operator in PowerShell – Stack Overflow
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/30
Cool tip by mjolinor to execute the scripts 1.ps1, 2.ps1 and 3.ps1 from a master.ps1 script in the same directory:
&"$PSScriptroot\1.ps1"
&"$PSScriptroot\2.ps1"
&"$PSScriptroot\3.ps1"
Source: [WayBack] scripting – Run Multiple Powershell Scripts Sequentially – on a Folder – Combine Scripts into a Master Script – Stack Overflow.
It uses $PSScriptroot which got introduced in PowerShell 2 in modules and extended in PowerShell 3 to be available in all scripts. More information in [WayBack] about_Automatic_Variables | Microsoft Docs
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/25
I love the solution with piped Join-Path constructs answered by David Keaveny in [WayBack] powershell – How do I use join-path to combine more than two strings into a file path? – Stack Overflow:
Since Join-Path can be piped its path value, you can pipe multiple Join-Path statements together:
Join-Path "C:" -ChildPath "Windows" | Join-Path -ChildPath "system32" | Join-Path -ChildPath "drivers"
Of course you could replace the built-in [WayBack] Join-Path by using using the .NET Framework [WayBack] Path.Combine Method (System.IO), but then you loose code completion.
If you do like that, here is how:
[System.IO.Path]::Combine("C:", "Windows", "system32", "drivers")
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »