Old, but I keep bumping in old Python code that needs conversion to work in Python 3.x: [WayBack] What’s New In Python 3.0 — Python 3.6.3 documentation.
Via: [WayBack] Version 3: History of Python – Wikipedia
–jeroen
Posted by jpluimers on 2019/07/30
Old, but I keep bumping in old Python code that needs conversion to work in Python 3.x: [WayBack] What’s New In Python 3.0 — Python 3.6.3 documentation.
Via: [WayBack] Version 3: History of Python – Wikipedia
–jeroen
Posted in Development, Python, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/26
Utility for converting curl commands to code
For my link archive: [WayBack] Convert cURL command syntax to Python requests, Node.js code
–jeroen
Posted in *nix, *nix-tools, cURL, Development, JavaScript/ECMAScript, Node.js, Power User, Python, 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 »
Posted by jpluimers on 2019/07/24
This is my default PowerShell script header from now on:
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$PSDefaultParameterValues['*:ErrorAction']='Stop'
This might sound like overkill, but it solves these problems:
Set-StrictMode -Version Latest will warn on uninitialised variables and other code risks; see for instance [WayBack] Enforce Better Script Practices by Using Set-StrictMode – Hey, Scripting Guy! Blog and [WayBack] Set-StrictMode$ErrorActionPreference = 'Stop' will raise exceptions when errors occur under almost all circumstances to you do not have to add -ErrorAction Stop in CmdLets; see for instance [WayBack] powershell – Why does the exception not get me in the catch block? – Stack Overflow$PSDefaultParameterValues['*:ErrorAction']='Stop'works around CmdLets that ignore $ErrorActionPreference = 'Stop'; see for instance [WayBack] windows – How to stop a PowerShell script on the first error? – Stack Overflow and [WayBack] error handling – PowerShell – Setting $ErrorActionPreference for the entire script – Stack OverflowThe above helped me tremendously with for instance [WayBack] powershell – Why does the exception not get me in the catch block? – Stack Overflow:
I’m trying to interrogate some service information. Sometimes the installer of the application fails to correctly install, so the registry does not contain a service entry. I want to find out which installer steps did get executed correctly, even on systems that do not have proper logging in the installer.
If
MyServicedoes not exist, the script below does not go to thecatchblock even though the exception handling documentation suggests a barecatchshould be enough:try { $path = 'hklm:\SYSTEM\CurrentControlSet\services\MyService' $key = Get-Item $path $namevalues = $key | Select-Object -ExpandProperty Property | ForEach-Object { [PSCustomObject] @{ Name = $_; Value = $key.GetValue($_) } } $namevalues | Format-Table } catch { $ProgramFilesX86 = [System.Environment]::GetFolderPath("ProgramFilesX86"); $ProgramFiles = [System.Environment]::GetFolderPath("ProgramFiles"); Write-Host $ProgramFilesX86 Write-Host $ProgramFiles }Why is that and how should I force it to end up in the
catch?This is what PowerShell outputs:
Get-Item : Cannot find path 'HKLM:\SYSTEM\CurrentControlSet\services\MyService' because it does not exist. At C:\Users\Developer\...\GetMyServiceInfo.ps1:17 char:12 + $key = Get-Item $path + ~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (HKLM:\SYSTEM\Cu...vices\MyService:String) [Get-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
For which I edited the answer to become this:
Force the error to be terminating:
$key = Get-Item $path -ErrorAction StopThat way it will throw and catch will get it.
Explanation and links to the official Microsoft documentation:
-ErrorActionis a Common Parameter that can be applied to any PowerShell command- The default value for
-ErrorActionisContinuewhich prevented the exception to be thrown in the first place.- You can configure a global
-ErrorActionsetting using the Preference Variable named$ErrorActionPreferenceto override this default value.
What is missing there is the link to the $PSDefaultParameterValues documentation at [WayBack] about_Parameters_Default_Values | Microsoft Docs
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/23
Interesting tool: DTW-DanWard/PowerShell-Beautifier: A whitespace reformatter and code cleaner for Windows PowerShell and PowerShell Core
–jeroen
via: [WayBack] Is there a PowerShell code formatter / pretty printer? – Stack Overflow
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/18
I’m not even sure if I’ve posted this before, but I always forget how to show all members (or columns) using Format-Table.
It’s dead easy: -Property *
Get-ChildItem | Format-Table -Property *
Later I found out this is equivalent with the shorter version where you omit the -Property part which I wrote about in [WayBack] PowerShell: when Format-Table -AutoSize displays only 10 columns and uses the width of the console when redirecting to file.
So you can shorten the above to:
Get-ChildItem | Format-Table *
It has way more columns than this:
Get-ChildItem | Format-Table
The extra members in both marked with *:
PSPathPSParentPathPSChildNamePSDrivePSProviderPSIsContainerBaseNameMode *Name *FullNameParentExistsRootExtensionCreationTimeCreationTimeUtcLastAccessTimeLastAccessTimeUtcLastWriteTime *LastWriteTimeUtcAttributesThe odd thing: one property fails in the -Property * table:
LengthI tracked this down to how -Property * works: it takes the first entry in the list. If that is not a file, then it has no Length property: [WayBack] powershell – Measure-Object : The property “length” cannot be found in the input for any objects – Stack Overflow.
Note that for a GUI version, you can replace Format-Table with Out-GridView. See
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/17
You can get many process properties using , for instance the total running time in minutes [WayBack] Get-Process:
New-TimeSpan -Start (Get-Process "devenv").StartTime | Select-Object -ExpandProperty "TotalMinutes"
Actually, the it matches multiple process instances, then you need to aggregate, for instance using this:
Get-Process "cmd" | ForEach-Object { New-TimeSpan -Start $_.StartTime } | Measure-Object -Property "TotalMinutes" -Sum | Select-Object -ExpandProperty "Sum"
If you want to see which properties are available, then use either of these:
Get-Process | Select-Object * | Out-GridView
Get-Process | Get-Member
Lets start getting the total CPU time of all processes by using Get-Process which – without arguments – returns data for all processes it has access to:
PS C:\Users\Developer> Get-Process | Measure-Object -Property CPU -Sum
You’d think this gives only the sum. Wrong:
Count : 80
Average :
Sum : 2410.5625
Maximum :
Minimum :
Property : CPU
And you need it with an Administrative UAC token in order to get all processes on the system. It doesn’t show many more processes, but a lot more CPU time since boot:
Count : 83
Average :
Sum : 6078.125
Maximum :
Minimum :
Property : CPU
So how to get rid of [WayBack] Measure-Object showing all aggregates?
The only stable solution I found is to expand that into | Measure-Object -Property CPU -Sum | Select-Object -ExpandProperty Sum which I found in the answer by davidhigh at [WayBack] Listing processes by CPU usage percentage in powershell – Stack Overflow and got me this by using [WayBack] Select-Object.
Note you have to use -ExpandProperty as just -Propertywill not cut it as you get an empty result (I think this has to do with Sum being a nullable type: Sum Property System.Nullable[double]):
PS C:\Windows\system32> Get-Process | Measure-Object -Property CPU -Sum | Select-Object -Property Sum
PS C:\Windows\system32> Get-Process | Measure-Object -Property CPU -Sum | Select-Object -ExpandProperty Sum
6126.40625
You’d think a CPU % is an easy thing to measure as it has been available in the Task Manager for such a long time, but it’s harder to determine than for instance process memory. Let me try to explain that (please post comments when it is unclear).
For process memory, you can measure it at the current instant: if you freeze the CPU, you can count the number of bytes used by the process.
For relative CPU usage however, you need to measure how a process executes over time. During that time, CPU usage may (or will) vary a little bit, so you need to measure over a little time-delta. If CPU core frequencies vary over time, you need to adjust for that so it gets even more difficult. Two links with a bit more background information on this:
I think the above difference is the reason that Get-Process doesn’t return a CPU percentage.
Get-CounterInstead, you can use [WayBack] Get-Counter to get processor CounterSampleslike this:
(Get-Counter '\Process(*)\% Processor Time').CounterSamples
It gets you the % Processor Time which is the percentage of CPU determined by a CPU [WayBack] Hardware performance counter.
If you want this for a specific process, you first need to find out which processes exist. You can do that by getting the unique InstanceName property values by using [WayBack] Sort-Object:
(Get-Counter '\Process(*)\% Processor Time').CounterSamples | Select-Object -Property InstanceName | Sort-Object -Property InstanceName -Unique
(Here you do not need the -ExpandProperty on Select-Objectas the -Property suffices)
InstanceName valuesThere are always entries with InstanceName having values _total and idle:
(Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "_total" }
(Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "idle" }
You can even get both at the same time by using the -or operator with [WayBack] Where-Object:
(Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {($_.InstanceName -eq "_total") -or ($_.InstanceName -eq "idle") }
Since the outputs are CPU core based, and sampled over time, they can be above 100%, heck even above the 100% * amount-of-CPU-cores as seen on a 2-core CPU system:
Path InstanceName CookedValue ---- ------------ ----------- \\w81entx64vs2015\process(idle)\% processor time idle 186.168932138452 \\w81entx64vs2015\process(_total)\% processor time _total 200.016208082634
You see that the CookedValue is what you’re after. If you just want the value for one instance, just use the -ExpandProperty trick shown above:
(Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "_total" } | Select-Object -ExpandProperty CookedValue
(Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "svchost" } | Select-Object -ExpandProperty CookedValue
This gets you a list like this:
PS C:\Windows\system32> (Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "svchost" } | Select-Object -ExpandProperty CookedValue
0
0
...
0
0
For that, you need to aggregate by using Measure-Object like described in the Get-Process section:
PS C:\Windows\system32> (Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "svchost" } | Measure-Object -Property CookedValue -Sum | Select-Object -ExpandProperty Sum
0
A more elaborate example of aggregating is at [Archive.is] ExportPerfomanceCountersHelpers.ps1.
This works for a single-instance process as well:
(Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "lsass" } | Measure-Object -Property CookedValue -Sum | Select-Object -ExpandProperty Sum
Example output:
PS C:\Windows\system32> (Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "lsass" } | Measure-Object -Property CookedValue -Sum | Select-Object -ExpandProperty Sum
0
The above often works, but sometimes you get an error, often even earlier in the process.
The error is always like Get-Counter : The data in one of the performance counter samples is not valid. View the Status property for each PerformanceCounterSample object to make sure it contains valid data.:
PS C:\Windows\system32> (Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.InstanceName -eq "lsass" } | Measure-Object -Property CookedValue -Sum | Select-Object -ExpandProperty Sum
Get-Counter : The data in one of the performance counter samples is not valid. View the Status property for each PerformanceCounterSample object to make sure it contains valid data.
At line:1 char:2
+ (Get-Counter '\Process(*)\% Processor Time').CounterSamples | Where-Object {$_.I ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidResult: (:) [Get-Counter], Exception
+ FullyQualifiedErrorId : CounterApiError,Microsoft.PowerShell.Commands.GetCounterCommand
0
It took me a while to figure this out, but the root cause is that in-between Get-Counter retrieving the hardware process counters and processing the values, the CPU continues executing thereby changing some of the values. For instance, processes can quit (the CPU is not aware of processes, so binding CPU thread information from the hardware process counters to logical processes can fail in that step).
These links helped me tremendously as the -ErrorAction SilentlyContinue is not documented by Microsoft at Get-Counter:
Always use a construct like this to search for CPU usages on one or more processes named powershell:
(Get-Counter '\Process(*)\% Processor Time' -ErrorAction SilentlyContinue).CounterSamples | Where-Object {$_.InstanceName -eq "powershell" } | Measure-Object -Property CookedValue -Sum | Select-Object -ExpandProperty Sum
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/16
Design Patterns and Refactoring articles and guides. Design Patterns video tutorials for newbies. Simple descriptions and full source code examples in Java, C++, C#, PHP and Delphi.
Source: [WayBack] Design Patterns & Refactoring.
And indeed a lot of examples in Delphi too; few sites have that: Delphi site:sourcemaking.com.
–jeroen
Via: [WayBack] I stumbled upon this yesterday, very informative, accessible and also with Delphi examples – among other languages. – Steffen Nyeland – Google+
Posted in .NET, C, C#, C++, Delphi, Design Patterns, Development, Java, Java Platform, PHP, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/16
I always forget the exact syntax for getting command-line arguments to PowerShell. It’s the $args implicit array variable:
–jeroen
Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »
Posted by jpluimers on 2019/07/11
For my link archive: [WayBack] Tech Notes: TypeScript at Google.
A good discussion, also about alternatives (like Kotin, Scala, GTW) is at [WayBack] TypeScript at Google | Hacker News
Via [WayBack] TypeScript at Google https://news.ycombinator.com/item?id=17894764 #typescript #google #microsoft #javascript – Adrian Marius Popa – Google+
–jeroen
Posted in Development, JavaScript/ECMAScript, Scripting, Software Development, TypeScript | Leave a Comment »