PowerShell for Windows Admins


March 3, 2012  8:26 AM

Windows 8 svchost

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

When you run get-process you will see a number of entries named svchost.  These are processes that host services. In task manager on Windows 7 and below all we see is the svchost entry. In the Windows 8 family we see the services running in a particular host

Now can we do anything similar with PowerShell.

Get-Service doesn’t do anything to help BUT the Win32_Service class has a ProcessID property that we can use

Get-CimInstance -ClassName Win32_Service |             
sort ProcessID -Descending |            
foreach {            
  $proc = Get-Process -Id $_.ProcessID            
  $_ | Add-Member -MemberType NoteProperty -Name ProcessName -Value $($proc.ProcessName) -PassThru            
} |            
Format-Table DisplayName, ProcessName -GroupBy ProcessId

I’ve used Get-CimInstance in this example because of the CIM cmdlets are new to PowerShell v3. For a PowerShell v2 install use Get-WmiObject

Get-WmiObject -Class Win32_Service |             
sort ProcessID -Descending |            
foreach {            
  $proc = Get-Process -Id $_.ProcessID            
  $_ | Add-Member -MemberType NoteProperty -Name ProcessName -Value $($proc.ProcessName) -PassThru            
} |            
Format-Table DisplayName, ProcessName -GroupBy ProcessId

The WMI objects are piped through sort & into foreach where we add the process name. In both cases I’ve used Get-Process – either Get-CIMInstance or Get-WmiObject using the Win32_Process class could be used instead.

Format-table is used with GroupBy to produce a nicely formatted report. This information is important because it shows the services that are related to a particular process and the impact if that process fails..

March 3, 2012  6:04 AM

PowerShell v3 Updateable Help

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

One of the things that we have become used to in PowerShell v1 and v2 is the help files. They are installed with PowerShell, available on line and a graphical version is available for download. The online help files are updated over time but the local files aren’t.  This changes with PowerShell v3.

When you install PowerShell v3 (or install Windows 8/Windows Server 8 ) help files are not installed. Thats right you don’t get help files available. If you try using help you get this

 

PS> get-help get-process

NAME
    Get-Process

SYNTAX
    Get-Process [[-Name] <string[]>] [-ComputerName <string[]>] [-Module] [-FileVersionInfo]  [<CommonParameters>]

    Get-Process -Id <int[]> [-ComputerName <string[]>] [-Module] [-FileVersionInfo]  [<CommonParameters>]

    Get-Process -InputObject <Process[]> [-ComputerName <string[]>] [-Module] [-FileVersionInfo]  [<CommonParameters>]

ALIASES
    gps
    ps

REMARKS
    Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
        — To download and install Help files for the module that includes this cmdlet, use Update-Help.
        — To view the Help topic for this cmdlet online, type: "Get-Help Get-Process -Online" or
           go to
http://go.microsoft.com/fwlink/?LinkID=113324.

 

Using –full doesn’t bring more information and –examples doesn’t help either.

This may seem like a huge step backwards – how are we going to work without the local help files. I use them on a regular basis. Help. I want my help files back.

OK – what we get in PowerShell v3 is updateable help.  This means that you can pull the help files from the web and get them installed. Notice the Remarks section above about using Update-Help. The PowerShell core module has 3 cmdlets related to help

Get-Help
Save-Help  – downloads help files for later use via update-help
Update-Help – downloads and immediately updates help files

To use Save-help or Update-help you need to start PowerShell with elevated privileges (Run as administrator)

NAME
    Save-Help

SYNTAX
    Save-Help [-DestinationPath] <string[]> [[-Module] <string[]>] [[-UICulture] <string[]>] [-UseDefaultCredentials]
    [-Force]  [<CommonParameters>]

    Save-Help [[-Module] <string[]>] [[-UICulture] <string[]>] -LiteralPath <string[]> [-UseDefaultCredentials]
    [-Force]  [<CommonParameters>]

PS> get-help Update-Help

NAME
    Update-Help

SYNTAX
    Update-Help [[-Module] <string[]>] [[-SourcePath] <string[]>] [[-UICulture] <string[]>] [-Recurse]
    [-UseDefaultCredentials] [-Force]  [<CommonParameters>]

    Update-Help [[-Module] <string[]>] [[-UICulture] <string[]>] [-LiteralPath <string[]>] [-Recurse]
    [-UseDefaultCredentials] [-Force]  [<CommonParameters>]

 

Notice that we can update the help for individual modules

Lets pull down the help files first

Save-Help -DestinationPath c:\source\helpfiles -UICulture en-US -Force –Verbose

You will see a progress bar and messages like

VERBOSE: Your connection has been redirected to the following URI:
"http://download.microsoft.com/download/3/4/C/34C6B4B6-63FC-46BE-9073-FC75EAD5A136/"
VERBOSE: Microsoft.PowerShell.Management: Saved
C:\source\helpfiles\Microsoft.PowerShell.Management_eefcb906-b326-4e99-9f54-8b4bb6ef3c6d_en-US_HelpContent.cab. Culture
en-US Version 3.0.0.0

for each help file that is downloaded.

the –Force parameter is interesting as it allows you to run a Save-Help or Update-Help command for the same module more than once each day.

I have found it is sometimes necessary to run save-help or update-help a couple of times to get all of the files downloaded

The help files can then be updated like this

Update-Help -SourcePath c:\source\helpfiles -UICulture en-US -Force –Verbose

 

You will get messages like this

VERBOSE: Microsoft.PowerShell.Management: Updated
C:\Windows\System32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Management.dll-help.xml. Culture en-US
Version 3.0.0.0

 

VERBOSE: Microsoft.PowerShell.Core: Updated
C:\Windows\System32\WindowsPowerShell\v1.0\en-US\about_WMI_Cmdlets.help.txt. Culture en-US Version 3.0.0.0

 

Now

get-help Get-Process –full

will give you the help files you know and love

That is a two stage process but ahs the advantage that the help files can be pulled once and put on a network share for access by all systems. This is especially important for my servers where I don’t normally allow access to the Internet

The above tests were performed on PowerShell v3 on Windows 7 SP 1

The alternative is to update the help files directly

Update-Help  -UICulture en-US -Force –Verbose

 

Notice that in all cases I’ve given the UICulture – the help files come as a pair e.g.

Microsoft.PowerShell.Host_56d66100-99a0-4ffc-a12d-eee9a6718aef_en-US_HelpContent.cab
Microsoft.PowerShell.Host_56d66100-99a0-4ffc-a12d-eee9a6718aef_HelpInfo.xml

You need to get the culture right to pull down the correct help files. I use English culture but I’m not sure what other localised versions are available  at this stage in the development cycle.

If you are running a 64 bit OS it looks like the help for 64 and 32 bit versions of PowerShell are updated simultaneously.

The help files may not be complete at this stage of Powershell v3 development so don’t be surprised if you don’t get help updates  for all modules – especially on Windows 8 server


March 2, 2012  4:29 PM

Windows 8 Modules

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

We saw the modules that come with Windows server 8

 

This is the list of modules available in a vanilla Windows 8 32 bit install

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

Again the core PowerShell modules are italicised – though that concept is becoming redundant as PowerShell v3 auto loads all modules it finds on the module path


March 2, 2012  1:09 PM

PowerShell v3 in Depth

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Hot on the heels on the announcements of that PowerShell v3 beta is available for download either as a free standalone product for installation on Windows 7, Windows 2008 & Windows 2008 R2 or as a commercial product where an operating system is included – Windows 8 or Windows server 8 to suit your mood

http://msmvps.com/blogs/richardsiddaway/archive/2012/03/01/windows-8-and-powershell-3-betas.aspx

comes the announcement from Manning of a new PowerShell book

PowerShell v3 in Depth

Written by Don Jones, Jeffrey Hicks and myself it covers PowerShell v3 in great detail – how to get the absolute maximum out of PowerShell. The 40 chapters will cover all aspects of PowerShell v2 and v3. This book is about PowerShell it self – we won’t cover working with AD, Exchange etc.

This is a book with a single voice as all 3 authors work on each chapter – with individual anecdotes, comments and asides as a bonus-   you get our collected and individual experience and knowledge.  If you only buy one PowerShell book it should be this one

Access to the early drafts is available from

http://www.manning.com/jones2/


March 1, 2012  4:00 PM

Server 8 Beta PowerShell

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I downloaded the Windows Server 8 beta overnight and spun up a virtual machine. We get PowerShell v3 beta plus and whole host of modules

ADDeploymentWF
AppLocker
Appx
BestPractices
BitsTransfer
BranchCache
CimCmdlets
DirectAccessClientComponents
Dism
DnsClient
International
iSCSI
IscsiTarget
Kds
Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host
Microsoft.PowerShell.Management
Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility
Microsoft.WSMan.Management
MMAgent
MsDtc
NetAdapter
NetLbfo
NetQos
NetSecurity
NetSwitchTeam
NetTCPIP
NetWNV
NetworkConnectivityStatus
NetworkTransition
NFS
PKI
PrintManagement
PSDiagnostics
PSScheduledJob
PSWorkflow
RDManagement
ScheduledTasks
SecureBoot
ServerManager
ServerManagerShell
SmbShare
SmbWitness
Storage
TelemetryManagement
TroubleshootingPack
TrustedPlatformModule
UpdateServicesDeployment
UserAccessLogging
Wdac
Whea
WindowsDeveloperLicense

This is a totally vanilla install with no features or roles installed. The RSAT tools aren’t installed either. 

The modules in italics are part of the base PowerShell install.   By comparison this is what is available from PowerShell v3 installed on Windows 7

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

Thats a lot of PowerShell to look at.  I’ll look and see what Windows 8 has by default


February 28, 2012  5:22 PM

UK PowerShell group–February 2012 recording

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

The recording, slides and demo scripts from tonight’s PowerShell and SQL Server session are available as a single zip file for download from

https://skydrive.live.com/#cid=43CFA46A74CF3E96&id=43CFA46A74CF3E96%212943

The file is created with jzip but any zip handling program should be able to unzip it

Thank you to the attendees and especially for the questions – I’ve posted the answer to the question regarding accessing named instances using a port number here

http://msmvps.com/blogs/richardsiddaway/archive/2012/02/28/connecting-via-smo-to-a-named-instance.aspx

Next meeting will be 28 March 2012

Topic will probably be CIM in PowerShell v3


February 27, 2012  10:56 AM

February UG meeting–Final reminder

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

 

The UK PowerShell group presents a Live Meeting tomorrow on using PowerShell with SQL Server

Details from

http://msmvps.com/blogs/richardsiddaway/archive/2012/02/09/february-powershell-group-meeting-sql-server-and-powershell.aspx


February 25, 2012  10:11 AM

Using [wmiclass] accelerator and string substitution

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tripped over an interesting problem

I want to use the [wmiclass] accelerator because I need to find the key of a WMI class (code borrowed from PowerShell team blog – to be returned when I’ve finished with it)

 

$t = [WMIClass]$class

$t.properties |

select @{Name="PName";Expression={$_.name}} -ExpandProperty Qualifiers |

where {$_.Name -eq "key"} |

foreach {"The key for the $class class is $($_.Pname)"}

 

Now I wanted to add the namespace so I tried this

PS> $namespace="root\cimv2"
PS> $class="Win32_Process"
PS> [wmiclass]"\\.\$namespace:$class"
Cannot convert value "\\.\Win32_Process" to type "System.Management.ManagementClass". Error: "Invalid namespace "
At line:1 char:11
+ [wmiclass] <<<< "\\.\$namespace:$class"
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

 

Huh – of course root\cimv2 is valid

But its not a WMI problem its a string substitution problem

because

PS> $target = "$namespace:$class"
PS> $target
Win32_Process

Oh – no namespace

Its because of the colon

The way we get round it is to escape the : using a backtick `

[wmiclass]\\.\$namespace`:$class

Which works

Just a little WMI quirk to be aware of


February 22, 2012  3:32 PM

Download multiple files by BITS

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Last time we looked at BITS we saw how to transfer a single file. The example in the help file doesn’t work in my environment so this is what I came up with as a work around

Import-Module BitsTransfer -Force            
            
$computername = "WebR201"            
$destination = "c:\source\transfer\"            
            
Get-WSManInstance -ResourceURI wmicimv2/* -Enumerate -Dialect WQL `
 -Filter "SELECT * FROM CIM_DATAFILE WHERE Drive='C:' AND Path='\\Transfer\\' " `
  -ComputerName $computername  |            
foreach {            
             
$name = Split-Path -Path $($_.Name) -Leaf            
$source =  "http://webr201/transfer/$name"            
Write-Host "Transferring $source to $destination"            
            
Start-BitsTransfer -Source $source -Destination $destination             
            
Test-Path -Path ($destination + $name) -Verbose            
}

Import the module

The use WMI over WSMAN cmdlets to find the files in the folder – this assumes that I know the physical path to the virtual directory – within my enterprise there’s no reason why I shouldn’t.

For each of the files I create the URL to the file – use Write-Host to put out a message and then use Test-Path on the destination folder to determine that it has arrived


February 22, 2012  1:13 PM

object vs value

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

An interesting question came up recently. A Powershell user was trying to access an AD attribute so they did something like this

$x = Get-ADUser -Identity usera -Properties * | select useraccountcontrol

 

When they tried to use $x it didn’t correctly in the rest of the script.

 

Select-object is used to filter down the attributes that are left on the object as it passes on the pipeline

So

PS> Get-ADUser -Identity usera -Properties * | select useraccountcontrol

useraccountcontrol
        ——————
                        512

 

If you just want the value rather than an object (I know that its still an object but in reality we work directly with the value) then use –expandproperty. On a property with a single value it returns that value

PS> Get-ADUser -Identity usera -Properties * | select -expandproperty useraccountcontrol
512


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: