PowerShell snippets



Recursively copy folders and files from 1 machine to another

 Get a GUID



Remoting across HomeGroup PCs

See here

Copy files greater than a given size from the local to another machine (in your domain or workgroup)

gci *.mid | where {$_.Length -lt 0.5kB} | Copy-Item -Destination \\dennis-pc\c$

Copy a single file to another destination

Copy-Item -Path .\test01.mid -Destination \\dennis-pc\c$\test01.mid

Find a string pattern in files

gci .\*.txt -Recurse | Select-String -Pattern “information”


Get the unique lines from Get-History

The command to get from the first screenshot to the second screenshot is this:

Get-History | % { $_.CommandLine } | select -Unique

This slideshow requires JavaScript.

And remember to can easily do this to the clipboard:

Get-History | % { $_.CommandLine } | select -Unique | clip

Recursively copy folders and files from 1 machine to another

The local / source machine…


The target / remote machine, where I happen to know there is a shared folder [sandbox]…


Just check the box is pingable first (in fact a 10″ £120 Windows tablet)…

So from the current directory, look for a folder [Jan]. Recursively copy all of its content to an existing share on the the [Den-Tab] tablet, with the name [sandbox]:

Copy-Item -Path .\Jan -Recurse -Force -Destination "\\DEN-TAB\sandbox"

Basically it all worked very nicely – all my home PCs are now on Windows 10, maybe not that it is responsible for any smoothness… or maybe it is:


Remove lines from a file based on an index or indexes

  • This reads a file into $content
  • Counts the records
  • Declares and initializes a dynamic array $tempOutput
  • If the line does not contain space at index 21 (zero-based) and does not contain a space at index 51, then it adds the line to $tempOutput
  • The content of $tempOutput is written to a file

