PowerShell for Windows Admins


December 14, 2012  8:26 AM

Registry oddity

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Looking at modifying the registry on a virtual machine while its offline. I mount the VHDX file and can run this  to load the registry

PS> reg load HKLM\VHDSYS h:\windows\system32\config\system
The operation completed successfully.

If I perform a reg unload at this point everything works but if I access the registry – for instance

PS> ls hklm:

and then try and unload I get an error!

PS> reg unload HKLM\VHDSYS
ERROR: Access is denied.

One thing I found is that there is as reference to the remote hive in the variable collection

PS> ls variable:

Name                           Value
—-                           —–
$                              HKLM\VHDSYS

Empirically I’ve found that running these commands

ls env:
ls variable:

changes the value of the $ variable

You can then unload the hive

PS> reg unload HKLM\VHDSYS
The operation completed successfully.

December 14, 2012  4:17 AM

PowerShell v3 installed modules

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

This is the list of installed modules in PowerShell v3 on Windows 8

AppLocker
Appx
BitLocker
BitsTransfer
BranchCache
CimCmdlets
DirectAccessClientComponents
Dism
DnsClient
International
iSCSI
ISE
Kds
Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host
Microsoft.PowerShell.Management
Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility
Microsoft.WSMan.Management
MMAgent
MsDtc
NetAdapter
NetConnection
NetLbfo
NetQos
NetSecurity
NetSwitchTeam
NetTCPIP
NetworkConnectivityStatus
NetworkTransition
PKI
PrintManagement
PSDiagnostics
PSScheduledJob
PSWorkflow
PSWorkflowUtility
ScheduledTasks
SecureBoot
SmbShare
SmbWitness
Storage
TroubleshootingPack
TrustedPlatformModule
VpnClient
Wdac
WebAdministration
WindowsDeveloperLicense
WindowsErrorReporting

This is the corresponding list on PowerShell v3 installed on Windows 7

AppLocker
BitsTransfer
CimCmdlets
ISE
Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host
Microsoft.PowerShell.Management
Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility
Microsoft.WSMan.Management
PSDiagnostics
PSScheduledJob
PSWorkflow
PSWorkflowUtility
TroubleshootingPack

As you can see there is quite a difference!

All of the Windows 8 modules that are highlighted in yellow are CDXML based.  They can’t be made available on Windows 7 because the underlying WMI classes aren’t available


December 12, 2012  2:18 PM

Creating Virtual machines #1: Creating the VM

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I’ve had two projects in mind for a while.  First I need to build a new WSUS server in my virtual environment & secondly I want to automate as much of the VM creation and configuration as possible. Oh – and I’m not using SC Virtual Machine Manager. 

I’ll be using the Hyper-V cmdlets that come with Windows 2012.

I covered some of this in PowerShell and WMI but that was for Windows 2008 R2 and I was using James O’Neills hyper-v functions. 

Does it get any easier with the cmdlets

This is what I came up with

function new-virtualmachine {            
[CmdletBinding()]            
param (            
 [parameter(Mandatory=$true)]            
 [string]$name,            
             
 [parameter(Mandatory=$true)]            
 [string]$path,            
 [Int64]$mem = 4GB,            
 [string]$vswitch = "Local Area Connection - Virtual Network",            
            
 [ValidateSet("Windows2012", "Windows2008R2", "Windows7")]            
 [string]$iso,            
            
 [switch]$startvm            
)            
            
Write-Verbose -Message "Testing VM Path"            
$vpath = Join-Path -Path $path -ChildPath $name            
if (-not (Test-Path -Path $vpath)){            
 New-Item -Path $path -Name $name -ItemType Directory            
}            
            
switch ($iso){            
 "Windows2012" {$isopath = "C:\Source\Windows 2012 RTM\en_windows_server_2012_x64_dvd_915478.iso"}            
 "Windows2008R2" {$isopath = "C:\Source\Window 2008R2\en_windows_server_2008_r2_standard_enterprise_datacenter_and_web_with_sp1_x64_dvd_617601.iso" }            
 "Windows7" {$isopath = "C:\Source\Windows7 RTM\en_windows_7_ultimate_x86_dvd_x15-65921.iso"}            
}            
            
New-VM -Name $name -MemoryStartupBytes $mem -Path $vpath -BootDevice CD -NewVHDPath "$vpath\$name.vhdx" -NewVHDSizeBytes 120GB -SwitchName $vswitch            
Add-VMDvdDrive -VMName $name -Path $isopath            
            
if ($startvm){Start-VM -Name $name}            
}

The new VM name and path are mandatory, I’ve set a default memory size of 4GB  and added a default Virtual switch. I’m adding the iso file containing the OS I want to install – that’s constrained by the set validation and I have a final parameter that allows me to start the VM.

if the path in which I want to create the VM doesn’t exist I create it.

A switch statement is used to set the full path to the iso file.

The New-VM cmdlet is used to create the VM based on the information provided.  I do hard code the fact that I’m setting the VM to boot from the CD and that the virtual disk will be 120GB

Add-VMDvdDrive is used to add the DVD drive to the VM (the controller location is automatically worked out) and the iso file mounted.

If the startvm switch is used then the VM starts and OS install commences. I’m deliberately NOT automating the OS setup at this time – that may be another project.


December 11, 2012  3:03 PM

PowerShell Jobs session recording

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

The recording, slides and demo scripts from tonight’s session on PowerShell Jobs is available from

https://skydrive.live.com/?cid=43cfa46a74cf3e96#cid=43CFA46A74CF3E96&id=43CFA46A74CF3E96%2140429


December 11, 2012  11:14 AM

Clearing AD values

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

A reader left a comment on this post http://msmvps.com/blogs/richardsiddaway/archive/2012/12/09/bulk-modifications-using-set-aduser.aspx

I was asked to show how to use the –Clear parameter.

Using the same CSV file this works:

$users = Import-Csv -Path C:\Scripts\adtest.csv                        
# Loop through CSV and update users if the exist in CVS file                        
                        
foreach ($user in $users) {                        
#Search in specified OU and Update existing attributes                        
 Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -Properties * -SearchBase "cn=Users,DC=manticore,DC=org" |                        
  Set-ADUser -Clear l, physicalDeliveryOfficeName, division                        
}

The difference with clear is that you have to use the proper LDAP attribute name – you can find this using ADSIEdit if you don’t know what it is. 


December 10, 2012  4:00 PM

Keep taking the tablets

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tablets seem to be all the rage at the moment. I’ve been working with three different types over the last month or so and thought I’d share my observations. These are base on my personal circumstances and needs – yours may be quite different.

The 3 tablets are in order that I started using them:

  • ipad 3
  • Kindle Fire HD
  • Microsoft Surface

The ipad is currently the iconoclastic tablet and has had masses written about. At the moment its the least useful of the tablets. I’ll explain why in a minute.

The Kindle Fire HD is relatively new and is a heavily customised versions of Android. Its a 7 inch device with a very nice email client that can access multiple accounts and a reasonably fast browser. Its size makes it small enough to use one handed as an e-reader. The other two being 1o inch tablets are really meant for two hands and are not as comfortable to use as e-readers. Being bigger they are more susceptible to glare on the screen. The smaller Kindle screen is easier to angle for glare avoidance.

You can synchronise files using the USB cable.

A simple Kindle is the best option if all you want is an e-reader – its small enough to slip in a pocket. Ideal for travelling. If you want a bit more the Fire is not much bigger and not that much more expensive.

The Surface is the youngest of the tablets. It runs the RT version of Windows 8 plus full versions of the Office products – Word, Excel & PowerPoint. Windows 8 enables the synchronisation of settings across multiple machines – I have a laptop, netbook and tablet running Windows 8 and a number of settings including IE favourites automatically sync. It also looks like wireless network settings sync!

The Surface cover folds down to give a keyboard. Its not something that I would want to use all day every day but with a touchpad mouse its more than adequate – I recently prepared a 2000 word article on it with no problems. The flip out stand on the back of the Surface props the screen at a good angle for use.

A full size USB port is a huge bonus for the Surface. It gives me options for mobile working – SkyDrive or USB. Covers all eventualities.

The Surface also includes PowerShell v3.  Just the console not ISE. Its a constrained version of PowerShell but it there.

By contrast the ipad has a usable app that functions as a mobile white board. That’s all I’ve really found useful.

Much is made of the numbers of apps available in the various app stores but if you actually look at them you have to wonder – how many versions of Sudoko do you really need?

Between the Kindle Fire and the Surface I have my leisure and business mobile needs met. The ipad doesn’t bring anything new to the table – that I need and so doesn’t get used.

As I said at the beginning these are my observations based on my needs and experiences. Yours may well be different.


December 10, 2012  2:25 PM

Get-CimClass changes

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

One thing that I don’t think I’ve mentioned is that the Get-CimClass output changed during the development process.

In PowerShell v3 RTM you can dig into a WMI class like this

