powershell, Uncategorized

Powershell : WebRequest Server Not Found

So at work we use a bit of PowerShell here and there to do various things. We also use PowerShell remoting, where we run the same bit of code on a potential list of remote targets.

One of the things we use a lot is a notification system where it will attempt to use this code or code

Invoke-RestMethod -Uri "$env:mattermost_uri" -Method Post -Body $json -ContentType "application/json"

But occasionally this would fail on some of our target VMs, where I would see a “Unable to connect to remote server“.

Turns out there is a default proxy at play which can be disabled like this

[System.Net.HttpWebRequest]::DefaultWebProxy = New-Object System.Net.WebProxy

After that is was all good for me


Open Live Writer + Syntax Highlighting

I have been trying to get the open source fork of Windows Live Writer to recognize plugins for ages now, have tried

Nothing seemed to work. Then I was just about to give up, then I came across this post : https://blogs.technet.microsoft.com/simonbrown/2017/06/23/using-open-live-writer/ by Simon Brown that just rained unicorns on my rather gloomy day

Simon has written this PowerShell script that you run once, and then just Restart Open Live Writer, and bingo by plugin now works.

Here is his script, thanks Simon you rock

#download zip file for syntax highlighting
$url = "https://richhewlett.blob.core.windows.net/blogdownloads/SyntaxHighlight_WordPressCom_OLWPlugIn_V2.0.0.zip" 
$path = (Get-Item -Path ".\" -Verbose).FullName + "\SyntaxHighlight_WordPressCom_OLWPlugIn_V2.0.0.zip"

Write-Host "Downloading [$url]`nSaving at [$path]" 
$client = new-object System.Net.WebClient 
$client.DownloadFile($url, $path ) 
#create destination directory
$LocalAppDir = [Environment]::GetFolderPath("LocalApplicationData")
$OpenliveWriterDir = $LocalAppDir + "\OpenLiveWriter"

#just in case there are multiple versions installed, or there's an upgrade, enumerate the application binary folders
$appDirectories = Get-ChildItem $OpenliveWriterDir | Where-Object {$_ -like "app-*"};

foreach ($appDirectory in $appDirectories) {

    #Create destination directory
    $targetDir = $appDirectory.FullName + "\Plugins"
    if(!(Test-Path -Path $targetDir )){
        Write-Host "Creating path $targetDir"
        New-Item -ItemType directory -Path $targetDir

    #decompress file into target directory
    Write-Host "Expanding $path to $targetDir"
    Expand-Archive $path -DestinationPath $targetDir

    #update config file
    $configFileName = $appDirectory.FullName + "\OpenLiveWriter.exe.config"
    [xml] $xml = gc $configFileName

    #create the new element
    $newitem = $xml.CreateElement("loadFromRemoteSources")

    #if it doesn't already exist in the file, add it and save
    if (!$xml.SelectSingleNode("//loadFromRemoteSources")) {



Powershell : Get Process Stats

At work the other day I found myself needing to gain some minimal process information. I mainly use .NET for my day to day existence (trying to learn Erlang right now argghh), but yeah day to day right now its .NET, so I am obviously aware of the .NET Process class, and what it brings to the table.


I am also aware of using Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems. As such you may also use WMI queries from .NET which you may read more about here http://www.codeproject.com/Articles/12138/Process-Information-and-Notifications-using-WMI


Thing is for my purpose I had to use a purely command line solution, so using .NET code was out, sure I could have created a small Console App, but I just felt there was a better tool for the job. Enter PowerShell.


My Requirements

I simply wanted to grab all processes matching a certain name, and grab a property value from each process matching that name, and export that tom either CSV or XML. I figured this should be something that I could easily do in PowerShell. So lets examine this step by step


Step 1 : Grabbing all processes matching a criteria

Lets say we want to grab all instances of the “notepad” process. This is how we could do that in PowerShell


Get-Process "notepad"


This yields this result




Cool, so we have some properties for each process. Mmm interesting, I wonder if we can grab some of those properties, which is what I need to do.


Step 2 : Grabbing the property value of interest for the matched processes

One of the really really great things about PowerShell is that you can pipe the results of one operation to the next (using F# a bit I have come to love the pipe operator). That means I should be able to use these Processes that I have and try and pipe them into another PowerShell operation that extracts one of the properties. Lets try that next. I came up with this (say I wanted to grab just the “Handles” information)


Get-Process "notepad" | Select-Object Handles


Which yields this result. See the “handles” is the only thing remaining for the “notepad” process



If you wanted to be a bit more verbose about how you get these results the following also works, which yield exactly the same results as those above

Get-Process | Where-Object {$_.ProcessName -eq 'notepad'} | format-table -property Handles
Get-Process | Where-Object {$_.ProcessName -eq 'notepad'} | Select-Object Handles


Ok so what have we achieved so far?


Well we have managed to grab only the processes we are interested in by name, and grab  the value of only the property we care about for each of these processes (note only one instance of notepad.exe was running for the screen shots above). Ok, so we are doing well,  not much left to do, we simply need to export this to CSV or XML.


Step 3a : Export to CSV

Ok lets exporting the data to CSV, must be a way right? Sure enough PowerShell doesn’t let us down, here is how:


Get-Process "notepad" | Select-Object Handles  | Export-Csv file.csv


Which gives us the following CSV file


#TYPE Selected.System.Diagnostics.Process



Step 3b : Export to XML

Exporting to an XML file is just as easy, here is how:


Get-Process "notepad" | Select-Object Handles  | Export-Clixml file.xml


Which gives us the following XML file

<Objs Version="" xmlns="http://schemas.microsoft.com/powershell/2004/04">
  <Obj RefId="0">
    <TN RefId="0">
      <I32 N="Handles">421</I32>


And there you go, job done……Hope that helped at least someone


PowerShell : Http Get/Post

This is another article in my on going learning/experimenting with PowerShell. This time I will show how you can use PowerShell to carry out REST operations such as GET/POST.

Now there may be some amongst you, who go why didn’t you just use WGet, which is a downloadable thing, and I could have indeed used that, except for the part that the machine I need to run this on, is so locked down that I can only use things that are already installed. So raw PowerShell it is

Here is the relevant PowerShell code, which allows 3 parameters to control the script

  • Target : The url
  • Verb : This is the http verb, GET, PUT etc
  • Content : This could be some content when doing a POST request for example

It just makes use of some very standard .NET classes namely WebRequest

    [string] $target,
    [string] $verb,      
    [string] $content
write-host "Http Url: $target"
write-host "Http Verb: $verb"
write-host "Http Content: $content"
$webRequest = [System.Net.WebRequest]::Create($target)
$encodedContent = [System.Text.Encoding]::UTF8.GetBytes($content)
$webRequest.Method = $verb
write-host "UTF8 Encoded Http Content: $content"
if($encodedContent.length -gt 0) {
    $webRequest.ContentLength = $encodedContent.length
    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($encodedContent, 0, $encodedContent.length)
[System.Net.WebResponse] $resp = $webRequest.GetResponse();
if($resp -ne $null) 
    $rs = $resp.GetResponseStream();
    [System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;
    [string] $results = $sr.ReadToEnd();
    return $results 
    exit ''

Here is an example usage (assuming the above script is saved as http.ps1 somewhere):

Http.ps1 -target “http://www.google.com” -verb “GET”

Which would give the following sort of output:


Anyway that’s it for now, hope this helps


PowerShell : Create MSMQ

AT work I use MSMQ I fair bit, and I also use NServiceBus a fair bit of late, which thankfully takes care of creating all the queues needed. But, for those time when you really need to make a bunch of queues, it can be a time consuming exercise, so I decided to see if my new found PowerShell skills could automate this process (remember I am still learning, so this may not be the best/most current way, in fact  know for Windows 8.1/Windows Server there is a later more groovy API. But for now this is what I came up with







function printUsage() 
    Write-Host "Usage is CreateQueue.ps1 -queueName SomeQueuName 
		-isTransactional $true -isJournalEnabled $true 
		-userName mclocal\barbers -isAdminUser $true"

try {

    $fullQueueName = ".\private$\" + $queueName

    If ([System.Messaging.MessageQueue]::Exists($fullQueueName))
        Write-Host($fullQueueName + " queue already exists")
        $newQ = [System.Messaging.MessageQueue]::Create($fullQueueName, 
        if ($isJournalEnabled)
            $newQ.UseJournalQueue = $True

        if ($isAdminUser)
            Write-Host("NOT ADMIN")
catch [Exception] {
   Write-Host $_.Exception.ToString()


This will allow you to create a private queue of your choice of name, where you can also pick the following

  • Whether its a transactional queue
  • If journaling is enabled
  • If its an admin user queue

Hope it helps


Powershell To Clean Visual Studio Bin/Obj folders

One of my old WPF Disciple buddies William Kempf read my last post, and alerted me to yet another useful PowerShell Command to clean all the BIN and OBJ folders of a Visual Studio solution.

Here is Williams version

gci -inc bin,obj -rec | rm -rec -force

In Williams own words

That wipes out all of the “bin” and “obj” directories in the current directory and every subdirectory. Super useful to run in your workspace directory to get to a “clean” state, especially when someone messes up and there’s something that a Clean or Rebuild inside the IDE doesn’t catch.

For those of you reading that may not know, PowerShell supports command aliases, here it is rewritten again not using the aliases

Get-ChildItem -inc bin,obj -rec | Remove-Item -rec -force

NOTE : You should have this stored in a PowerShell file and place that file at the root of your solution (where the .sln file resides), and then run it when you want a proper clean (not the micky mouse one that VisualStudio does, and reports success too).

If you want to know a commandlet alias you can use the following PowerShell commandlet to find the full commandlet name:

Get-Alias gci

Which when run for this example will give something like this:



Powershell : Killing all processes of name

Now I am just starting with PowerShell, so I will likely come up with some ridiculously simple examples.

One of thing I really like about PowerShell is the ability to pipe things from one CmdLet  to another.

Imagine you want to get all instances of the the running process “notepad” and kill them.

This is easily achieved using the following code

GetProcess "notepad" | StopProcess


Like  I say this is ridiculously simple, and hardy worthy of a blog post at all, but I aim to build a set of common tasks posts, and this will just form one of those.

So until next time


Powershell selecting from SQL Server

I am just getting into PowerShell, and today a work colleague of mine stated he has a table in SQL server that he needed to examine. The table contained names of files on the disk drive. He then needed to examine the names of the files in the table, and if the file existed rename it to include todays date. He asked if this could be done in PowerShell, at lunch I decided to try it and came up with this:


Say I have this table

USE [SachaTest]

/****** Object:  Table [dbo].[Files]    Script Date: 10/22/2014 13:59:07 ******/


CREATE TABLE [dbo].[Files](
      [FilePath] [nvarchar](max) NOT NULL


Which was populated like this

INSERT INTO [SachaTest].[dbo].[Files]
INSERT INTO [SachaTest].[dbo].[Files]

Where I have the following directory on disk


I then came up with the following PowerShell file to carry out the work as described in the opening paragraph of this article

    Establish SQL connection, and grab the stuff from the 
   "Files" table
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source=omnidev;Initial Catalog=SachaTest;
	Integrated Security=True;Timeout=180;MultipleActiveResultSets=true;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select * from Files"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
	Processes each DataRow handed to it, where it will grab the FilePath" column value within the DataRow
	and shall create a new file in the format of currentFilenameDDMMYY
Function ProcessFile (){
    Process {
          # use the column called "FilePath" to grab the file name from within the DataRow
          $fileOnDisk = New-Object -TypeName System.IO.FileInfo($_["FilePath"])
          write-host "full name is : " + $fileOnDisk.FullName
          $datePartForFile = (Get-Date -format d).Replace("/","")
          $justFileName = [System.IO.Path]::GetFileNameWithoutExtension($fileOnDisk.FullName)
          $newFileName = $fileOnDisk.DirectoryName + '\' + $justFileName + '_' + 
			$datePartForFile + $fileOnDisk.Extension
          write-host "new file name is : " +  $newFileName
          If (Test-Path $newFileName){
               Remove-Item $newFileName
          [System.IO.File]::Copy($fileOnDisk.FullName, $newFileName);
# Skip null objects filter
filter Skip-Null { $_|?{ $_ } }
	Loop through the DataSet.Tables[0] (where this will be the Files table, 
	which only has one column called "FilePath"
	then process each file by calling the "ProcessFile" function
$DataSet.Tables[0] |
Select-Object $_.Rows |
Skip-Null |

Which when run gives the following results