April 2009 - Posts

How many bytes?

I was playing around with PowerShell and started thinking about the kb, mb etc values and I realised I didn’t know what they really looked like.  1kb is 1024 but it gets very hazy after that. So how could I see the values stacked up

1kb,1mb,1gb,1tb,1pb | foreach{"$_".PadLeft(16)}

works.  We feed in the list of values. Pipe into foreach and use string substitution to display.  That will left justify the display.  By padding the left of the display with spaces we can effectively right justify the field to give

            1024
         1048576
      1073741824
   1099511627776
1125899906842624

So now you know what the stack of xbytes looks like

We can also achieve the same effect using

1kb,1mb,1gb,1tb,1pb | foreach{"{0,16}" -f $_}

Hmm.. wonder how effort is involved to produce a Tower of Hanoi script from this

Technorati Tags: ,,
Posted by Richard's space

Creating a process

I've looked at creating a process before - using [WMIClass].
 
With CTP3 we have a few more options
 
Start-Process -Filepath notepad.exe
 
Invoke-WMIMethod -Class Win32_process -Name Create -ArgumentList notepad.exe
 
Set-WMIinstance -Class Win32_process -Arguments @{Path=c:\windows\system32\notepad.exe}
 
The first two just happen.  The third option will throw an exception because it can't find the instance and then create one.
 
Three options - which to use.  In this case probably start-process but the invoke-wmimethod is useful.
Posted by Richard's space
Filed under:

PowerShell verbs

If you haven't seen the post on PowerShell standard verbs from the PowerShell team it is worth reading - http://blogs.msdn.com/powershell/archive/2009/04/22/soliciting-new-verbs.aspx
 
If you have an idea for a new verb - make sure you make it known
Posted by Richard Siddaway's Blog
Filed under:

PowerShell remoting options

One of the big pieces of functionality in PowerShell v2 is the ability to directly administer remote machines.  A number of cmdlets get a computername parameter for working directly. The main push for remoting is through the *-PSsession cmdlets

Enter-PSSession
Exit-PSSession
Export-PSSession
Get-PSSession
Import-PSSession
New-PSSession
Remove-PSSession

New-, Get and Remove- I have blogged about before.  The interesting ones are the Enter/Exit and Import/Export pairs.

Enter-PSsession enables you to work directly in the session – as if you had RDP’d into the machine and were running PowerShell on the box.  It means we don’t need to use Invoke-Command as much. Exit-PSsession steps back out of the session but leaves the session open.

Import-PSsession enables you to import functionality from the remote session into your local PowerShell session.  For instance you can import the 2008 R2 AD cmdlets into your local session.  They show up as functions rather than cmdlets but are fully usable.

Export-PSsession saves PowerShell command types (cmdlets, functions etc) to a module that can be loaded at any time into a session.

There is a lot of flexibility and power built into the remoting system that should allow you to get a way of working that suits you.

Technorati Tags: ,,
Posted by Richard Siddaway's Blog
Filed under:

Too ambitious?

Been looking at Exchange 2010.  It installed OK on Windows 2008 R2 Beta and seemed to run OK.  I have come across a few issues:

  • Exchange Management Console doesn’t start properly and doesn’t run properly
  • The new Remote PowerShell functionality doesn’t work (against Windows 7)

I think this is due to trying to work two betas together.  I’m going to put Exchange 2010 onto Windows 2008 SP1 and see what happens when I use PowerShell CTP 3 against it.

Apart from the Exchange 2010 looks good.  The way Exchange 2010 uses PowerShell has changed significantly – especially for remote access.  Really makes remote PowerShell the way to go.

I hope that the RTM timings can be sorted so that Exchange 2010 RTM will work properly on Windows 2008 R2.  Be a big shame to have to wait for Ex 2010 SP1 for this combination.

 

Technorati Tags: ,,
Posted by Richard Siddaway's Blog
Filed under:

AD attributes

