PowerShell for Windows Admins


September 2, 2013  3:28 PM

Get-Alias surprise

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

On the principle that any day on which you learn something new is not a complete waste I stumbled over this today:

Get-Alias has a –definition parameter

I’d always done this

Get-Alias | where Definition -eq ‘select-string’

now I can save some typing

get-alias -Definition ‘select-string’

Easy

September 2, 2013  11:29 AM

Winter Scripting Games–maybe?

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Did you enjoy the Summer Scripting Games? Do you want more?

We are exploring the possibility of running a Winter Scripting Games – see http://powershell.org/wp/forums/topic/winter-games-2013/

This will be a team event (minimum of 2) that would run late this year or early next year.

Interested?

Add a comment with your thoughts on the process and the timing to the thread at the above URL


September 1, 2013  1:56 PM

Get-Command trick

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

A useful trick with Get-Command. Use the –ListImported parameter

Get-Command -ListImported -CommandType cmdlet

shows the cmdlets imported into your session

Get-Command -ListImported -CommandType function

shows the functions imported into your session

Get-Command –ListImported

shows cmdlets and functions

useful for knowing what you’ve imported against what’s available


September 1, 2013  4:57 AM

Find the key of a WMI class

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

At least one property of a WMI class will be marked as a key. This information is held in the property Qualifiers which is a collection of data. The key is needed if you need to create an instance of the class. I’ve shown how to find the key with Get-WmiObject before but not with the new CIM cmdlets.

Its actually easier with the CIM cmdlets

$class = Get-CimClass -ClassName Win32_Process

foreach ($property in $class.CimClassProperties) {

$property | select -ExpandProperty Qualifiers |
foreach {
if ($_.Name -eq ‘key’){
$property
}
}

}

Get the CIM class. Iterate over the properties and expand the Qualifiers of the property. Check the names of the qualifiers for key & when you find it print out the property data


August 31, 2013  2:18 PM

Server Core Module

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

On a Windows Server 2012 system you will find a ServerCore module with two cmdlets

Get-DisplayResolution
Set-DisplayResolution

On a full GUI system the cmdlets work

PS> Get-DisplayResolution
1366×768
1280×1024

And thats it! Not a lot but it shows the basic information

You set the resolution like this
Set-DisplayResolution -Width 1366 -Height 768

If you look in the functions both actually call the setres command!


August 31, 2013  8:21 AM

Third Age of PowerShell

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

We’re now firmly in the Third Age of PowerShell.

The First Age covered the betas and PowerShell 1.0

PowerShell was adopted by developers and admins (with a scripting background) that saw the need for better automation tools and went looking for them. Information was sketchy, and every new discovery of how to do something generated a blog post.

Exchange 2007 relied on PowerShell for some activities but most admins only used it when they had to and in a very begrudging way. The moans about functionality that was only available through PowerShell went on & on

while ($true){
Write-Host “Why can’t I use the GUI”
}

PowerShell was very niche with a relatively small number of (very vocal) supporters and was viewed as something that had to be used rather than a tool admins were comfortable with.

The Second Age started with the release of Windows Server 2008 R2 and PowerShell 2.0

Many of the functionality gaps were filled and PowerShell came of age. Microsoft made PowerShell support mandatory for all products – some did it better than others which is still true to day.

Admins began to sit up and take notice as the body of information grew. Blogs began to die away though which is a shame in many ways.

The Scripting Games cut over to being PowerShell only.

The start of the Third Age is defined by the release of PowerShell 3.0 and Windows Server 2012. The amount of PowerShell functionality has gone through the roof – there are still bits of the PowerShell functionality in Server 2012 I haven’t touched.

Admins are beginning to embrace PowerShell. The last 12 months or so I’ve heard a lot of statements that start “I can use PowerShell to do that..”

PowerShell is here to stay and its a must learn technology. The self-proclaimed industry experts are now jumping on the bandwagon and pushing PowerShell as if they invented it.

So where do we go from here.

PowerShell 4.0 will be with us in October with the availability of Server 2012 R2. It has some evolutionary features but I don’t think there’s anything revolutionary.

We’ll still be in the Third Age.

The Fourth Age will start when the majority of admins use PowerShell as a matter of course and you can’t really work on the Windows platform without it.

Come on Microsoft – Make my day & remove the GUI permanently from Windows Server.


August 31, 2013  6:16 AM

Travelling devices

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Disclaimer: The following is based on my personal experiences and needs that may well not match yours. Feel free to disagree with my conclusions. I offer my insights to help others decide on the devices that suit them.

I’ve been using a number of devices over the last six months or so and found they all have problems. They have seemed to settle into niches though.

Microsoft Surface RT.

The great thing about this is that it has the Microsoft Office installed. Complete versions of Word, Excel, PowerPoint and OneNote. The email client is reasonable – its the standard Windows 8 mail app. It also shares settings with my other Windows 8 devices. And best of all it has PowerShell installed. PowerShell is constrained and restricted but it is very useful. The fact that it has a full size USB port makes movign files between devices very easy. The stand is a brilliant idea that makes using it on a desk much more comfortable.

The aspect ratio is 16:9 rather than the more common 4:3 which makes using it as a reader a bit awkward. Its also too big to be used comfortably as an e-reader.

Mainly used for meetings, conferences and writing while travelling. I’ve written several chapters of my latest book on it and though the touch keyboard isn’t brilliant it is more than usable.

Number 1 choice for working.

Kindle Fire HD

This is my device of choice if I’m on holiday. Very good size as an e-reader and good email client. The apps are OK but the screen is too small to work on documents except for a quick skim read. The web browser is fast. Linking to my main laptop is easy through a USB cable which makes transferring files simple.

iPad

This is the least useful of all my devices. The Kindle app is flashy with the simulated page turning but it isn’t comfortable to hold for long periods. The fact that you have to link through itunes to move files around is a pain. It is useful reading technical books due to the screen size. The retina display that’s raved about doesn’t look any better to my eyes than any of the other devices. The email client is so-so. It still reports the number of unread messages incorrectly. The on screen keyboard isn’t very well laid out – especially the odd characters like # where you have to go to a third level. The web browser is so and unresponsive.

Apart from being another screen when researching through technical books its not used that much. Definitely the one I could live without.

The best e-reader of all for long distance flights/trains is still my simple Kindle device!

I still have a netbook that runs Windows 8. It’s used when I need a full Windows 8 device that’s got a small footprint.


August 30, 2013  11:09 AM

Filtering AD searches

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Interesting question came up regarding how you define a Filter when you are searching for particular users. With the Microsoft cmdlets you can define a filter or an ldapfilter.

In these examples we’re looking for users that don’t have email addresses. First lets look at a filter

PS> Get-ADUser -Filter {mail -notlike “*”} | select Name, objectclass | group objectclass -NoElement

Count Name
—– —-
776 user

The filter is looking for any user accounts that have a mail attribute that isn’t like any characters – in otherwords empty. The advantage of using the –Filter parameter is that the syntax is easy and is what you’re used to in other PowerShell cmdlets such as Where-Object.

The LDAP filters get a bit more complicated

PS> Get-ADUser -LDAPFilter “(&(objectCategory=user)(!mail=*))” | select Name, objectclass | group objectclass -NoElement

Count Name
—– —-
776 user

Same results but the filter is much more difficult to understand

“(&(objectCategory=user)(!mail=*))”

& means AND

! means NOT

so this reads as

objectcategory=user AND NOT(mail = anything)

The advantage to using an LDAP filter is that you can re-use it on the GUI tools or directorysearcher

You need to be careful if you use Get-ADObject instead of Get-ADUser. Using the same LDAPFilter as above is fine

PS> Get-ADObject -LDAPFilter “(&(objectCategory=user)(!mail=*))” | select Name, objectclass | group objectclass -NoElement

Count Name
—– —-
776 user

but if you change objectcategory to objectclass which seems reasonable you get very different results:

PS> Get-ADObject -LDAPFilter “(&(objectClass=user)(!mail=*))” | select Name, objectclass | group objectclass -NoElement

Count Name
—– —-
30 computer
776 user
2 msDS-ManagedServiceAcc…
1 msDS-GroupManagedServi…

Huh! – Computers?

This because computers, users and managed service accounts all derive from the same AD schema class – users BUT they have different objectcategories to separate them.

There’ll be a lot more on searching AD and LDAP filters in AD management in a month of lunches – www.manning.com/siddaway3


August 30, 2013  4:29 AM

Setting an IP address

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I need to add an IP address to an adapter. I could use the GUI or WMI but with Windows 8/2012 and above I’ve got all of the nifty networking cmdlets to play with.

Lets start with finding the adapter to use

PS>Get-NetAdapter

will show all of the adapters. Unlike ipconfig it only shows real NICs – thats physical and virtual but not stuff like “Tunnel adapter Teredo Tunneling Pseudo-Interface”

The one I’m interested in is

Name ifIndex Status
—- ——- ——
Connections 21 Up

You can find the IP addresses associated with this NIC

PS>Get-NetIPAddress -InterfaceIndex 21 -AddressFamily IPv4

IPAddress : 10.0.50.100
InterfaceIndex : 21
InterfaceAlias : Connections
AddressFamily : IPv4
Type : Unicast
PrefixLength : 24
PrefixOrigin : Manual
SuffixOrigin : Manual
AddressState : Preferred
ValidLifetime : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource : False
PolicyStore : ActiveStore

To add the IP address use:

New-NetIPAddress -InterfaceIndex 21 -AddressFamily IPv4 -IPAddress 10.0.18.100 -PrefixLength 24

Job done.

If you have to do this on a regular basis you can script finding the adapter and setting the IP address in one pass


August 29, 2013  3:03 PM

Protecting your csv files

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I’m using csv files for this example but it applies to other types of file as well. Let’s produce a csv file
Get-ChildItem -Path C:\Users\Richard\Documents -File |
select FullName, Length, LastWriteTime |
Export-Csv files.csv

This gives a small, useful set of data for the purposes of this post.
You can read the data back in:
Import-Csv .\files.csv

You have decided you need to keep a record of how these files are changing over time. You have further decided that you will create a csv file for each individual day you run the command. The individual files will carry the date as part of the name.
You can create the file name incorporating the date like this:
$file = “Files_$( (get-date -Format “s”).Split(“T”)[0]).csv”

Creating the csv file then becomes:
Get-ChildItem -Path C:\Users\Richard\Documents -File |
select FullName, Length, LastWriteTime |
Export-Csv $file

You can read the file using $file or its name
Import-Csv $file
Import-Csv Files_2013-08-29.csv

Ideally you only want to produce this file once a day and don’t want to overwrite an existing file. Rather than building your own checks you can use the –NoClobber parameter on Export-Csv. If you try to overwrite an existing file you will get an error:

£> Get-ChildItem -Path C:\Users\Richard\Documents -File | select FullName, Length, LastWriteTime | Export-Csv $file -NoClobber
Export-Csv : The file ‘C:\scripts\Files_2013-08-29.csv’ already exists.
At line:1 char:97
+ … astWriteTime | Export-Csv $file -NoClobber
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceExists: (C:\scripts\Files_2013-08-29.csv:String) [Export-Csv], IOException
+ FullyQualifiedErrorId : NoClobber,Microsoft.PowerShell.Commands.ExportCsvCommand
The –Force parameter won’t override the -NoClobber
£> Get-ChildItem -Path C:\Users\Richard\Documents -File | select FullName, Length, LastWriteTime | Export-Csv $file -NoClobber -Force
Export-Csv : The file ‘C:\scripts\Files_2013-08-29.csv’ already exists.
At line:1 char:97
+ … astWriteTime | Export-Csv $file -NoClobber -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceExists: (C:\scripts\Files_2013-08-29.csv:String) [Export-Csv], IOException
+ FullyQualifiedErrorId : NoClobber,Microsoft.PowerShell.Commands.ExportCsvCommand

This technique is useful when you have automated processes producing your files. If the process can be run multiple times per day and you want to preserve the first set of data produced then use –NoClobber.
There are other cmdlets with a –NoClobber parameter:
£> get-help * -Parameter NoClobber

Name
—-
Import-Module
Export-Console
Export-Alias
Export-Clixml
Export-Csv
Export-FormatData
Out-File

-NoClobber isn’t infallible –for instance you could explicitly delete the file but it does add a useful level of protection.


Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: