PowerShell for Windows Admins


September 12, 2010  5:52 AM

Deleting files older than a certain date



Posted by: Richard Siddaway
File System, PowerShell v2

A question on the ITKE forums asked how files older than a certain date (in this case two months) could be deleted without touching younger files.

001
002
003
$date = (Get-Date).AddMonths(-2)
Get-ChildItem -Path c:\scripts | where {!$_.PSIsContainer} |
foreach {if ($_.LastWriteTime -lt $date){Remove-Item $_ -whatif}}

Simply remove the –whatif parameter for the delete to actually happen

September 6, 2010  12:47 PM

WMI and Network Adapters: 4



Posted by: Richard Siddaway
Network, PowerShell v2

We have looked at using Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration. 

Get-WmiObject -Class Win32_NetworkAdapter -Filter "NetEnabled=’$true’" |
Format-List NetConnectionID, Description, MACAddress, Speed

Get-WmiObject -Class Win32_NetworkAdapterConfiguration |
where {$_.IPAddress} | Foreach { $_.Description; $_ |
select -ExpandProperty IPAddress}

Now we need to look at combining the information from the two classes. One way to do it is like this

001
002
003
004
005
006
007
008
009
010
011
012
Get-WmiObject -Class Win32_NetworkAdapter -Filter "NetEnabled=’$true’" | 
foreach {
 $_ | Format-List NetConnectionID, Description, MACAddress, Speed 

 $filt = "Index=’" + $_.DeviceID + "’"
 $nic = `
 Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter $filt 
 
 $nic | Format-List DefaultIPGateway, IPSubnet, DNSServerSearchOrder
 "IP Address"
 $nic | select -ExpandProperty IPAddress
}

This doesn’t give the most elegant of results so we will need to refine what we are doing


September 2, 2010  12:26 PM

September PowerShell User Group



Posted by: Richard Siddaway
PowerShell v2, User Group

 

When: Tuesday, Sep 14, 2010 8:30 PM (BST)
Where: Virtual

*~*~*~*~*~*~*~*~*~*

Jonathan Medd – PowerShell MVP – explains the new remoting features in PowerShell 2.0

Richard Siddaway has invited you to attend an online meeting using Live Meeting.

Join the meeting.

Audio Information

Computer Audio

To use computer audio, you need speakers and microphone, or a headset.

First Time Users:

To save time before the meeting, check your system to make sure it is ready to use Microsoft Office Live Meeting.

Troubleshooting

Unable to join the meeting? Follow these steps:

  1. Copy this address and paste it into your web browser:

    https://www.livemeeting.com/cc/usergroups/join
  2. Copy and paste the required information:

    Meeting ID: 56QBWG

    Entry Code: WF,6(G8xj

    Location: https://www.livemeeting.com/cc/usergroups

If you still cannot enter the meeting, contact support

Notice

Microsoft Office Live Meeting can be used to record meetings. By participating in this meeting, you agree that your communications may be monitored or recorded at any time during the meeting.


August 31, 2010  2:03 PM

WMI and Network Adapters: 3



Posted by: Richard Siddaway
Network, PowerShell v2

 

We have seen how to query WMI for information on network adapters.  But what we didn’t get was information about the addresses allocated to the NICs.  We need a different class for that

Get-WmiObject -Class Win32_NetworkAdapterConfiguration

However this gives us too much information as it includes all cards – we only want to see those with addresses

Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.IPAddress}

Gives us the two NICs (on my machine that are live). 

To just get the addresses

Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.IPAddress} | Foreach { $_.Description; $_ | select -ExpandProperty IPAddress}

Gives a quick view of the addresses associated with each card


August 30, 2010  3:39 AM

PowerShell in Practice offer



Posted by: Richard Siddaway
Books, PowerShell v2

Today Manning are offering 50% their best selling books including PowerShell in Practice.

 

See www.manning.com to order


August 28, 2010  5:07 AM

WQL wildcards



Posted by: Richard Siddaway
PowerShell v2, WMI

 

Get-WmiObject -Class Win32_NetworkAdapter 

will show us a list of network adapters.  We can narrow this down to a specific adapter

Get-WmiObject -Class Win32_NetworkAdapter -Filter "DeviceId=’11′" | fl *

What if we know that there is a NIC that is labelled as Wireless something or other.  We have two options

Get-WmiObject -Class Win32_NetworkAdapter | where {$_.NetConnectionID -like "wireless*"}

use the where-object cmdlet and filter using a like statement or

Get-WmiObject -Class Win32_NetworkAdapter -Filter "NetConnectionID LIKE ‘wireless%’"

filter in the get-wmiobject. Note that the wildcard symbol is % NOT * in the filter parameter. This is because we are using WQL which is a subset of SQL.

We could also write this as

Get-WmiObject -Query "SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID LIKE ‘wireless%’"

The WQL equivalent of the single character wildcard “?” is _ so we could write

Get-WmiObject -Query "SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID LIKE ‘_ireless%’"

More information on WQL wildcards can be found

http://msdn.microsoft.com/en-us/library/aa392263(v=VS.85).aspx


August 26, 2010  3:14 PM

WMI and Network Adapters: 2



Posted by: Richard Siddaway
Network, PowerShell v2

Ok – just to help out we can do this to see the useful information we need to complete our IPconfig listing

Get-WmiObject -Class Win32_NetworkAdapter -Filter "NetEnabled=’$true’" | Format-List NetConnectionID, Description, MACAddress, Speed

This gets a display like this

NetConnectionID : Local Area Connection
Description     : NVIDIA nForce Networking Controller
MACAddress      : 00:1F:16:63:F5:DF
Speed           : 10000000

NetConnectionID : Wireless Network Connection
Description     : Atheros AR5007 802.11b/g WiFi Adapter
MACAddress      : 00:24:2B:2F:9C:A5
Speed           : 54000000

Notice that the speed is in bits/second

Looks like 54Mb isn’t 56623104 after all.


August 26, 2010  1:09 PM

WMI and Network Adapters: 1



Posted by: Richard Siddaway
Network, PowerShell v2

Network adapters are a fundamental part of our system – without them our networks grind to a halt because the machines can’t communicate. We have a good tool in ipconfig for looking at NIC information but we can extend this using PowerShell and WMI.

Let’s start by seeing what is available.

Get-WmiObject -List *network*

returns a bunch of classes

Win32_NetworkLoginProfile
Win32_NetworkAdapterConfiguration
Win32_NetworkAdapterSetting
CIM_NetworkAdapter
Win32_NetworkAdapter
Win32_NetworkConnection
Win32_NetworkProtocol
Win32_NetworkClient
Win32_SystemNetworkConnections

plus some classes that give us performance counters – we’ll leave them for later.

Looking at the list of classes we’ll start with Win32_NetworkAdapter

On my Windows 7 machine I get a total of 14 adapters returned – that’s not bad for a machine with one Ethernet port and one wireless NIC!!  Each adapter returns some of the following information

ServiceName
MACAddress
AdapterType
DeviceID
Name
NetworkAddresses
Speed

This is the default data.  We can see what else might be available

Get-WmiObject -Class Win32_NetworkAdapter | Get-Member

gives us the following properties

AdapterType
AdapterTypeId
AutoSense
Availability
Caption
ConfigManagerErrorCode
ConfigManagerUserConfig
CreationClassName
Description
DeviceID
ErrorCleared
ErrorDescription
GUID
Index
InstallDate
Installed
InterfaceIndex
LastErrorCode
MACAddress
Manufacturer
MaxNumberControlled
MaxSpeed
Name
NetConnectionID
NetConnectionStatus
NetEnabled
NetworkAddresses
PermanentAddress
PhysicalAdapter
PNPDeviceID
PowerManagementCapabilities
PowerManagementSupported
ProductName
ServiceName
Speed
Status
StatusInfo
SystemCreationClassName
SystemName
TimeOfLastReset

if we look at the NICs that have the NetEnabled property set to true we get

PS> Get-WmiObject -Class Win32_NetworkAdapter -Filter “NetEnabled=’$true’”

ServiceName      : NVENETFD
MACAddress       : 00:1F:16:63:F5:DF
AdapterType      : Ethernet 802.3
DeviceID         : 7
Name             : NVIDIA nForce 10/100/1000 Mbps Networking Controller
NetworkAddresses :
Speed            : 10000000

ServiceName      : athr
MACAddress       : 00:24:2B:2F:9C:A5
AdapterType      : Ethernet 802.3
DeviceID         : 11
Name             : Atheros AR5007 802.11b/g WiFi Adapter
NetworkAddresses :
Speed            : 54000000

Comparing this to ipconfig

PS> ipconfig

Windows IP Configuration

Wireless LAN adapter Wireless Network Connection:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::6d95:b824:6a72:a0a9%12
   IPv4 Address. . . . . . . . . . . : 192.168.196.139
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.196.1

Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::4547:ee51:7aac:521e%11
   IPv4 Address. . . . . . . . . . . : 10.10.54.202
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

Tunnel adapter Teredo Tunneling Pseudo-Interface:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter isatap.{01F4E3B7-5F1F-40BD-8252-DCC3331891C1}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter isatap.{4DFBBD42-D7E9-49B8-9AD0-F5A644A94173}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

I’m going to leave the tunnel adapters for now and just concentrate on the enabled NICs. To get the full set of information for these NICs we use

Get-WmiObject -Class Win32_NetworkAdapter -Filter “NetEnabled=’$true’” | fl *

I’ll leave you to look at what we get from this command. Next time we’ll look at what we need from this to populate of ipconfig type report.


August 23, 2010  12:39 PM

WMI date issue



Posted by: Richard Siddaway
Operating System, PowerShell v2

 

Working with WMI dates can be awkward sometimes. For instance if we look at the last boot up time of our system

$machine = Get-WmiObject -Class Win32_OperatingSystem

PS> $machine.LastBootUpTime
20100823183135.359600+060

We get a non-intuitive result

The ConvertToDateTime method can rescue us from this problem

PS> $machine.ConvertToDateTime($machine.LastBootUpTime)

23 August 2010 18:31:35

 

And we can even use it with write-host

PS> Write-Host $machine.ConvertToDateTime($machine.LastBootUpTime)
23/08/2010 18:31:35

 

However if we want to make the boot time part of a larger string we get a problem

PS> Write-Host "$machine.ConvertToDateTime($machine.LastBootUpTime)"
\\RSLAPTOP01\root\cimv2:Win32_OperatingSystem=@.ConvertToDateTime(\\RSLAPTOP01\root\cimv2:Win32_OperatingSystem=@.LastBootUpTime)

 

so we can use a sub-expression

PS> Write-Host "Boot up Time $($machine.ConvertToDateTime($machine.LastBootUpTime))"
Boot up Time 08/23/2010 18:31:35

 

but we end up with date that has changed format and is confusing if you are used to DD/MM/YYYY as we use in the UK. We can then use the DateTime property to get back to the format we need

PS> Write-Host ($machine.ConvertToDateTime($machine.LastBootUpTime)).DateTime
23 August 2010 18:31:35

PS> Write-Host "Boot up Time $($machine.ConvertToDateTime($machine.LastBootUpTime).DateTime)"
Boot up Time 23 August 2010 18:31:35

Done.


August 11, 2010  1:05 PM

Memory configuration



Posted by: Richard Siddaway
Hardware

 

We have seen how to discover the total physical memory in a system but how is that memory arranged.

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
034
035
036
037
038
039
040
041
$form = DATA {
ConvertFrom-StringData -StringData @’
7 = SIMM
8 = DIMM
‘@

}

$type = DATA {
ConvertFrom-StringData -StringData @’
0 = Unknown
1 = Other
2 = DRAM
3 = Synchronous DRAM
4 = Cache DRAM
5 = EDO
6 = EDRAM
7 = VRAM
8 = SRAM
9 = RAM
10 = ROM
11 = Flash
12 = EEPROM
13 = FEPROM
14 = EPROM
15 = CDRAM
16 = 3DRAM
17 = SDRAM
18 = SGRAM
19 = RDRAM
20 = DDR
21 = DDR-2
‘@

}

Get-WmiObject -Class Win32_PhysicalMemory |
Format-Table BankLabel, PositionInRow, 
@{Name="Size GB"; Expression={[math]::round($($_.Capacity/1GB), 2)}}, 
DataWidth, DeviceLocator, 
@{Name="Form factor"; Expression={$form["$($_.FormFactor)"]}},
@{Name="Memory type"; Expression={$type["$($_.MemoryType)"]}}, 
Speed, TotalWidth -autosize

We can turn to the Win32_PhysicalMemory class. It will show us each memory module, the size, which bank it is in, the speed and the data width