I had a question come through as a private message regarding how to extract a particular attribute for user objects. The script wasn’t working because the label name in AD Users and Computers didn’t match the attribute name. This is a fairly common scenario as there are quite a few attributes like this for instance in the GUI the label is First Name but the AD attribute that we need to access in our PowerShell scripts is givenName (capitalisation isn’t mandatory).

How can we find the correct attribute.  I tend to dive into ADSIEdit. I pick a test user. Set the value of the attribute in question to something obvious using the GUI then look it up in ADSIEdit.

Another way is to use the information on msdn - http://msdn.microsoft.com/en-us/ms677980(VS.85).aspx.  There is a set of User Object User Interface Mapping tables one for each tab in the GUI.

At http://msdn.microsoft.com/en-us/ms677286.aspx you can find a link that covers mapping for computers, domains, groups, OUs printers and users.

With this information easily available and much of it defined as parameters in the AD cmdlets (Win 2008R2 and Quest) accessing AD objects in scripts becomes much easier. 

Technorati Tags: ,

Sorting

Sorting is a fairly common activity in PowerShell.  One scenario I don’t see very often is a requirement to sort in two different directions.  I have a list of users and their last logon dates – I want to sort users into alphabetical order (ascending) and lat logon into descending order.

001
Import-Csv logons.txt | sort @{Expression="Name";Descending=$false},@{Expression="LastLogon";Descending=$true}

We have to use a hash table for the fields and the direction if we want different sorting directions.  Looks a bit messy but works a treat.

Technorati Tags: ,
Posted by Richard Siddaway's Blog
Filed under:

User Module – local account

Back in February - http://richardsiddaway.spaces.live.com/blog/cns!43CFA46A74CF3E96!2099.entry – I showed a module I had created to generate a new password.  Its time to return to that module.  I am going to expand it to work with local user accounts. Then I’ll add AD accounts.

I have a script that I wrote a while back to work with local accounts

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
## To create a user on the local machine
## add the assembly
Add-Type -AssemblyName System.DirectoryServices.AccountManagement

## create a password
$password = Read-Host "Password" -AsSecureString
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "userid", $password


## create the context i.e. connect to the domain
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, "pcrs2"

## create the user object
$usr = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $context

## set the properties
$usr.SamAccountName = "Newuser1"
$usr.SetPassword($cred.GetNetworkCredential().Password)
$usr.DisplayName = "New User"
$usr.Enabled = $true
$usr.ExpirePasswordNow()

## save the user
$usr.Save()

 

Add-Type is PowerShell v2 and you will need .NET 3 to use the Accountmanagement classes.  Given where we are in the Windows 7 lifecycle (a feeding frenzy in the press over when the RC will ship) I will be concentrating on PS 2

The script reads a password (we’ll replace that with a call to new-password) and uses the Accountmanagement classes to create the user account

The line

Add-Type -AssemblyName System.DirectoryServices.AccountManagement

becomes

# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @("System.DirectoryServices.AccountManagement")

in the module manifest.  This is good as I load it once and it will be available for all of my functions.

## create a password
$password = Read-Host "Password" –AsSecureString

becomes

$password = ConvertTo-SecureString -String $(new-password 8) -AsPlainText -Force

for a standard password. I’ll put switch parameters in later for a stronger password

so as a first pass the function looks like this

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
function new-user {
    [CmdletBinding()]
    param (
        [Parameter(Position=0,HelpMessage="The loginid")]
        [string]$id , 
       
        [Parameter(Position=1,HelpMessage="The Display name")]
        [string]$name 
       
    )   
    ## create a password
    $password = ConvertTo-SecureString -String $(new-password 8) -AsPlainText -Force
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "userid", $password

    ## get the machine
    $pc = $env:computername
    ## create the context i.e. connect to the domain
    $ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
    $context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ctype, $pc

    ## create the user object
    $usr = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $context

    ## set the properties
    $usr.SamAccountName = $id
    $usr.SetPassword($cred.GetNetworkCredential().Password)
    $usr.DisplayName = $name
    $usr.Enabled = $true
    $usr.ExpirePasswordNow()

    ## save the user
    $usr.Save()   
}

 

We can look at groups next.

Posted by Richard Siddaway's Blog
Filed under:

Forest and domain modes

We can find the forest and domain modes using the following commands

Get-ADDomain -Identity grayson | select DomainMode

Get-ADForest grayson | select forestmode

The modes can be set from the GUI as normal or

Set-ADDomainMode -Identity grayson -DomainMode Windows2008R2Domain
Set-ADForestMode -Identity grayson -ForestMode Windows2008R2Forest

Not that you will be using these cmdlets very often

 

Two PowerShells

Windows Server 2008 R2 is 64 bit only so we we get two instances of PowerShell and ISE.  One (64bit version) is just labelled Windows PowerShell V2 and Windows PowerShell V2 ISE.  The 32bit version has (x86) appended to the name.

One point to watch for – the 64 and 32bit versions have different execution policies – you need to set both

Technorati Tags: ,,
Posted by Richard Siddaway's Blog
Filed under:

PowerShell for DBAs

Chad has a very interesting post on “The Value Proposition of PowerShell to DBAs” - http://chadwickmiller.spaces.live.com/blog/cns!EA42395138308430!347.entry where he discusses the results of a poll of DBAs regarding PowerShell.

On initial reading it is a bit depressing for the PowerShell community as only 20% of respondents were using PowerShell. However, it gets a bit more cheerful if you consider that another 40% were planning to – I wonder how that will change as SQL Server 2008, with PowerShell built in, becomes more widespread.

Chad gives a number of benefits of learning PowerShell. I think that one of the most compelling reasons si that it will be a part of all future Microsoft products – look what is happening with Windows 2008 R2 – an provides a common automation platform across your Microsoft estate. PowerShell gives us the possibility of integrated, automated administration across you servers and applications.

Gives us more time for PowerShel space invaders

Technorati Tags:

Windows 2008 R2 PowerShell for AD

Back in this post http://richardsiddaway.spaces.live.com/default.aspx?_c01_BlogPart=blogentry&_c=BlogPart&handle=cns!43CFA46A74CF3E96!2214 we looked at creating OUs using the AD cmdlets in Windows 2008 R2. 

We may want to look at the OUs we have in our domain

Get-ADOrganizationalUnit -Filter {Name -like "*"} | Format-Table name, distinguishedname -AutoSize

or we may want to search for a user

Get-ADUser -Identity Richard

As regular readers will be aware I am a big fan of the Quest AD cmdlets – so I wanted to see how the Win08R2 cmdlets compared.

Creating a new user is relatively straight forward

New-ADUser -SamAccountName "fdrake" -Name "DRAKE Francis" -AccountPassword (ConvertTo-SecureString -AsPlainText "Passw0rd!" -Force) -Enabled $true -ChangePasswordAtLogon $true -GivenName "Francis" -Surname "Drake" -Path "OU=England,OU=AllUsers,DC=grayson,DC=test"

I like the ability to enable the account at the same time as we create it.  I don’t like the convolutions with the password I would probably look to move that part to a separate statement and use a variable as the value for the cmdlet if I was bulk creating users.   For creating users the two sets of cmdlets are comparable. The differences are more or less balanced.  I would be happy using either.

Searching for users is another matter.  These variants work

Get-ADUser -Filter {Name -like "*drake*"}
Get-ADUser fdrake

Some other options such as using the name don’t.  My feeling is that the Quest tool is better at this aspect of working with AD.

The AD provider I find very clumsy at first impression.  Using the distinguished name involves a lot more work than seems necessary. I’ve used the PowerShell Community Extensions provider in the past and the navigation in that does seem neater.  However, the advantage of the R2 provider is that I get access to the configuration and schema partitions as well so maybe it isn’t all bad. Need to do some more work with this one.

One feature that I am excited about in R2 is the recycle bin for AD.  The forest & domain level need raising to Windows 2008 R2 and then we can run

Enable-ADOptionalFeature 'Recycle Bin Feature' -Scope Forest -Target 'grayson'

where the target is the name of the forest.

Next job is to look at using the recycle bin.

PowerShell Modules and Exchange 2010 prerequisites

PowerShell v2 introduces the concept of modules – these can be scripts or dlls (think snapin from V1).  The modules that are loaded into PowerShell can be viewed by using get-modules.  When you install roles\functions onto Windows 2008 R2 the PowerShell functionality is delivered as modules.  Use

Get-Module -ListAvailable | Select Name

To see the available modules.  Most modules appear to be 32bit only – at least in the beta

Exchange 2010 delivers functionality as snapins

PS C:\Scripts> Get-PSSnapin -Registered

Name        : Microsoft.Exchange.Management.PowerShell.E2010
PSVersion   : 1.0
Description : Admin Tasks for the Exchange Server

Name        : Microsoft.Exchange.Management.PowerShell.Setup
PSVersion   : 1.0
Description : Setup Tasks for the Exchange Server

Name        : Microsoft.Exchange.Management.Powershell.Support
PSVersion   : 1.0
Description : Support Tasks for the Exchange Server

One of the modules is for Server Manager

Import-Module ServerManager

Expect to see error messages about loading extended type data if you have other modules already loaded.  As long as the message ends with  File skipped because it was already present from "Microsoft.PowerShell".    then we are good to go.

Server Manager gives us three cmdlets

Get-Command -Module ServerManager

Add-WindowsFeature
Get-WindowsFeature
Remove-WindowsFeature

Get-Windowsfeature will display all of the features with an indication of which are installed. The display name and the name by which we access the feature are displayed

Display Name                                            Name
------------                                            ----
[ ] Active Directory Certificate Services               AD-Certificate
    [ ] Certification Authority                         ADCS-Cert-Authority
    [ ] Certification Authority Web Enrollment          ADCS-Web-Enrollment
    [ ] Online Responder                                ADCS-Online-Cert
    [ ] Network Device Enrollment Service               ADCS-Device-Enrollment
    [ ] Certificate Enrollment Web Service              ADCS-Enroll-Web-Svc
    [ ] Certificate Enrollment Policy Web Service       ADCS-Enroll-Web-Pol
[X] Active Directory Domain Services                    AD-Domain-Services
    [X] Active Directory Domain Controller              ADDS-Domain-Controller
    [ ] Identity Management for UNIX                    ADDS-Identity-Mgmt
        [ ] Server for Network Information Services     ADDS-NIS

etc

Exchange 2010 has a number of prerequisite features that need installing.  Unfortunately the documentation gives them using ServerManagerCmd.  This will never do.  Ok the PowerShell equivalent is

Add-WindowsFeature -Name RSAT-ADDS-Tools, RPC-over-HTTP-proxy, NET-HTTP-Activation, Web-Dyn-Compression, Web-Windows-Auth, Web-Digest-Auth, Web-Basic-Auth, Web-Lgcy-Mgmt-Console, Web-Metabase, Web-ISAPI-Ext, Web-Server -Concurrent

If required the features can be installed individually. The PowerShell remoting features enable us to perform these actions on remote servers as well as the local server. 

The module system in PowerShell v2 makes dynamic configuration of your PowerShell environment much simpler and more flexible

Posted by Richard Siddaway's Blog
Filed under:

Exchange 2010

Exchange 2007 has been a poster child for PowerShell.  The GUI is layered over PowerShell cmdlets and everything can be performed at the PowerShell prompt.  There are some activities that can only be performed at using PowerShell.

The Exchange 2010 beta became available this week.  It has lots of good stuff for Exchange people but the important news is that the use of PowerShell remains – in fact it gets better.

Exchange 2010 beta requires PowerShell v2 CTP3.  This gives us access to the remoting and asynchronous processing capabilities – think mailbox provisioning as a background task. 

Put Exchange PowerShell together with the PowerShell functionality in Windows 2008 R2 and we really will be into a PowerShell world.

I will be posting some examples of the two together as soon as my virtual machine finishes building – its a sloooooooow process.

Technorati Tags: ,,
Posted by Richard Siddaway's Blog
Filed under:

PowerShell goes to work

I was working this past weekend. PowerShell saved me lots of time and effort for instance:

  • use the Quest cmdlets to move subnets between sites.  One by hand isn’t too bad but by the time you have tens of the things it gets tedious.
  • moving DCs between sites
  • checking replication is working properly & forcing a replication so I can test (both those scripts are in my book)
  • checking the contents of GPOs
  • adding accounts to AD & local groups
  • etc

The more you use it the more you find to do with it – I haven’t quite got to the point of 2+2 in PowerShell but its only a matter of time  ;-)

Technorati Tags:
Posted by Richard Siddaway's Blog
Filed under:

Interesting Posts

A couple of interesting posts I came across.

First up is a way to work with System Center Configuration Manager using PowerShell.  http://blogs.technet.com/mniehaus/archive/2009/04/07/fun-with-configmgr-2007-and-powershell.aspx

Some of the System Center family have PowerShell support but not Config Manager.  Hopefully this will be corrected in the next release.

The second post was from Jonathan – a UK User Group member – on working with the registry and using the functions supplied by PowerShell MVP Shay Levy - http://jonathanmedd.blogspot.com/2009/04/putting-shays-powershell-registry.html

Enjoy

Posted by Richard Siddaway's Blog
Filed under:

Select-String

One task I had to do a a few times recently is track down which GPOs had a particular setting enabled.  If you are working in an environment with a signifcant number of GPOs this can be a tedious task.
 
The easier way - use the SDMSoftware GPMC cmdlets to create an XML file for each GPO. You can then use select-string to search through the GPOs for the setting you need.  The real advantage that searching is so quick that you can have multiple attempts to refine your search and still do it much quicker than checking manually in GPMC.
 
 

Modules in Windows 2008 R2

One thing I have noticed with my quick dip into Windows 2008 R2 is that the extra functionality is all loaded as modules.  This is a new area in PowerShell v2 that enables you to load\unload functionality from your PowerShell sessions.  Modules can be "libraries" of functions as I showed in a recent set of posts or they can be compiled dlls with cmdlets.  The good thing about compiled modules is that you don't have to register them in the same way you do snapins.  Much easier to work with. I would expect snapins to disappear in (much) future version of PowerShell (!!!! My opinion only !!!!) as modules do the same role role and more.
 
There are a number of default modules that are available when you first install R2 including:
  •  File Transfer
  • PSdiagnostics
  • TroubleShootingPack
  • AD Rights Management

As you add functionality - such as running dcpromo other modules are installed.  You only get the PowerShell modules for the functionality you install.  It appears, at least in the beta, that even though Windows 2008 R2 is 64 bit - most of the PowerShell functionality is 32bit.  Compare the modules folder in the two PowerShell install directories.

 
Posted by Richard Siddaway's Blog
Filed under:

Windows 2008 R2 - OU

One of the big benefits of Windows 2008 R2 is the fact that PowerShell v2 is installed by default and that AD can be administered by PowerShell.  There are 76 AD cmdlets and an AD provider.  We’ll start by looking at the cmdlets.

Organizational Units are the subdivisions with a domain.  We can easily create a new OU.

New-ADOrganizationalUnit -Name "AllUsers" -ProtectedFromAccidentalDeletion $true

The default location is to create OUs in the root of the domain.  I really like the ability to set Protection from Accidental Deletion on when I create the OU.

If I want to create a child OU I just need to add the path to the OU in which I want to create the OU.


New-ADOrganizationalUnit -Name "RemoteUsers" -Path "OU=AllUsers,dc=grayson,dc=test" -ProtectedFromAccidentalDeletion $true

We also have Get-, Set- and Remove-OrganizationalUnit cmdlets.

The Get returns a Microsoft.ActiveDirectory.Management.ADOrganizationalUnit object – NOT a directory entry object.  We need to use the other cmdlets to work with the OU.

PowerShell in Practice- Chapter 11

Chapter 11 on AD topology has been posted on Mannings early access site - http://www.manning.com/siddaway/

Enjoy

Posted by Richard Siddaway's Blog
Filed under:
More Posts Next page »