Get-CimClass -ClassName Win32_OperatingSystem | select -ExpandProperty CimClassMethods
Get-CimClass -ClassName Win32_OperatingSystem | select -ExpandProperty CimClassProperties
Get-CimClass -ClassName Win32_OperatingSystem | select -ExpandProperty CimClassQualifiers
Get-CimClass -ClassName Win32_OperatingSystem | select -ExpandProperty CimSystemProperties

In at least some of the CTP versions of PowerShell v3 there were parallel, or alternate, properties you could use: Methods , Properties and Qualifiers respectively.

You may see reference to them in older posts – if you do just prefix with CimClass and you’ll be good.


December 9, 2012  1:10 PM

Reminder–PowerShell Jobs session

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Quick reminder that this coming Tuesday the UK PowerShell group presents a session on PowerShell Jobs

Details from

http://msmvps.com/blogs/richardsiddaway/archive/2012/12/02/powershell-jobs-and-scheduled-tasks-date-change.aspx


December 9, 2012  3:41 AM

Bulk modifications using Set-AdUser

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

 

The standard approach to the bulk modification of users is to create a CSV file with an identifier and the data you want to change. Here’s part of a CSV file that could be used to modify some AD attributes – Division, City and Office

SamAccountName,Division,Office,City
mgreen,Accounting,"Main Office","New York"
dgreen,Sales,"North East",Boston
jgreen,Marketing,"North West",Seattle
bkent,Manufacturing,"North",Chicago

I always like to first test what is set

$users = Import-Csv -Path C:\Scripts\adtest.csv            
            
foreach ($user in $users) {            
 Get-ADUser -Identity $user.SamAccountName -Properties * |            
 select SamAccountName, Division, Office, City             
}

A simple loop through each user and display the data. I’ve used –Properties * to ensure that I get the data I want. I could have put the attribute names in to restrict the returned data – might be a good idea if you are working with lots if user accounts at once

SamAccountName      Division            Office              City              
————–      ——–            ——              —-              
mgreen                                                                        
dgreen                                                                        
jgreen                                  Test                                  
bkent               AD Admin            ADML House          Peterborough

With Set-ADUser you get two options – a named parameter or the Add, Replace, Clear, Remove parameters.  See the help file for more details. All of our attributes have named parameters  so we can use this code

# Import AD Module             
Import-Module ActiveDirectory            
            
# Import CSV into variable $userscsv            
#$userscsv = import-csv D:\areile\Desktop\adtest.csv            
$users = Import-Csv -Path C:\Scripts\adtest.csv            
# Loop through CSV and update users if the exist in CVS file            
            
foreach ($user in $users) {            
#Search in specified OU and Update existing attributes            
 Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -Properties * -SearchBase "cn=Users,DC=manticore,DC=org" |            
  Set-ADUser -City $($user.City) -Office $($user.Office) -Division $($user.Division)            
}

Import the CSV file and loop through the users. For each user get the user object and pipe to Set-ADUser. The new attribute values are set from the CSV file data

Alternatively if you know the LDAP name of the attribute OR there isn’t a parameter for that attribute use the –Replace parameter.

# Import AD Module             
Import-Module ActiveDirectory            
            
# Import CSV into variable $userscsv            
#$userscsv = import-csv D:\areile\Desktop\adtest.csv            
$users = Import-Csv -Path C:\Scripts\adtest.csv            
# Loop through CSV and update users if the exist in CVS file            
            
foreach ($user in $users) {            
#Search in specified OU and Update existing attributes            
 Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -Properties * -SearchBase "cn=Users,DC=manticore,DC=org" |            
  Set-ADUser -Replace @{l = "$($user.City)"; physicalDeliveryOfficeName = "$($user.Office)"; division = "$($user.Division)"}            
}

The thing to note here is that the LDAP attribute names don’t always match the GUI names which are used as parameters. Get-ADUser seems to translate OK though!  You can find the correct name using ADSIEdit.

Note also that the help file for Set-AdUser is incorrect in at least once place – the list of attribute name-value pairs must be separated by semi-colons NOT commas as the help file states


December 7, 2012  11:28 AM

Amazon does PowerShell

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

A suite of PowerShell cmdlets for managing Amazon Web Services has been released

http://news.techworld.com/virtualisation/3415262/aws-adds-powershell-continues-windows-push/?cmpid=TD1N11&no1x1&olo=daily%20newsletter

The cmdlets can be downloaded from

http://aws.amazon.com/powershell/

Information on using the cmdlets can also be found on this site


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: