PowerShell for Windows Admins


June 8, 2012  7:53 AM

Cleaning up the temp folder



Posted by: Richard Siddaway
File System, PowerShell 3

 

This post

http://powershell.com/cs/blogs/tips/archive/2012/06/05/checking-size-of-downloads-folder.aspx

go me thinking about the temp folder. Its one of those areas tucked away in your profile that just seems to get left to grow.  Time to do something about it.

$testdate = (Get-Date).AddDays(-10)            
$names = "FXSAPIDebugLogFile.txt", "hsperfdata_Richard"            
            
## assume TMP = TEMP            
$path = $env:TEMP            
            
Get-ChildItem -Path $path -File  |            
where LastWriteTime -lt $testdate |            
where Name -NotIn $names |            
Remove-Item -Force #-WhatIf            
            
Get-ChildItem -Path $path -Directory |            
where LastWriteTime -lt $testdate |            
where Name -NotIn $names |            
Remove-Item -Force -Recurse #-WhatIf

I decide to use some of the new functionality in PowerShell v3 and separate the file and folder processing so I could play (er experiment) with some of the new parameters in  Get-ChildItem

Get-ChildItem [-Attributes <FileAttributes]>] [-Directory] [-File] [-Force] [-Hidden] [-ReadOnly] [-System]

[-UseTransaction] [<CommonParameters>]

These are a separate parameter set which means that -exclude and –include don’t work with them.

So start by creating a date to test against. Anything older than this will be deleted. Define a few names of things that have to be left alone (these will probably be different on your system) and set the path. I’ve assumed that the TEMP and TMP environmental variables point to the same path. if your system is different put the rest of the code into a foreach loop to iterate through the two variables.

Starting with files we get all the files in the root of TEMP. The –File parameter means we only look at files – folders are automatically excluded.

I’ve then used two where statements. Now the obvious comment is that I could combine them but if I do that I have to check each file for its age and then if its name is in my exclusion list. This way I test for age and immediately filter out any file that it is too young. Then I test for name. Doing it this way gives a small performance increase if you have a lot of young files.

I then pass the files to Remove-Item to delete.

The directories are processed in a similar manner except that we use –Directory on Get-ChildItem and add –Recurse to the Remove-Item call so that non-empty folders are removed.

Next move is to make this a scheduled task using the new PowerShell scheduled task cmdlets.

June 8, 2012  2:34 AM

PowerShell in Depth excerpts



Posted by: Richard Siddaway
Books, PowerShell 3

If you haven’t seen them already Microsoft’s ScriptingGuy has kindly published a couple of excerpts from PowerShell in Depth by Don Jones, Jeff Hicks and myself

http://blogs.technet.com/b/heyscriptingguy/archive/2012/06/04/powershell-in-depth-part-1.aspx

http://blogs.technet.com/b/heyscriptingguy/archive/2012/06/05/powershell-in-depth-part-2.aspx

Enjoy


June 2, 2012  8:19 AM

Toggling between LAN and Wireless



Posted by: Richard Siddaway
Network, PowerShell 3, Windows 8, Windows Server 8, WMI

One of the questions in the recent Scripting Games involved toggling between a wireless and LAN connection. Only one was to be up at any one time.

This can be solved using WMI but becomes hugely simpler in Windows 8/2012 as we get a bunch of cmdlets for working with network adapters.

Using WMI

Get-WmiObject -Class Win32_NetworkAdapter | Measure-Object

I get 15 objects returned on my system – but I’m only interested in 2 of them!

Using the new functionality

PS> Get-NetAdapter | ft -a Name, ifIndex, Status

Name             ifIndex Status
—-             ——- ——
Virtual Wireless      21 Disabled
Virtual LAN           12 Up

This leads to a simple piece of code

Get-NetAdapter |
foreach {
  $nic = $_
  switch ($_.Status){
   "Up"        {Disable-NetAdapter -InputObject $nic -Confirm:$false}
   "Disabled"  {Enable-NetAdapter -InputObject $nic -Confirm:$false}

  }
}

