Archive for the Category PowerShell


Grow Your PowerShell

We’ve spent some time looking at PowerShell and every time we get better at it.

Some confusion arises from the use of custom functions but we have on method that’s shown to work.

First, we’re working off a set of external sources from some of our new best friends.

We found a discussion at, here, that provides us with the code to support a specific use case that’s always driving us nuts, proving that a user ID and password is good or bad. This is remarkably handy when working with service accounts that are supported by a bunch of neanderthals in a cage labeled “Windows Support.”

Then we have another discussion, here, that helps us with some PoSh function management stuff.

And, finally, our new best friend, Don, explains a bit here about executing a number of commands on a list on inputs piped in one at a time.

So, here goes…

You can create a function interactively from your PoSh prompt one line at a time.

PS C:\Windows\system32> Function WriteSomethingOnScreen {
>> Write-Host "Something"
>> }
PS C:\Windows\system32>

In that code, note the following:

  • The function amounts to the word “function,” the function name and some code inside {curly braces}.
  • When you start building a function, PoSh figures it out and turns your <path>> prompt into an interactive, “>>” prompt.
  • When you feed the >> prompts a blank line, it jumps out of interactive mode and back into your standard, <path>> prompt.

Now we have a function in memory and we can call it by name at the <path>> prompt:

PS C:\Windows\system32> Function WriteSomethingOnScreen {
>> Write-Host "Something"
>> }
PS C:\Windows\system32>

If we kill our PoSh session, the function dies with it.

Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\Windows\system32> WriteSomethingOnScreen
The term 'WriteSomethingOnScreen' is not recognized as the name of a cmdlet, fu
{Blah,blah, blah}
 + CategoryInfo : ObjectNotFound: (WriteSomethingOnScreen:String)
 [], CommandNotFoundException
 + FullyQualifiedErrorId : CommandNotFoundException
PS C:\Windows\system32>

Yes, we have to create our function all over again from scratch. Since that sucks, we’ll just write our function into a script in NotePad and save it, no problem.




Save the script and run it in PoSh:

First thing you’ll note is that, by default, PoSh will block scripts from running:

PS C:\Windows\system32> writesomethingonscreen.ps1
File C:\Windows\SYSTEM32\WriteSomethingOnScreen.ps1 c
e execution of scripts is disabled on this system. Pl
{Blah, Blah, Blah}
 + FullyQualifiedErrorId : RuntimeException
PS C:\Windows\system32>

So run:

PS C:\Windows\system32> Set-ExecutionPolicy Unrestricted

Execution Policy Change
The execution policy helps protect you from scripts that you
{Blah, Blah, Blah}
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"):
PS C:\Windows\system32>

Now PoSh will run your script.

PS C:\Windows\system32> WriteSomethingOnScreen.ps1
PS C:\Windows\system32>

Note also that the input is NOT case sensitive.

PS C:\Windows\system32> writesomethingonscreen.ps1
PS C:\Windows\system32>

So our script created our function and we should be able to run it now, right? Wrong. We actually have to call the function from the script to make it work by adding:

WriteSomethingOnScreen the bottom of the script and then running it.

PS C:\Windows\system32> writesomethingonscreen
PS C:\Windows\system32>

We’ll look at the list of inputs next time.

This is where we’re headed:

Function Test-Credentials {
 Param($context, $username, $password, $domain)
 Add-Type -AssemblyName System.DirectoryServices.AccountManagement
 $ct = [System.DirectoryServices.AccountManagement.ContextType]::$context
 $pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ct, $domain)
 New-Object PSObject -Property @{
 UserName = $username;
 IsValid = $pc.ValidateCredentials($username, $password).ToString()

Then, your command looks like this:

test-credentials <{"Machine" | "Domain"}> 
                 <User ID> 
                 <{Macine Name | Domain Name}>

Of course, replace the new lines with simple blank spaces.

This does a lot of cool stuff. Once it’s written into the PoSh memory you can run it like a CMDLT and pass it, with no commas, a context {machine or domain} a UID, a password and a domain or machine name and it will tell you if the UID and PW are correct.

We’ll look at it more closely next time.






PowerShell at the Document Library Level

Well it’s tough being a robot and always waiting for someone to ask you to do something and then you’ve got to figure out how to do it like yesterday.

Case in point, after we migrated 10,000 documents to the customer’s new SharePoint site they said “Well, all those are published; we need them unpublished.”

And you know how I hate the whole SharePoint version control, check out, publish routine but here we are and our answer is, of course PowerShell.

If you look at first, you’ll not find any specific cmdlets pertaining to libraries or documents. So good thing we have our new best friends to help.

First, here, Salaudeen, gives us a great look at extending the SPWeb object to the folder\library and then manipulate the items in it. Essentially, the routine is:

  1. Get-SPWeb by URL
  2. Set library variable to SPWeb.GetFolderand use the library name.
  3. Set files variable to Library.Files
  4. Call a Files.Add and pass it the library name, the file path\name and an overwrite variable, true or false.

That’s all good but there’s more at CodePlex here and here.

These ought to get you in business pretty quickly.



PowerShell Next Steps

Well, since we know all about PowerShell now, we’ll need to prove it by writing some scripts. To do that, we’ll need to understand about the PowerShell’s logical operators and we have some help for that from our new best friends, Guy and Neolisk.

Guy tells us all about the $_ operator here. We’ll use this with pipes in a line like this:

Get-Something | Write-Host $_.SomePropertyOfSomething

Then, Neolisk helps us here. He tells us about the $_. and alot of other special commands. My favorite is ‘n which will send a newline character to my output.



PowerShell Re-Introduction Part Five: PowerShell Rookie Review

Part One: More PowerShell: A Re-Introduction If You’re Starting from Scratch
Part Two: PowerShell Re-Introduction: Part Two
Part Three: PowerShell Re-Introduction Part Three: Script Prerequisites
Part Four: PowerShell Re-Introduction Part Four: Our First Script

So we’ve got cmdlets and script basics nailed down. We still have to look at a couple of things to shake off the “rookie” label.

For example, we might think we need a cheat sheet like this. And, of course, PowerShell.Com is the Bomb. They got this wicked cool example of adding a clock to your PowerShell console here.

So while we need to review all the details we’ve covered, let’s take a minute to look at what our friends have done that might help us extend our knowledge into more valuable spaces.

First, here’s a great video looking at PowerShell Maturity from Idera.Com and Tobias Weltner:

And here’s some more help with filters and pipes:

For example try this one:

Help Get-EventLog

What we see here is that we can go to a remote computer and get the system log and check the errors.

Finally, in a domain it’s less complicated because console and remote computer can share user credentials, but for non-domain computers or computers in different domains, we need to learn how to log in remotely. To help with that, we have this from TechNet:

What we see here is that running PowerShell commands that target remote computers requires two things:

  1. The remote target must be running the WinRM service.
  2. You have to run PowerShell as an administrator.

Most of this is taken care of using Enable-PSRemoting on the target. Of course, you get a lot smarter if you run:

Help Enable-PSRemoting

 Then, we get the money pitch from the Scripting Guy: Here‘s the fastball that explains how to log into a remote machine using a specific user ID and password.


PowerShell Re-Introduction Part Three: Spript Prerequisites

Part One: More PowerShell: A Re-Introduction If You’re Starting from Scratch
Part Two: PowerShell Re-Introduction: Part Two

So in our last two efforts, we tried to cover the PowerShell Command Line Interface (CLI) and the way it runs programs and cmdlets. Remember, we covered the way to get help regarding a cmdlet and the way to list all the available cmdlets.

This time, let’s explore that a little more and then see if we can begin to chain cmdlets together to form PowerShell scripts and manage those scripts in PowerShell’s native Integrated Script Editor (ISE.)

First, let’s look at what we already know and what the robot inside PowerShell might be trying to tell us.

We can run Get-Help. Part of what we get back is the Get-Help cmdlet’s syntax, including some examples:

Gety-Help Syntax

Get-Help Syntax

So as we see, we can run Get-Help for any of our cmdlets. But we can also just run plain old Help.

We can also just drop a -? after a cmdlet and get it’s help file. Let’s try the first example:

 Get-Help Get-Process and Get-Process -? return the same page:

Get-Process -?

Get-Process -?

If you read the synopsis, you get an idea of where we’re headed; with get-process, you can actually get a running process in Windows and make it do stuff, even from a remote computer.

But first things first. Let’s look at one we already know, get-command and see what we get with Get-Help Get-Command -full and look at the syntax and description:

Syntax and Desription for Get-Command

Syntax and Desription for Get-Command

 First, the syntax tells us we can select a single command, like get-process:

Get-Command Get-Process

Get-Command Get-Process

 But we can also filter for cmdlets or functions, etc. Try these:

  • Get-Command -CommantType cmdlet
  • Get-Command -CommantType Function
  • Get-Command -CommantType Alias

 The first just lists all our cmdlets.

The second lists all our functions. If you look at these:

Get-Command -CommandType Function

Get-Command -CommandType Function

You’ll see some functions that are intended to make PowerShell act like DOS. For example, you can log on to your D drive simply by typing D: and you can create a new directory using the mkdir function. But look at the far right column, Definition. Here we see some of how PowerShell works. Those functions are just a cmdlet with some added text. For example, D: is defined as Set-Location D: and mkdir is defined as … 

Okay, we get it. We’re not really sure what means but we understand that we can run functions that act like cmdlets.

But we can run a Help mkdir and we see we get the help for New-Item and mkdir is just a method of invoking New-Item to create a new folder. So let’s navigate down our root folder on C: using CDs.. and then create a PSTest folder using this New-Item cmdlet.


Here, we’ve lapsed into some kind of immeidate response mode and PowerShell is asking us for an item type. If we type Foo here, we’re going to get an error that says only “Directory” or “File” are acceptable values. So you can try that or just enter Directory.

And success; we can see and then log into our new folder:

Creating and Logging into a New Folder

Creating and Logging into a New Folder

Okay, you say, enough with this trivial mechanics, let’s build something.

Sure, when but the something we’re going to build is a script or function (we’ll start with a script) and in order to do that, you have to work your away around a PowerShell’s built in security called its ExecutionPolicy. Its Execution Policy is PowerShell’s way of determining if it can trust a script. Remember that, in PowerShell, you can do anything a user can do at the Windows GUI so running a script is like letting someone else sit down at your desktop, even if that someone is a monkey, or worse, a sick, evil mastermind monkey like GoGo JoJo from the PowerPuff Girls.

So let’s do this. Let’s run Get-ExecutionPolicy:



Ah, so, we’re Restricted, whatever that means. Well, to figure this our, let do this: Remember when we ran Get-Command?

One of the syntax options was -Noun. This means that we can get all our commands the involve our ExecutionPolicy with a Get-Command -Noun ExecutionPolicy:

Get-Command -Noun ExecutionPolicy

Get-Command -Noun ExecutionPolicy

So we see we can Get or Set our ExecutionPolicy. Well, yes, we run Get-Help Set-ExecutionPolicy -full.

Now there’s lots of gems here and some are more valuable than others:

  • We see that to set the exection policy, we actually have to start PowerShell by right clicking and selecting Run As Adminstrator.
  • We see that the execution policy can be assigned to the user, the machine or a process; the default is LocalMachine.
  • We see it protects configuration files including your PowerShell profile. We’ll need to know more about this, huh?
  • Our default policy is Restricted which means we can’t run scripts or configuration files.
  • We can require scripts to be “Signed” but that sounds like a technical challenge.
  • There’s stuff about Common Parameters we’ll have to cover.
  • There’s group policy restrictions that are override an ExecutionPolicy set in PowerShell.

That’s a lot of stuff. Let’s just restart PowerShell as an administrator and set our execution policy to Unrestricted and see what we can do realizing full well that if GoGo JoJo barges in, we are so screwed.

Let’s review:

  • Get-Help.
  • Get-Command with filters.
  • Native Functions.
  • Mimicing DOS commands.
  • Run As Administrator.
  • Execution Policy.


More PowerShell: A Re-Introduction If You’re Starting from Scratch

Any robot knows that robots are for doing things that people don’t want to do. For example, you would never want a robot to go to the rock show for you because you’d want to go yourself. On the otherhand, all this stuff you do everyday that drives you nuts are perfect for a robot and your robot’s favorite tool is probably PowerShell.

The latest versions of Windows gives you PowerShell by default. There’s some goofieness involved if you’re struggling to find it. Our new best friend, Liam, covers that in part here. But let’s just say you can go Start | Programs | Accessories | Windows PowerShell.

Here’s you should find two options: Windows PowerShell and Windows PowerShell ISE.

The latter option here is an integrated script editor. That will become a favorite but first, we need to understand the former option.

Click on Windows PowerShell and you’ll get a blue box.

PowerShell CLI

The Initial PowerShell Command Line Interface

 You can do some pretty cool things here including access the entirety of the PowerShell libraries that are installed. So, you may ask, what is a PowerShell library? Where did I get one or more of those? Am I missing any? I’m so confused.

Well, remember, robot are just like people and the first thing they want to do when they meet an attractive stranger is say “Hello.” If that breaks something, then our relationship was just not to be. We type Hello and hit enter.

Typical Error Message

The Error Message Returned by Unsuitable Command

Well, we are talking to a stranger and seems like he could be a little nicer but at least he is verbose and all in red, presumably to get our attention. Maybe he just didn’t understand. but, instead of going to all the trouble to type “Hello” again, we can just push our up arrow. That will reload our previous command. we hit enter and, no surprise, we get the same  response. And when we do that ten or twelve times, we get get a screen full of repetitive garbage and see our scroll bar moving down the right side of our window.

Here, I’ll give you one for free. Try cls and hit Enter.

Cleared Screen

The Cleared Screen After Running CLS

Ahhh. Sweet clarity.

Note here, now if you tap your up arrow, you get cls again and if you tap it again, you get Hello. This is very clever. In fact, no matter how many commands you’ve entered, tapping up will always give you the previous command. And, as you move back into your command history, you can tap the down arrow of back out of your history.

And just to set your mind at ease here and now and for all time, your commands are NOT case sensitive. Sure HELLO and Hello and hello all generate the same response but you’ll also see that CLS and cls and cLs all clear your screen.

So, let’s tap around until we can run that Hello command one more time and take a closer look. First, it says:

The term ‘hello’ is not recognized as the name of a cmdlet, function, script file, or operable program.


We need to get smarter about what these things are. I’m going to call them “suitable commands.” Obviously, a suitable command is a cmdlet, function, script file or operable program. Let’s start with the last item, an operable program. We know what these are and we have some. For example, we have a program called notepad.exe that lives in c:\windows\system32. So let’s type notepad.exe and hit enter.

Sure enough, Notepad opens.

Also note that while PowerShell opens in c:\windows\system32 and notepad.exe lives in the same folder, you can run a cd.. command twice and your PowerShell will be reading the c:\ root folder. You can run Notepad.exe here and still, Notepad will open. This implies that your PowerShell prompt is able to find the program in this different, remote folder, even if that folder lives on a different path.

Okay, one more robot trick. After you’ve cd.. twice, you can see that you’re in the root C:\ folder. Here, you can type cd pro

A Partially Entered Command

A Partially Entered Command

… and tap your Tab key and our new robot friend will fill in the friggin’ blanks suggesting we’re really trying to type cd program files but just got all lazy human-like.

Type Ahead Code Completion

Type Ahead Code Completion

And it gets even better. Say you’re crazy lazy, here you can just type, n and tap you tab key and our robot friend will give you the first suitable command that starts with the letter “n” …

Type Ahead Code Completion

The First Suitable Command Consistant with Partially Entered Command

In this case, we see, that’s a folder called .\NETGEAR. But we can can cotinue to tap the Tab key and our robot friend will cycle through all the suitable commands in the current folder and all the known paths and offer each of the suitable commands that begin with the letter “n” alphabetically. We can Tab  and Tab until we get to notepad.exe and hit enter and run Notepad.

So lets review:

Up Arrow – Loads previous command consecutively.

CLS – Clears the screen.

CMDLETs are NOT case sensitive.

Command line can open executables.

Command line can read from remote paths and folders.

Tab will try to complete any partially entered command.

That’s a lot for one robot in one day so let’s just plan on looking at those other suitable commands,  next time.