Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Friday, 24 June 2011

Online cmdlet help

Not long after PowerShell v2 was released I did a presentation to most of the tech staff in the department which I pretty much simply wanted to use as an opportunity to give them a heads-up that they had better start thinking about upping their knowledge of PS.  Apart from demo-ing some of the cool stuff you could do with PowerShell I wanted to make sure that the audience left remembering three simple things that would help them help them start using it:

  1. verb-noun
    Cmdlet format is simply ‘what do you want to do’ hyphen ‘what do you want to do it to?’.
  2. get-command
    Want a list of available cmdlets?  This’ll do it.
  3. get-help
    If you can remember 1 & 2 then this cmdlet is all you need to learn more.

The get-help cmdlet uses locally stored info so is current at the time of installation and in the majority of cases is sufficient.  Something I found out yesterday was that you can use the –online parameter with get-help and if you’ve got a connection to the outside world i will bring up the most up-to-date help on TechNet, e.g.

get-help –online get-acl

will load…

image

Saturday, 21 May 2011

Hex / Binary / Decimal / Octal number conversion in WinDbg

Normally if I need to do any conversions between different number formats I’ll just do it in my head (yeah, right!) or load calc.exe.   A while back one of my posts showed how easy it was to convert numbers in PowerShell e.g.

[Convert]::ToString(734, 2)

will convert 734 to binary, and

[Convert]::ToString(179, 16)

will convert 179 to hexadecimal.

It’s just as easy to do it in WinDbg if you need to do any conversions while debugging using .formats.  The benefit of .formats is that it will give you all the available conversions it can, so if you were to enter .formats 0y1100011 you would see:

image

To make sure that WinDbg is aware of the number format you are entering as a parameter you give it the relevant prefix: 0y (binary), 0x(hexadecimal), 0t (octal) & 0n (decimal).  You can also set the default number base using the n command which means all numbers entered will be interpreted as such. Just entering n will show the current number base e.g.

image

And to change it to octal…

image

Tuesday, 19 April 2011

Doing a 'start /wait' in PowerShell

Countless times I’ve had to write a script that would start a process, normally some sort of installation routine, but have needed to ensure that the process had finished doing its thing before passing control back to the script.  Normally if you’re writing a batch/cmd file you’d do something like this..

start /wait notepad.exe  

..or in VBscript something like this..

Set objShell = Wscript.CreateObject("Wscript.Shell")
objShell.Run("notepad.exe"),1,True  

As part of our Windows 7 rollout here at the Uni I want to reduce the number of startup/shutdown & logon/logoff scripts and if we have to script something then it would be done in PowerShell.  As such I’ve needed to reproduce the ‘start /wait’ type functionality that I’ve used before in .cmd & .vbs scripts in a .ps1.  After a bit of research seems like the easiest way to do it is with something like this:

$process = [System.Diagnostics.Process]::Start("notepad.exe")
$process.WaitForExit()  

And passing parameters is easy as well, you just need something like:

$process = [System.Diagnostics.Process]::Start("notepad.exe","c:\temp\sometextfile.txt")
$process.WaitForExit()  

Thursday, 14 April 2011

Less is not always more

In the past I’ve made various posts giving examples of how PowerShell can be perfect for the the lazy sysadmin through not having to type as much.  This can be done through using aliases instead of the full cmdlet and truncating parameters (only available with PS v2 remember, you old-school v1 users will have to upgrade).  For example, why type all of…

Get-ChildItem u:\scripts -Include *.ps1 –Recurse

…when you could simply type…

 gci U:\Scripts -i *.ps1 –r

For simply running stuff from within PS the shorter version is ideal.  Problem arises when you start to copy-and-paste your one-liners into a script, that then gets put into production, that then might have to be revised / debugged / fixed by someone else in the future?  Am guilty as charged as have done this myself on numerous occasions, in an attempt to affirm my alpha-geek status.  Trouble is it all falls apart when one of your team asks you what one of your scripts is doing and you struggle to come up with a reasonable explanation.