Get the adapter, test its status and toggle to the other.

These cmdlets are in the NetAdapter module which is created using the cmdlets over objects techniques to utilise WMI classes in a much friendlier way. Remoting capabilities are supplied by CIMsessions


June 2, 2012  7:58 AM

Using a colon with cmdlet parameters



Posted by: Richard Siddaway
PowerShell, PowerShell 3, PowerShell v2

Another question at Tuesdays PowerShell group revolved around using colons to link values to parameters. I’d not really thought about before. Thinking about it  later I realised that you only really see it when passing booleans to –Confirm.  If you don’t use a colon then you get this

PS> Disable-NetAdapter -Name "Virtual Wireless" -Confirm $false
Disable-NetAdapter : A positional parameter cannot be found that accepts argument ‘False’.
At line:1 char:1
+ Disable-NetAdapter -Name "Virtual Wireless" -Confirm $false
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Disable-NetAdapter], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Disable-NetAdapter

But this will work

PS> Disable-NetAdapter -Name "Virtual Wireless" -Confirm:$false

Just for completeness this works as well

PS> Get-NetAdapter –Name:"Virtual Wireless" 

though it doesn’t tend to get used


June 2, 2012  6:34 AM

Using Windows 2012 Active Directory module in a Windows 2008 R2 domain



Posted by: Richard Siddaway
Active Directory, PowerShell 3, Windows 2008 R2, Windows Server 8

A question came up on Tuesdays UK PowerShell Group session about using the Windows 2012 Active Directory module. The recording links are here

http://msmvps.com/blogs/richardsiddaway/archive/2012/05/30/may-2012-powershell-group-recording-and-slides.aspx

The question asked if the new Site, Subnet and Site link cmdlets would work in a legacy environment.

This morning I installed a Windows Server 2012 Release Candidate member server into my Windows 2008 R2 domain. I then installed the RSAT feature on the Windows 2012 server – this includes the Active Directory module.

The site, subnet and site link cmdlets appear to work with NO changes required to the Windows 2008 R2 domain controller. I was able to view and create sites, subnets and site links.

I haven’t tested any other scenario.


June 2, 2012  3:07 AM

PowerShell v3 release candidate



Posted by: Richard Siddaway
PowerShell 3

Hot on the heels of the Windows 8/2012 release candidates comes the PowerShell v3 (well Ok the Windows Management Framework) release candidate.

This is available for

  • Windows 7 SP 1
  • Windows Server 2008 R2 SP 1
  • Windows 2008 SP2

32 and 64 bit versions are available as applicable to the OS

Notice the omissions Vista, Windows 2003 and XP. If that continues into RTM there will be some issues around using the some of the functionality across the estate as it relies on WSMAN 3.0

Details and links from here

http://blogs.msdn.com/b/powershell/archive/2012/06/02/windows-management-framework-3-0-rc-is-available-for-download.aspx


June 1, 2012  1:07 PM

Working with profiles: part 1



Posted by: Richard Siddaway
PowerShell 3, PowerShell v2, WMI

A question came up on the forum for PowerShell and WMI – how do I delete profiles. I’m going to work up to answering that by looking at using WMI to work with profiles.

So to start how can we find the profiles available on our system

Get-WmiObject -Class Win32_UserProfile |
select LocalPath, SID, @{N="LastUseTime"; E={$_.ConvertToDateTime($_.LastUseTime)}}

LocalPath                   SID                         LastUseTime              
———                   —                         ———–              
C:\Users\Richard            S-1-5-21-2542198769-1191… 01/06/2012 19:56:28      
C:\Windows\ServiceProfil… S-1-5-20                                             
C:\Windows\ServiceProfil… S-1-5-19                                             
C:\Windows\system32\conf… S-1-5-18        

or if you prefer the CIM cmdlets in PowerShell v3

Get-CimInstance -ClassName Win32_UserProfile |
select LocalPath, SID, LastUseTime

