Tag Archives: powershell

Powershell – ForEach-Parallel


In PowerShell I often find the need to speed things up when having to do querying lots of similar things – usually getting the same stuff from multiple machines. So I ventured out onto the Interwebs and over time slap together a PowerShell module that does parallel processing. I’m not claiming this to be purely my work – I only added and refined it a bit for my needs.

This example works with ‘older’ versions of PowerShell (think version 4/5 and perhaps 3). The latest versions of PowerShell (afaik version 7) now has something like this built in.


Using any sort of parallel coding requires a different approach than normal procedural (Start at the top and run code line by line until you get to the end). Basically it is multi-threading but PowerShell ‘out of the box’ has nothing like it. To implement multi threading you need to use ‘runspaces’ which effectively means you are running multiple instances of PowerShell.

The ForEach-Parallel function takes a scriptblock as input. Optionally you can also specify the number of threads used to do the parallel processing.

function ForEach-Parallel {
         [System.Management.Automation.ScriptBlock] $ScriptBlock,
     BEGIN {
         $iss = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
         $pool = [Runspacefactory]::CreateRunspacePool(1, $maxthreads, $iss, $host)
         $threads = @()
         $ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock("param($_)r`n" + $Scriptblock.ToString())
     PROCESS {
         $powershell = ::Create().addscript($scriptblock).addargument($InputObject)
         $threads+= @{
             instance = $powershell
             handle = $powershell.begininvoke()
     END {
         $notdone = $true
         while ($notdone) {
             $notdone = $false
             for ($i=0; $i -lt $threads.count; $i++) {
                 $thread = $threads[$i]
                 if ($thread) {
                     if ($thread.handle.iscompleted) {
                         $threads[$i] = $null
                     else {
                         $notdone = $true
 export-modulemember -function ForEach-Parallel 

To make use of this ‘module’ save it to a file named ForEach-Parallel.psm1 and place it in C:\Users\{your user account}\Documents\WindowsPowerShell\modules\ForEach-Parallel


$computers = 'computer1','computer2','computer3'
 $computers | ForEach-Parallel -MaxThreads 20 -ScriptBlock {
     $computerToPing = $_
     [int]$ResponseTime = 0
     [string]$ResolvedName = ''
     $StepPing = (Test-Connection -ComputerName $computerToPing -Count 1 -ErrorAction SilentlyContinue)
   if ($StepPing -ne $null){
      $ResponseTime = $StepPing.ResponseTime 
   New-Object psobject -Property @{     
    Name               = $computerToPing     
    ResponseTime       = $ResponseTime                  


There are a few things to watch out for – like any multi-threading coding. While the code is running there is no indication how far each ‘thread’ is – you have to wait until all of them are done. Threads are independent so they cannot reference each other or even variables in the calling thread.

So.. happy multi-threading.

SSH from PowerShell

I’ve been playing with more non Microsoft technologies recently and even have a few Linux VMs running here and there. In the process I’ve learned a lot about interacting between the two worlds/environments using technologies like SSH and even running the Powershell Alpha previews on my Linux VMs. Then I got ‘bored’ and looked for a way to programmatically interact with my VMs (for monitoring) and discovered the open source project SSH.Net which I now have incorporated into even QuickMon. Then I got even more bored and started looking for a way to use SSH from Powershell and came across the SSH-Sessions module which incidentally also use SSH.Net to give Powershell a way to call/connect using SSH.

No PassPhrase

This all works nicely except… SSH-Sessions had one shortcoming.. which I just had to fix. The creator(s) of this module implements a way to specify a key file when connecting to an SSH server but does not provide a way to specify the ‘PassPhrase’ at all! WHY?

Any way, I knew the SSH.Net library does support it since I actually make use of this functionality in QuickMon. Then I started digging inside the SSH-Session script files and made a few adjustments…


To enable PassPhrase functionality I simply had to add the following code in the ‘New-SshSession’ function:

Change the function header to:

function New-SshSession {
    param([Parameter(Mandatory=$true)][string[]] $ComputerName,
          [Parameter(Mandatory=$true)][string]   $Username,
          [string] $KeyFile = '',
          [string] $PassPhrase = 'blankPassphrase',
          [string] $Password = 'SvendsenTechDefault', # I guess allowing for a blank password is "wise"...          
          [int] $Port = 22,
          [switch] $Quiet

and then inside the function:

if ($KeyFile -ne '') {
        if (-not $Quiet) {
            "Key file specified. Will override password. Trying to read key file..."
        if ($PassPhrase -eq 'blankPassphrase') {
            $SecurePassPhrase = Read-Host -AsSecureString "key provided. Please enter pass phrase for $KeyFile"
            $PassPhrase = ConvertFrom-SecureToPlain $SecurePassPhrase
        if (Test-Path -PathType Leaf -Path $Keyfile) {
            $Key = New-Object Renci.SshNet.PrivateKeyFile( $Keyfile, $PassPhrase ) -ErrorAction Stop
        else {
            "Specified keyfile does not exist: '$KeyFile'."


And with the you can now use the module to connect to SSH using a Key file that has a PassPhrase. If you don’t specify the PassPhrase the script will prompt you for one. If you actually don’t have a PassPhrase at all then pass an empty string as the value of PassPhrase (not tested but it should work).

Import-Module SSH-Sessions
New-SshSession -Computer mySSHServer -Username me  -KeyFile 'c:\mykeys\mykey.key' -PassPhrase 'somePhrase'
Invoke-SshCommand  -ComputerName mySSHServer -Command "cat /proc/cpuinfo | grep processor" -Quiet
Remove-SshSession -RemoveAll -Quiet

How to install Powershell on Ubuntu 16.10

I recently tried installing the latest Alpha of Powershell (Alpha 12) on the newly released Ubuntu 16.10 and discovered that the install failed because of a dependency on the library libicu55 which has been replaced in the new version of Ubuntu (libicu57). Actually, the whole .Net Core install fails because of this.

Fortunately this is easy to fix by manually installing the old library from http://cz.archive.ubuntu.com/ubuntu/pool/main/i/icu/libicu55_55.1-7_amd64.deb

Then you can download the latest Powershell version (Alpha 12 as of this writing) from https://github.com/PowerShell/PowerShell/releases

Hopefully the creators of the Powershell packages will release an updated version that is natively compatible with Ubuntu16.10.


PowerShell ISE on Windows 10 (10049 preview)

Just a quick tip how to get to the PowerShell ISE in Windows 10 which they (MS) seems to be trying to hide away… 🙂

Launch the normal PowerShell command window – “All Apps – Windows System – Windows PowerShell”. Once it is running pin it to the taskbar. Now if you right click on the pinned icon it will include a menu option under Tasks for ‘Run ISE as Administrator’ and ‘Windows PowerShell ISE’.

You can then launch the ISE and pin that to the taskbar as well if you like…


How to access the ‘Service Controller Database’ remotely on a Workgoup network

After having some issues with my home computers not being able to ‘see’ each others services I started digging around for solutions – having already checked all the other possible problems. The main issue is that all these computers are running on an old fashioned ‘Workgroup’ since I don’t have an Active Directory Controller (no Windows Servers). Thus all the machines connect using the same username/password combination.

I’ve made sure of things like firewalls, user accounts (as mentioned already), UAC etc. are all ok but still I got the ‘Cannot open Service Control Manager Database’ error (Access denied (5)). I started suspecting there must be another level of security that is blocking access to view/start/stop Windows services across different machines. Then I stumbled across articles describing ACLs and the issue that to this day Microsoft has not exposed Service ACL’s through .Net yet (yet they have things like File and Registry ACLs exposed through System.Security namespace…).

The only way to get to these ACL’s are through old fashioned Win32 APIs or using the SC.exe utility. I’ve read that someone wrote a C# wrapper class for these somewhere but I could not find any remaining source of this through Google. Bummer… Then using the SC.exe utility through some nasty loosely coupled integration is the only solution…

To view the current DACL (Discretionary Access Control List) for ‘Service Controll Manager’ you can use the followig command on the source/host computer you want to connect to:

sc sdshow scmanager

That should give you something like this:


Now, the part that was relevant to me using a ‘Workgroup’ network is the (…AU) part because for some reason even though I’m using the same user account/Password on all machines – and this account is an Administrator on each machine, the system only recognize the user as part of the Authenticated users group ONLY. Thus the  (A;;CC;;;AU) part is not sufficient to allow access to the service control manager database…

To get access to the Service Controller Database you need permissions like this: (A;;CCLCRPRC;;;AU)

To understand what all those letters use please refer to ‘Best practices and guidance for writers of service discretionary access control lists‘ which explains the whole lot. The following command can be used to ‘fix’ the access to the ‘Service Controller Database’: (note that is is just an example!! Check the output of the previous command first)

 sc.exe sdset scmanager D:(A;;CCLCRPRC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)

After running this you should be able to access the  ‘Service Controller Database’ remotely (assuming all the other things have been checked). All good and wonderful! uhmm… Then I discover this does not display all services… bugger again..

Actually there are two parts to the original problem – as I discovered that each Windows service on its own has an ACL that can/should be set. Some ‘system’ services already come with permissions for AU (Authenticated Users) so they are visible by default. Most other and particularly my custom created services don’t have the right ACLs set. To fix that is simple… Just repeat the process above for that particular service – like this (for my QuickMon 3 Service):

Sc sdshow "Quickmon 3 service"

This should give an output like this:


As you can see it does not have any permissions for AU. To fix access to that server you simply have to add the AU permissions like this:


Now of course you have to repeat this for each Windows Service you need access to…

To help in this process I created the following PowerShell script that list all Windows Servers plus their ACLs:

$services = @{}
Get-Service | foreach {
    $DACL = sc.exe sdshow $_.ServiceName
    $service = @{
        'ServiceName' = $_.ServiceName
        'DisplayName' = $_.DisplayName
        'ServiceType' = [string]$_.ServiceType
        'DependsOn'   = [string]$_.ServicesDependedOn
        'State'       = [string]$_.Status
        'DACL' = ([string]$DACL).Trim()
    $serviceObj = New-Object -TypeName PSObject -Property $service
$services.Values | select ServiceName, DisplayName, ServiceType, State, DependsOn, DACL | Sort-Object ServiceName

Now you have to repeat the whole process for each service… And that is how it’s done… Enough to keep you out of mischief or perhaps enough to get you into it again…

Getting GDI object count per process in Powershell

Ever wanted to query the GDI object count in PowerShell per process?

Here’s how:

"Number of GUI handles per process"
$sig = @'
public static extern int GetGuiResources(IntPtr hProcess, int uiFlags);

Add-Type -MemberDefinition $sig -name NativeMethods -namespace Win32

$processes = [System.Diagnostics.Process]::GetProcesses()
[int]$gdiHandleCount = 0
ForEach ($p in $processes)
        $gdiHandles = [Win32.NativeMethods]::GetGuiResources($p.Handle, 0)
        $gdiHandleCount += $gdiHandles
        $p.Name + " : " + $gdiHandles.ToString()   
    catch {
        #"Error accessing " + $p.Name
"Total number of GDI handles " + $gdiHandleCount.ToString()

Alternatively you can use Process Explorer from Microsoft (originally sys-internals) if it is installed.

Start or stop BizTalk Applications using PowerShell

This is not actually something new but for anyone else that wants to quickly have a reference to it, here are two PowerShell scripts to stop and start BizTalk applications.

Stopping a specified Application:

if ($args.count -eq 0) {
  "You must specify the BizTalk Application name to stop!"
    $BTSAppName = $args[0]
    $SQLInstance = "."
    $BizTalkManagementDb ="BizTalkmgmtdb"
    [void] [System.reflection.Assembly]::LoadWithPartialName("Microsoft.BizTalk.ExplorerOM")
    $Catalog = New-Object Microsoft.BizTalk.ExplorerOM.BtsCatalogExplorer
    $Catalog.ConnectionString = "SERVER=$SQLInstance;DATABASE=$BizTalkManagementDb;Integrated Security=SSPI"

    $BTSApp = $Catalog.Applications[$BTSAppName]
    if ($BTSApp.Status -ne "stopped")
        "Stopping" + $BTSApp.Name
        $BTSApp.Name + " is already stopped"

Starting a specified Application:

<pre>if ($args.count -eq 0) {
  "You must specify the BizTalk Application name to start!"
    $BTSAppName = $args[0]
    $SQLInstance = "."
    $BizTalkManagementDb ="BizTalkmgmtdb"
    [void] [System.reflection.Assembly]::LoadWithPartialName("Microsoft.BizTalk.ExplorerOM")
    $Catalog = New-Object Microsoft.BizTalk.ExplorerOM.BtsCatalogExplorer
    $Catalog.ConnectionString = "SERVER=$SQLInstance;DATABASE=$BizTalkManagementDb;Integrated Security=SSPI"

    $BTSApp = $Catalog.Applications[$BTSAppName]
    if ($BTSApp.Status -ne "started")
        "Starting " + $BTSApp.Name
        $BTSApp.Name + " is already started"

List all .Net versions using PowerShell

A quick tip (script) how to list all the .Net (major) versions of a list of machines.

$serverListFile = "<Path to file>\computers.txt";
$computers = Get-Content -path $serverListFile

$BASEDOTNETPATH = "\c$\Windows\Microsoft.NET\Framework\"

function CheckNet45($computerName){
  $NETROOTKEY = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4"
  $keyname = $NETROOTKEY + "\\Full"
    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $computerName)
    if ($reg -ne $null){
      if ($reg.OpenSubKey($keyname).GetValue("Version").ToString().StartsWith("4.5")){
        return $True
  catch {
    #do nothing
  return $False

foreach($computer in $computers)
  $ok = Test-Connection $computer -Count 1 -Quiet
  if ($ok) {
    $computerBasePath = "\\" + $computer + $BASEDOTNETPATH
    $versionStr = ""
    if (Test-Path ($computerBasePath + "v1.0.3705")){
      $versionStr = $versionStr + "1.0,"
    if (Test-Path ($computerBasePath + "v1.1.4322")){
      $versionStr = $versionStr + "1.1,"
    if (Test-Path ($computerBasePath + "v2.0.50727")){
      $versionStr = $versionStr + "2.0,"
    if (Test-Path ($computerBasePath + "v3.0")){
      $versionStr = $versionStr + "3.0,"
    if (Test-Path ($computerBasePath + "v3.5")){
      $versionStr = $versionStr + "3.5,"
    if (Test-Path ($computerBasePath + "v4.0.30319")){
      $versionStr = $versionStr + "4.0,"

      if (CheckNet45($computer)){
        $versionStr = $versionStr + "4.5,"
    $versionStr = $versionStr.TrimEnd(',')
    "  Installed version(s): " + $versionStr

   " Is not pingable!"

All you have to do is create a text file with a list of machine names (one name per line). It does assume you have Admin rights so you can access the C$ share and read the remote registries.

A little (versioning) pain with Powershell

First thing to mention is I’m not complaining about PowerShell itself or functionality provided with PowerShell. Rather, this is a problem with referencing it from .Net (C#) and versioning when used on another machine where the .Net App was deployed and happen to have an older version of PowerShell (PS for short).


If you want to run PowerShell scripts from a C# program like I’m doing in QuickMon now, you have to add a reference to “System.Management.Automation.dll“. I happen to have Version 4.0 of PowerShell on the computer where the C# app is compiled. Now, this is all fun and games until you want to run the same app on another machine that only have, say Version 2.0 of PowerShell. PS 2 does have a version of System.Management.Automation.dll but somehow it is not compatible (at run time). When I compiled the same app on a computer that only has V2.0 of PowerShell and deploy that app to machines that has either PS v2.0 or v4.0 it works on all of them.

If this was C++ it would have made sense (dll versioning very strict) but this is a C# app that supposively should not care about the version of the referenced assembly (and yes, this is a .Net assembly). The methods (I) used in the dll are all the same of both versions.

I even tried generating the System.Management.Automation.dll file manually on the ‘target’ machine and copy that dll to the App’s directory (using the PS “Copy ([PSObject].Assembly.Location) C:\” command) but this gave other versioning referencing errors.

Possible solution

The solution that seems to work for now is to set the ‘Specific Version‘ property on the referenced dll in the C# project to true (making sure it points to the PS 2.0 related version – dll version 6.1.7601.17514). Interestingly enough when switching the project to ‘release’ configuration it display pointing to ‘C:\Windows\assembly\GAC_MSIL\System.Management.Automation\\System.Management.Automation.dll’. That tells me the PS version ‘2.0’ of that assembly is still available (on my PS 4.0 computer). As a safety precaution I also set the ‘Copy Local’ property on this referenced dll to True to have it deployed with the app.

Deploying this combination seems to work on all ‘target’ machines – I even saw it working on a computer that only has PS 1.0!

All fun and joy… as long as there’s no lawyer sitting on a loo in the bush… with an angry T-Rex nearby…

List all servers where I have an RDP session on (even ones where I’m disconnected)

This is something more than just one administrator has had trouble with. How do you find out what servers/machines you have worked on at some point and happened to simply use the ‘disconnect’ feature because you still had windows open? So far I have not found a simple way to do this – however I have created a script that helps with this. Unfortunately it still requires you to specify a list (input text file) of possible servers than needs to be checked. I would have liked if it was possible to have it automatically discover all machines with RDP sessions that use my logon…

The solution I created is simply a powershell script that takes an input text file with the list of machines you want to test connections with. This list would probably contain the usual machines you connect to. The other bit of the ‘solution’ is calling the ‘qwinsta’ utility that queries a specified machine and returns some details about RDP connections active on that machine. The script must then parse the output to figure out if your username is one of them…

param (
    $myAccount #(Read-Host -Prompt "Enter a user name")
    ,$serverListFile #(Read-Host -Prompt "File with list of servers")
if ($myAccount -eq $null){
    $myAccount = $env:username
if ($serverListFile -eq $null){
    $scriptpath = $MyInvocation.MyCommand.Path
    $dir = Split-Path $scriptpath
    $serverListFile = $dir + "\myservers.txt"

$showDebugInfo = $false
$reader = [System.IO.File]::OpenText($serverListFile)
"Listing RDP sessions for " + $myAccount
try {
    for(;;) {
        $server = $reader.ReadLine()
        if ($server -eq $null) { break }
        # process the line
        if(!(Test-Connection -Cn $server -BufferSize 16 -Count 1 -ea 0 -quiet))
            " Error accessing " + $server
                if ($showDebugInfo){
                    "Checking " + $server + "..."
                $qwinstaResults = (qwinsta /server:$server | foreach { (($_.trim() -replace “\s+”,”,”))} | ConvertFrom-Csv)
                ForEach ($queryResult in $qwinstaResults)
                    if ($queryResult -CMatch $myAccount)
                        "Logged on to " + $server
                " Error processing " + $server
finally {

Then using this script is as easy as calling it from (say) a batch file like this:

powershell.exe .\MyRDPConnections.ps1 myusername myservers.txt

Not perfect but at least it helps.