So what lessons am I going to try and learn from this?

  • If I’m going to insist on trying to make my typing as little as possible I’ll back up my code with enough comments (but then kind of defeats the object of reduced typing!)
  • Use full cmdlet and parameter names in scripts (and comments!) as if I don’t its only going to come back and bite me anyway.

Monday, 11 April 2011

Assigning multiple values in PowerShell

Some time ago I posted a PS one-liner to display the number in the Fibonacci sequence up to 10000000.  I learnt something new about PowerShell today regarding assigning values to variable so thought I’d use the same one-liner to demonstrate.  Originally I assigned a starting value to two variables separately, like this…

$1 = 0; $2 = 1;

The neat trick I found today was that you can do the same with…

$1,$2=0,1;

…which now makes the one-liner now look like…

$1,$2=0,1;$3=$1+$2;do{$3;$1=$2;$2=$3;$3=$1+$2} while ($3 -lt 10000000)

Makes for slightly less typing (well one less “=” anyway, but they all add up for the lazy sysadmin), but its just continues to prove that PowerShell is so flexible in how it lets you use it.

Wednesday, 8 December 2010

Send email using PowerShell

I like it when you come across something new and today’s nugget is the PowerShell cmdlet Send-MailMessage.  I’ve used mailing scripts with VBS in the past, for example when I wanted email notification when a script had finished but the beauty of the PowerShell method is that you can do it with a single line of code.  As a bare minimum all you need is something like:

image

Okay, so I did say that you only needed a single line of code but I used the back-tick (highlighted) just to make it more readable.

You can find the TechNet article on the Send-MailMessage cmdlet here.

Tuesday, 7 December 2010

Checking BADMIFS

Recently there has been a slight increase in the number of files appearing the BADMIFS folder on one of our SCCM servers.  Given that these files get assigned a seemingly random name the only way to identify which client machine they’ve come from to identify any pattern is to open each one.  If you’ve only got a couple of BADMIFs then this task isn’t too onerous but anymore than that you need to look to automate the checks.  What I came up with was a…wait, can you guess?…PowerShell script that checks if there are any BADMIFS on either server and if found then extracts the particular line that contains the computer name and outputs it all to a text file.  A sanitised version of the code I came up with is below:

image

Tuesday, 2 March 2010

Thursday, 11 February 2010

PowerShell on an iPhone…almost!

I’ve been lucky enough to have been issued with an iPhone as a replacement for my HTC S740 Windows Mobile device.  I’m trying not to get too attached to it as it might be possible that someone may decide to pull rank on me and it may end up being reallocated as quickly as it arrived, but like most things Apple it’s a pretty nice device.  Anyway, since I’ve had it I have inevitably trawled the AppStore looking for useful applications to allow me to be more productive at work with my work supplied device.  So far..Lego Photo, BubbleWrap, AirCoaster, Sky News, Sky Sports Football Centre, Met Office Weather, Paper Toss and an app to turn my iPhone into a Star Wars light sabre….well, you get the idea.  But that was until yesterday when into my Inbox arrived an email from Sapien updating me on their products (I’ve used PrimalScript as my scripting environment for years and I’m yet to find anything better).  Lo and behold there’s a PowerShell app for the iPhone that contains full descriptions for all PS v1 cmdlets.  Installed it and it looks pretty good, and now I’m happier as I’m now doing something almost work-related on my new device.  Details on the app can be found here.

Tuesday, 15 December 2009

Defragmenting drives with PowerShell: updated

A while back I posted about how it was possible to defrag a disk with PowerShell but ended the post saying that I would probably never need to use it.  Turns out that I did need to after all…

It had been quite some time since I’d defragmented either the drive in my main PC at home or any of the external hard drives connected to it.  What I wanted to to be able to do with a PowerShell script was:

  1. Identify all local hard drives,
  2. Work out how defragmented the drive is,
  3. Defrag the drive,
  4. Show how much less it is fragmented afterwards,
  5. Log it all to a file
  6. Then shutdown the PC (given that if I’m sitting in front of this PC I tend to be playing Team Fortress 2 I wanted it to run when I’d finished then shut the box down.  I know that defrag will fall back into the background if it detects that the user is doing anything but given my n00bTF2 skills I can’t afford to hamper my performance!).

Using the code I posted previously as a starting point, turned out that it was pretty easy to achieve everything I wanted the script to do…

image

  1. Identify all local hard drives using Win32_Volume class, checking that DriveType equals 3 (a local drive) and that there is a drive letter assigned,
  2. then use the Win32_DefragAnalysis class to work out how fragmented the drive is,
  3. then use Defrag Method associated with the Win32_Volume class,
  4. repeat step 2,
  5. Log it all using the start-transcript and stop-transcript cmdlets,
  6. and finally shutdown the PC using the stop-computer cmdlet.

This will only run on Vista and later and needs to be run elevated, but it means that I can defrag my drives and shut my PC down without having to leave it on and rely on scheduling and it’s one less excuse I have for being beaten on TF2 again….

Friday, 20 November 2009

Preventing boredom with numbers (and PowerShell) #3: Maths magic…

I recently read an article in the paper version (how old fashioned!) of Wired that told how you could impress friends and colleagues with a simple number trick:

Get someone to think of a number, ask them to double it, add 12, halve it, then subtract the number that they started with.  You can then amaze them by telling them that the answer is 6!

Obviously I wanted to prove this theory so I knocked up a PowerShell script that does the same calculation for each number between 1-100000 (it was originally a one-liner but I added line breaks here for readability)…

$y=1;

do{$x=((($y*2)+12)/2)-$y;"Start with $y, end up with $x";$y++}

while ($y -le 100000)

Okay, so it’s not the most useful bit of PS but at least you’ve got a bit of mathematical magic to impress people with…

 

Friday, 26 June 2009

So you work in IT…?

Once again the unwritten rule of ‘you work in IT therefore you are expected to know everything about any device that is powered by elastic-trickery and has some sort of user-input (normally buttons)’ came into play today.  Was it a case of “how would I list all installed MS updates on my PC using PowerShell?” or something similar?  Errr, no.  It was “how do I create contact groups on my Nokia mobile?”  Guess it goes with the territory of my chosen career path…

Anyway, today wasn’t all bad.  My copy of Windows Internals 5th Edition was waiting at home for me.

Oh, and if you did want to list the installed MS updates using PS…

image

Tuesday, 9 June 2009

Defrag a disk with PS…

At various points during the Config Manager course I was on last week there were some inevitable lulls to proceedings whilst waiting for the virtual machines to do their thing.  To fill the time I revisited the Win32 classes documentation on MSDN (okay, surely I could have found something more interesting to browse, but once a geek always a geek…).  There I came across a class that I hadn’t spotted before: Win32_DefragAnalysis.  Straight away I started to think “hmm, can I check a disk and then defrag it if required using a PS script…?”.  Granted, any normal person would have thought “Hmmm, boring.  Maybe I’ll just start an InPrivate browsing session and find something more interesting…”, but I digress.  It turns out that it’s quite easy, use Win32_Volume to identify what drive you want to analyse/defrag then use that to hook into Win32_DefragAnalysis/Win32_Defrag…

image

Win32_DefragAnalysis & Win32_Defrag are only available on Server 2003 and higher.  I tested this on Win7 and it ran fine, but it needs to be run elevated.

Will I ever need to use a script to defrag a drive?  Probably not, but it’s nice knowing that I could if I wanted to…

Saturday, 6 June 2009

PS on Win7 RC: The same but different…

It turns out that a few changes have been made between the CTP3/Win7 Beta version of PowerShell and the version that comes with Win7 RC.  Microsoft MVP Oishin Grehan has posted a good summary of the differences here.

Wednesday, 6 May 2009

BITS on Win 7

A while back I posted about the ability to leverage BITS with PS v2, some of the really cool things being that it’s a network friendly way of transferring large amounts of data and that once the transfers are running they can survive connectivity-loss or even a reboot.  I started to take a look at this again today, this time using PS on Win7, but when I ran the script that had previously worked it bombed out.  Before you can do anything BITS-related in PS you need to load the required module, so I did the same again hoping to identify the error…

image

And there was the answer, turns out that with the version of PS that ships with Win7 the module name changed, so running…

get-module –ListAvailable

…showed that the module name was now BitsTransfer.

image

Yay!  So after importing the correct module name I was back in business.

image

Note that the cmdlet names have changed as well.

Tuesday, 5 May 2009

Meeting prep…

I’m trying to use Windows 7 as much as possible (I’ve installed it on a Toshiba A600 and it seems to be running pretty well) and that means leaving my trusty but ageing M400 running Vista in the cupboard. My scripting tool of choice is Primal Script but it’s still on my M400 so I’ve been using the PowerShell ISE that ships with Windows 7. I had to attend what I knew would be a boring meeting this morning so in preparation I decided to print some PS code I’d been working to take with me (and hopefully not get caught doing so by the other attendees!). It was at that point that I discovered that the ISE doesn’t have the ability to print! I’ve never noticed before as I’ve done pretty much everything through Primal Script, although given that it still only (I think) the CTP I shouldn’t really complain if it’s missing a couple of features, although printing does seem pretty fundamental. Just meant that I had to actually pay attention during the meeting…

Friday, 1 May 2009

Quadrillions of bytes…

With PowerShell v1 came a set of administrative constants that made it easier to easily display storage values in MB, GB etc.  PS v2 has gone even more enterprise-class as shown below:

image

Yep, you can easily report disk space in terabytes and petabytes.  So this bit of code…

image

 

…shows how much space I’ve got free on my C: drive in petabytes.  Even with a 134GB of free space on the notebook I did this on I had to format the output to 5 decimal places to show a readable value!

Wednesday, 22 April 2009

PowerShell in 15 minutes

If you've got 15 minutes to spare and want an overview of PS v2, brought to you by Jeffrey Snover, then check this out. This was a presentation he did at Lang.NET 2009, and if you can keep up it's well worth a look. You want end up knowing PS as a result but you'll have a pretty good idea about how powerful it is.

Monday, 13 April 2009

Preventing boredom with numbers (and PowerShell) #2

Towards the end of last week I started to look at how I could get a PowerShell script to generate a list a list of Perfect Numbers. It's not that I wanted to know what they are (that's what Google is there for), I just wanted to see if I could code it up in PS. Given the nature of Perfect Numbers, the first thing is to identify those numbers that are proper positive divisors of the starting number eg: 6 is the first Perfect Number as the sum of the proper positive divisors (1, 2, & 3) equal the starting number.
The basic premise was to code the division (easy), then check to see if the result was a whole number, cast all the results into an array and then see if the sum of the numbers in the array equalled the starting number, then start the process again incrementing the starting number by one.
First hiccup was to how to check whether the result of the division was a whole number. A post to the Scripting Guys Forum on TechNet on Saturday night prompted a number of suggestions as to how I could do this (thanks to all who replied!). Being lazy I've gone for the (hopefully!) least typing option and that is to perform a check on the result of the division with something like this:
$result = 6/2
if ($result -is [int]){write-host "It's a whole number"}
That's as far as I've got in what is probably the next installment of my series of 'Preventing boredom with numbers (and PowerShell)' postings, but fear not dear avid reader, I will keep you updated as to how my latest sleep-inducing PS project is progressing...

Friday, 27 March 2009

No excuse now...

After a particularly uninspiring and pretty awful week at work, there was one nugget of tech goodness that I uncovered this afternoon: Powershell is now available for deployment via WSUS! I'd already built a deployment script using VB that did the pre-req checks etc but I'd delayed using it in the hope that it would appear on my WSUS boxes. It did earlier this week (it's classed under Feature Packs), so early next week I plan to do a couple of test deployments and then release it to PCs in my department. The really good thing is that I can now start putting some of my dev scripts (each time I put a new VBS script into production I produce the equivalent PowerShell script) into use live environment.
If PowerShell appearing as an update on my WSUS boxes was the highlight, you kind of appreciate how bad the last working week was....