$content= Get-Content -Path .\x.ps1
$tempOutput = @()
$content | % {if ($_[21] -ne " " -and $_[51] -ne " "){
    $tempOutput += $_}
else {
    write-host "bad"}
$tempOutput | Out-File -FilePath .\goodFile.txt


To be clear, there is nothing significant about the indexes at 21 and 51 in this case, they are just an example.

Stopping and starting services

My article here

Find files with a given wildcard, recursively

way faster than Windows Search, and more trustworthy…

gci -Include *.rx2 -Recurse -File -ErrorAction SilentlyContinue


Copy to the clipboard, via Get-history, in this case…


Write command history (Get-history) to a file

$hist = Get-History
$hist | Export-Csv -Path .\AzureBackupHistory.csv

A bunch of text for testing your text file handling against, from Pride and Prejudice – thanks to Project Gutenberg for the text

They’re using a SHA-1 certificate, but we can forgive them that
Using this you could test line counts, search and replace, record truncation, find max,min,average line length, the words, etc.
It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.
However little known the feelings or views of such a man may be on his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters.
"My dear Mr. Bennet," said his lady to him one day, "have you heard that Netherfield Park is let at last?"
Mr. Bennet replied that he had not.
"But it is," returned she; "for Mrs. Long has just been here, and she told me all about it."
Mr. Bennet made no answer.
"Do you not want to know who has taken it?" cried his wife impatiently.
"You want to tell me, and I have no objection to hearing it."
This was invitation enough.
"Why, my dear, you must know, Mrs. Long says that Netherfield is taken by a young man of large fortune from the north of England; that he came down on Monday in a chaise and four to see the place, and was so much delighted with it, that he agreed with Mr. Morris immediately; that he is to take possession before Michaelmas, and some of his servants are to be in the house by the end of next week."
"What is his name?"
"Is he married or single?"
"Oh! Single, my dear, to be sure! A single man of large fortune; four or five thousand a year. What a fine thing for our girls!"
"How so? How can it affect them?"
"My dear Mr. Bennet," replied his wife, "how can you be so tiresome! You must know that I am thinking of his marrying one of them."
"Is that his design in settling here?"
"Design! Nonsense, how can you talk so! But it is very likely that he may fall in love with one of them, and therefore you must visit him as soon as he comes."
"I see no occasion for that. You and the girls may go, or you may send them by themselves, which perhaps will be still better, for as you are as handsome as any of them, Mr. Bingley may like you the best of the party."
"My dear, you flatter me. I certainly have had my share of beauty, but I do not pretend to be anything extraordinary now. When a woman has five grown-up daughters, she ought to give over thinking of her own beauty."
"In such cases, a woman has not often much beauty to think of."
"But, my dear, you must indeed go and see Mr. Bingley when he comes into the neighbourhood."
"It is more than I engage for, I assure you."
"But consider your daughters. Only think what an establishment it would be for one of them. Sir William and Lady Lucas are determined to go, merely on that account, for in general, you know, they visit no newcomers. Indeed you must go, for it will be impossible for us to visit him if you do not."
"You are over-scrupulous, surely. I dare say Mr. Bingley will be very glad to see you; and I will send a few lines by you to assure him of my hearty consent to his marrying whichever he chooses of the girls; though I must throw in a good word for my little Lizzy."
"I desire you will do no such thing. Lizzy is not a bit better than the others; and I am sure she is not half so handsome as Jane, nor half so good-humoured as Lydia. But you are always giving her the preference."
"They have none of them much to recommend them," replied he; "they are all silly and ignorant like other girls; but Lizzy has something more of quickness than her sisters."
"Mr. Bennet, how can you abuse your own children in such a way? You take delight in vexing me. You have no compassion for my poor nerves."
"You mistake me, my dear. I have a high respect for your nerves. They are my old friends. I have heard you mention them with consideration these last twenty years at least."
"Ah, you do not know what I suffer."
"But I hope you will get over it, and live to see many young men of four thousand a year come into the neighbourhood."
"It will be no use to us, if twenty such should come, since you will not visit them."
"Depend upon it, my dear, that when there are twenty, I will visit them all."
Mr. Bennet was so odd a mixture of quick parts, sarcastic humour, reserve, and caprice, that the experience of three-and-twenty years had been insufficient to make his wife understand his character. Her mind was less difficult to develop. She was a woman of mean understanding, little information, and uncertain temper. When she was discontented, she fancied herself nervous. The business of her life was to get her daughters married; its solace was visiting and news.

And here are some ideas for free…

$content = Get-Content -Path C:\temp\pride.txt
$content | Measure-Object -Property length -Minimum -Maximum -Average -Sum
$content| % {$_ -replace "You", "Thou dost"}

Yes, the last line gives you some nonsense, but that’s part of the fun, ain’t it? ☺
And try this msdn site for more on Measure-Object.


Get a random integer between 0 or 1 and some calculated upper limit

Get-Random -Minimum 1 -Maximum ("myasdfadf").Length

Output your path in a more easily readable format

$a = $env:Path; $a.split(";")

Add an item to your path for the life of the session

$env:Path += ";C:\windows\Microsoft.NET\Framework64\v4.0.30319;"

Another way of presenting the path

gci env:path | Format-Table -Wrap

Remote scripting

function Do-It() {



$session = New-PSSession -ComputerName Den-Tab

Invoke-Command -Session $session -ScriptBlock {

$VerbosePreference = $using:VerbosePreference

Write-Verbose “Test”



A way of creating unique-ish names…

Providing that you are creating eg. files sequentially, and don’t need to create more than 10,000 per second, then this gives a perfectly good way of creating uniqueish names…

$fileName = "AccountsRandomName"+(Get-Date).Ticks+".txt"

Well, that’s what I thought… however if you ran this through a loop 10 times, you get duplication.

(1..10) | % { "AccountsRandomName"+(Get-Date).Ticks+".txt" }


You may need to sleep (sorry) for a tick before moving to the next iteration, giving something like this…


(1..10) | % { "AccountsRandomName"+(Get-Date).Ticks+".txt" ; [system.threading.thread]::sleep(10) }

Getting records meeting criteria from a text file



Creating random data for testing

The idea being that you then paste this into a column in Excel or somesuch

zip codes

1..100 | % { Get-Random -mi 10001 -ma 99999} | clip


US style phone numbers

1..100 | % { "($(Get-Random -mi 101 -ma 999)) $(Get-Random -mi 101 -ma 999)-$(Get-Random -mi 1001 -ma 9999)"} | clip


Random floats

1..10 | % { Get-Random -Minimum 0.0 -Maximum 1422.0}


Random floats to 2 places

1..10 | % { [math]::Round($(Get-Random -Minimum 0.0 -Maximum 1422.0),2)}


and remember that as a general principle you can always append [ | clip ] to these commands to get the output in to the clipboard, if that is most convenient for you.

Random Dates


Get the date 5 days ago…


Get a thousand lots of the date 1000 days ago (sure, why would you)…

1..1000 | % { $([datetime]::UtcNow).AddDays(-1000).ToString("o")}

Get a thousand lots of a random date between now and (about) a year ago…

1..1000 | % { $randomDay = Get-Random -mi 0 -ma 365; $([datetime]::UtcNow).AddDays(-$randomDay).ToString("o")}



Number formats


To a literal “AB”, append a number formatted to have a specific length, padded out with leading zeroes, e.g. “AB00000024”. Do this for a range, in this example, of 1 to 100:

1..100 | % { "AB" + $($_).ToString("D9") }

Build a folder structure for a HTML/JavaScript project

Used elsewhere, and sufficiently useful for me to keep a copy here


$htmlDevRoot = "d:\build\HtmlDevDir"
$appDir = "BikeMaintenance"
$fullAppDirPathRoot = "$htmlDevRoot\$appDir"
New-Item -Path $fullAppDirPathRoot -ItemType Dir
$subfolders = @("app","app\feature1", "app\feature2", "common", "common\services","css","fonts","images","js")
$subfolders | % {New-Item -Path "$fullAppDirPathRoot\$_" -ItemType Dir}

Regex in PowerShell

Example here

$pattern = "SeqNum=`".*`"" # "any and all characters within the double quotes are ignored for pattern-matching (in addition to SeqNum etc having to match)
$updatedPatternStart = "SeqNum=`""
$updatedPatternEnd = "`""

$r = [regex] $pattern
$result = $r.Match($currentLine)

if ($result.Success) {
        $foundLiteral = $result.Value
$updatedLine = $currentLine -replace $foundLiteral, $replacementString

Useful links


Write a sequence of faceted codes to the console or a file…





Given a column of data (e.g. in Excel, Sheets), convert it to a delimited string (using PowerShell)

If I have an input like this in any spreadsheet:

One way is this:



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s