C:\Users\Richard            S-1-5-21-2542198769-1191… 01/06/2012 19:56:28      
C:\Windows\ServiceProfil… S-1-5-20                                             
C:\Windows\ServiceProfil… S-1-5-19                                             
C:\Windows\system32\conf… S-1-5-18
   

Notice that with the CIM cmdlet we don’t have to perform any date conversions – worth switching just for that alone.

But the data above doesn’t show the user account.

Unfortunately there isn’t an association between profile and user account so we need to do the filtering ourselves

Get-WmiObject -Class Win32_UserProfile |
select LocalPath, SID,
@{N="LastUseTime"; E={$_.ConvertToDateTime($_.LastUseTime)}},
@{N="User"; E={Get-WmiObject -Class Win32_UserAccount -Filter "SID = ‘$($_.SID)’" | select -ExpandProperty Caption}}

LocalPath            SID                  LastUseTime          User              
———            —                  ———–          —-              
C:\Users\Richard     S-1-5-21-25421987… 01/06/2012 20:01:56  RSLAPTOP01\Richard
C:\Windows\Servic… S-1-5-20                                                    
C:\Windows\Servic… S-1-5-19                                                    
C:\Windows\system… S-1-5-18   

The alternative with the CIM cmdlets

Get-CimInstance -ClassName Win32_UserProfile |
select LocalPath, SID, LastUseTime,
@{N="User"; E={Get-CimInstance -Class Win32_UserAccount -Filter "SID = ‘$($_.SID)’" |
select -ExpandProperty Caption}}

C:\Users\Richard     S-1-5-21-25421987… 01/06/2012 20:01:56  RSLAPTOP01\Richard
C:\Windows\Servic… S-1-5-20                                                    
C:\Windows\Servic… S-1-5-19                                                    
C:\Windows\system… S-1-5-18  

The final part is to filter out any of the well known special accounts such as Local service

Get-WmiObject -Class Win32_UserProfile -Filter "Special = ‘$false’" |
select LocalPath, SID,
@{N="LastUseTime"; E={$_.ConvertToDateTime($_.LastUseTime)}},
@{N="User"; E={Get-WmiObject -Class Win32_UserAccount -Filter "SID = ‘$($_.SID)’" | select -ExpandProperty Caption}}

or

Get-CimInstance -ClassName Win32_UserProfile -Filter "Special = ‘$false’" |
select LocalPath, SID, LastUseTime,
@{N="User"; E={Get-CimInstance -Class Win32_UserAccount -Filter "SID = ‘$($_.SID)’" | select -ExpandProperty Caption}}

either of these will just return the top line in the output above.

Now we can identify our profiles & relate them to user accounts – how do we delete them


May 30, 2012  1:03 PM

May 2012 Powershell group recording and slides



Posted by: Richard Siddaway
PowerShell 3, User Group, Windows Server 8

 

The recording, slides and demo scripts from last nights session  – Powershell in Windows Server 8 part 2  – is available from

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

The full set of historical recordings can be found here:

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

2011 09 PowerShell remoting and end point customisation
2011 11 Whats new in PowerCLI 5
2011 12 Intro to WMI
2011 12 WSMAN_WMI_and_CIM
2012 January PowerShell v3 CTP 2 overview
2012 February PowerShell and SQL Server
2012 March CIM cmdlets
2012 April Powershell in Windows Server 8
2012 May Powershell in Windows Server 8 part 2 

Older folders just have the slides


May 27, 2012  10:56 AM

May UG meeting reminder



Posted by: Richard Siddaway
PowerShell 3, User Group, Windows Server 8

Quick reminder that the UK PowerShell group session on PowerShell in Windows 2012 is on Tuesday 29 May. Details from

http://msmvps.com/blogs/richardsiddaway/archive/2012/05/08/uk-powershell-group-may-2012.aspx


May 25, 2012  11:58 AM

Working with WMI methods



Posted by: Richard Siddaway
PowerShell 3, PowerShell v2, WMI

Many WMI classes have methods. Methods allow us to perform some action on the object. A recent question on the forum about using methods made me realise that there are still a lot of people following the old VBScript way of doing things.

We will experiment with the BITS service as it is safe for these purposes.

PS> Get-WmiObject -Class Win32_Service -Filter "Name = ‘BITS’"

ExitCode  : 0
Name      : BITS
ProcessId : 928
StartMode : Auto
State     : Running
Status    : OK

Lets have a look at the service and its methods

$service = Get-WmiObject -Class Win32_Service -Filter "Name = ‘BITS’"

$service | Get-Member -MemberType method

TypeName: System.Management.ManagementObject#root\cimv2\Win32_Service

Name
—-
Change
ChangeStartMode
Delete
GetSecurityDescriptor
InterrogateService
PauseService
ResumeService
SetSecurityDescriptor
StartService
StopService
UserControlService

So we see methods to stop and start the service

$service.StopService()

PS> Get-Service BITS

Status   Name               DisplayName
——   —-               ———–
Stopped  BITS               Background Intelligent Transfer Ser…

$service.StartService()

PS> Get-Service BITS

Status   Name               DisplayName
——   —-               ———–
Running  BITS               Background Intelligent Transfer Ser…

The person asking the question was trying to use the InvokeMethod method

$service.InvokeMethod(‘StopService’,$Null)

and wondering why it was failing. If you look back to the list of methods above you won’t see InvokeMethod. That’s because it is on the base object. PowerShell, in many instances, doesn’t return the pure .NET object. There are methods and properties added or removed to create the object we normally see.

We can get back to the base object

$service.psbase | gm

And in that list you will see a method called InvokeMethod

PS> $service.psbase.InvokeMethod

OverloadDefinitions
——————-
System.Object InvokeMethod(string methodName, System.Object[] args)
void InvokeMethod(System.Management.ManagementOperationObserver watcher, string methodName, System.Object[] args)
System.Management.ManagementBaseObject InvokeMethod(string methodName, System.Management.ManagementBaseObject
inParameters, System.Management.InvokeMethodOptions options)
void InvokeMethod(System.Management.ManagementOperationObserver watcher, string methodName,
System.Management.ManagementBaseObject inParameters, System.Management.InvokeMethodOptions options)

Shows us how to use it.

Going for the simplest option

PS> $service.psbase.InvokeMethod("StopService", $null)
0
PS> Get-Service BITS

Status   Name               DisplayName
——   —-               ———–
Stopped  BITS               Background Intelligent Transfer Ser…

PS> $service.psbase.InvokeMethod("StartService", $null)
0
PS> Get-Service BITS

Status   Name               DisplayName
——   —-               ———–
Running  BITS               Background Intelligent Transfer Ser…

PS> Get-WmiObject -Class Win32_Service -Filter "Name = ‘BITS’" | Invoke-WmiMethod -Name StopService

PS> Get-Service BITS

Status   Name               DisplayName
——   —-               ———–
Stopped  BITS               Background Intelligent Transfer Ser…

PS> Get-WmiObject -Class Win32_Service -Filter "Name = ‘BITS’" | Invoke-WmiMethod -Name StartService

PS> Get-Service BITS

Status   Name               DisplayName
——   —-               ———–
Running  BITS               Background Intelligent Transfer Ser…

These options will work as well

$service | Invoke-WmiMethod -Name StopService
$service | Invoke-WmiMethod -Name StartService

Invoke-WmiMethod -InputObject $service -Name StopService
Invoke-WmiMethod -InputObject $service -Name StartService

My preference is to use the get-wmiobject | invoke-wmimethod pairing as when I am developing I can easily test any filters before I start affecting the service.

Of all of the options using the  InvokeMethod method is the one to avoid as it is more cumbersome and involves more typing

In PowerShell v3 we can use the CIM cmdlets but that is a post for another day

More information on using WMI with PowerShell in PowerShell and WMI – www.manning.com/powershellandwmi


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: