WMI and CIM dates

A question on the forum asked about extracting the year from the ReleaseDate property returned by Win32_BIOS

 

They were trying to do this

Get-CimInstance Win32_BIOS | Select-Object @{n=”ReleaseDate”;e={$_.ConvertToDateTime($_.ReleaseDate).year()}}

 

There are 2 problems with this approach – firstly the objects that Get-CimInstance produces don’t have the ConvertToDateTime method (its added by PowerShell to the objects produces by Get-WmiObject) and secondly on a DateTime object Year is a property not a method.

 

If you use the WMI cmdlet you see this

£> Get-WmiObject -Class Win32_Bios | select Releasedate

Releasedate
———–
20140512000000.000000+000

 

The date is in WMI format and needs to be converted.

£> Get-WmiObject Win32_BIOS | Select-Object @{n=”ReleaseDate”;e={$_.ConvertToDateTime($_.ReleaseDate)}}

ReleaseDate
———–
12/05/2014 01:00:00

 

If you want just the year

£> Get-WmiObject Win32_BIOS | Select-Object @{n=”ReleaseDate”;e={($_.ConvertToDateTime($_.ReleaseDate)).Year}}

ReleaseDate
———–
       2014

 

This conversion is already done for you with the CIM cmdlets

£> Get-CimInstance -CimSession $c -ClassName Win32_Bios | select ReleaseDate

ReleaseDate
———–
12/05/2014 01:00:00

 

Again if you just want the year

£> ((Get-CimInstance -CimSession $c -ClassName Win32_Bios).ReleaseDate).Year
2014

Posted in CIM, PowerShell and WMI | Leave a comment

Creating a DHCP reservation

For my demo at the PowerShell Summit I wanted to use DHCP for the Linux machine but guarantee that it had a specific IP address.  Time to create a DHCP reservation

 

The DHCP module in Windows Server 2012 and 2012 R2 enables you to create a reservation:

Add-DhcpServerv4Reservation -ScopeId 10.10.54.0 -IPAddress 10.10.54.2 -ClientId 00155D36C906 -Description “LInux machine” -Name “SphinxLX01″

 

The clientid is the VMs MAC address.

 

You can view the current reservations:

 

£> Get-DhcpServerv4Reservation -ScopeId 10.10.54.0 | fl *

IPAddress             : 10.10.54.2
ScopeId               : 10.10.54.0
AddressState          : ActiveReservation
ClientId              : 00-15-5d-36-c9-06
Description           : LInux machine
Name                  : SphinxLX01
Type                  : Both

 

You can view current leases:

£> Get-DhcpServerv4Lease -ScopeId 10.10.54.0 | fl *

IPAddress             : 10.10.54.2
ScopeId               : 10.10.54.0
AddressState          : ActiveReservation
ClientId              : 00-15-5d-36-c9-06
ClientType            : Dhcp
Description           : LInux machine
DnsRegistration       : NotApplicable
DnsRR                 : NoRegistration
HostName              : SphinxLX01
LeaseExpiryTime       :
NapCapable            : False
NapStatus             : FullAccess
PolicyName            :
ProbationEnds         :
ServerIP              : 10.10.54.201

 

And all from the comfort of your very own PowerShell prompt

Posted in DHCP, PowerShell v4, Windows Server 2012 R2 | Leave a comment

Getting the most from your PowerShell Summit

With the first European PowerShell Summit rapidly approaching – 11 days and counting – I thought I’d give you a few ideas on how to get the maximum out of the Summit.

First – ask questions – lots of questions.  The speakers are masters of their topics and if you need to drill deeper to understand something talk to them in the breaks or over lunch. At Summits in North America we’ve had discussions go on well into the early morning!

 

Don’t try and copy code that you see.  The demo code and slides will be available after the Summit.

 

All of the sessions are recorded so you will have a chance to replay bits you need to see again. Some of the speakers will cram a lot into the sessions so accessing the recordings will be useful

 

Talk to your fellow attendees – I seen discussions where one persons problem was solved by another attendee who’d gone through the same issues

 

Make suggestions for topics you’d like covered at future Summits – if we get enough demand for a topic we’ll find a speaker

 

Representatives of the PowerShell will be present, and speaking. Talk to them. Tell them what you like. More importantly tell them what you don’t like or what isn’t working for you.  They love feed back from real users.

 

A number of PowerShell MVPs will be speaking or in the audience. This is your opportunity to talk to them and  ask your difficult questions. They are recognised experts and will be more than willing to help.

 

Lastly – ask questions. Lots of questions. If you can’t get your questions answered at a PowerShell Summit – there is a serious problem.

Posted in Powershell, Summit | Leave a comment

Output from jobs

I tripped over a little problem the other day that’s worth reporting.  I was running something like this:

 

$sb = {
$procs = get-service
$procs | Export-Csv test.csv -NoTypeInformation
}

Start-Job -ScriptBlock $sb -Name test

 

I was collecting some data and outputting a CSV.  My problem was more complex but this stands as a good example

 

I didn’t get the data I wanted

 

Thinking about it I put the full path to where I wanted the CSV

 

$sb = {
$procs = get-service
$procs | Export-Csv C:\MyData\scripts\Test\test.csv -NoTypeInformation
}

Start-Job -ScriptBlock $sb -Name test

 

And it works.

 

So where did my data go in the original version?

 

I ran this

 

$sb = {
Get-Location

$procs = get-service
$procs | Export-Csv test.csv -NoTypeInformation
}

Start-Job -ScriptBlock $sb -Name test

 

And then pulled the data from the job

 

£> Receive-Job -Id 10

Path
—-
C:\Users\Richard\Documents

 

Obvious really – a job runs in a new powershell process that doesn’t run your profile so it starts in the default location  – which is your home directory. And sure enough the CSV file is there

 

£> ls C:\Users\Richard\Documents\*.csv

    Directory: C:\Users\Richard\Documents

Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—        14/09/2014     11:50      46042 test.csv

 

I can’t remember how many times I’ve told people that PowerShell jobs run in a separate process so I should have realised.  Excellent example of the more you know the more you need to learn

Posted in Powershell Basics | Leave a comment

Multiple triggers on a scheduled task

Setting up a scheduled task can be accomplished like this:

 

$taskname = ‘Test Job’

Get-ScheduledTask -TaskName $taskname -ErrorAction SilentlyContinue |  Unregister-ScheduledTask -Confirm:$false

 

$trigger = New-ScheduledTaskTrigger -Daily -At 03:00

 

$actionscript = ‘-NoExit -NonInteractive -NoProfile -WindowStyle Normal -NoLogo -Command “&{get-process}”‘

$pstart =  “C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe”

$action = New-ScheduledTaskAction -Execute $pstart -Argument $actionscript
Register-ScheduledTask -TaskName $taskname -Action $action -Trigger $trigger -RunLevel Highest -Description “Test job”

 

Define the task name and then unregister (remove) any instances of that task

 

You then define the trigger and actions and finally register the task with the name you defined earlier.

 

The script above will create a task to run at 3am.

 

You can force the task to run as a test:

Start-ScheduledTask -TaskName ‘Test Job’

 

But what about if you want to run the task multiple times during the day. Simple.  You define multiple triggers:

 

$taskname = ‘Test Job’

Get-ScheduledTask -TaskName $taskname -ErrorAction SilentlyContinue |  Unregister-ScheduledTask -Confirm:$false

 

$triggers = @()
$triggers += New-ScheduledTaskTrigger -Daily -At 03:00
$triggers += New-ScheduledTaskTrigger -Daily -At 09:00
$triggers += New-ScheduledTaskTrigger -Daily -At 15:00
$triggers += New-ScheduledTaskTrigger -Daily -At 21:00

 

$actionscript = ‘-NoExit -NonInteractive -NoProfile -WindowStyle Normal -NoLogo -Command “&{get-process}”‘

$pstart =  “C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe”

$action = New-ScheduledTaskAction -Execute $pstart -Argument $actionscript
Register-ScheduledTask -TaskName $taskname -Action $action -Trigger $triggers -RunLevel Highest -Description “Test job”

 

 

Define an array and then add the triggers into it. Remember to use the array when you register the task.

 

You can test the triggers on a scheduled task:

Get-ScheduledTask -TaskName ‘Test Job’ | select -ExpandProperty Triggers

Posted in Powershell | Leave a comment

OneNote and XML–finding pages

Pages are towards the bottom of the hierarchy in OneNote – though we still haven’t dived into the content of pages yet.

 

You can find the pages in your notebooks like this:

 

$onenote = New-Object -ComObject OneNote.Application
$scope = [Microsoft.Office.Interop.OneNote.HierarchyScope]::hsPages
[ref]$xml = ”

$onenote.GetHierarchy($null, $scope, $xml)

$schema = @{one=”http://schemas.microsoft.com/office/onenote/2013/onenote”}

$xpath = “//one:Notebook/one:Section”
Select-Xml -Xml ([xml]$xml.Value) -Namespace $schema -XPath $xpath |
foreach {
$psitem.Node.Name
}

 

There’s one drawback to this – all you get is the page names:

PowerShell Summit
Comedy
Personal information
Book Series
AD
Applications
CCNA
Exchange
Infrastructure Architecture
Operations
Security
Hyper-V
WMI
PS Deep Dive
Deep Dive US12

 

You need to play around with Xpath a bit more to get a meaningfiul structure – ideally notebook – section – page

Posted in Office 2013, Powershell | Leave a comment

OneNote and XML–finding sections

I recently showed how to find the names of your OneNote notebooks.  The next level down is the section.  You can find these sections in a notebook like this:

 

$onenote = New-Object -ComObject OneNote.Application
$scope = [Microsoft.Office.Interop.OneNote.HierarchyScope]::hsPages
[ref]$xml = ”

 

$onenote.GetHierarchy($null, $scope, $xml)

 

$schema = @{one=”http://schemas.microsoft.com/office/onenote/2013/onenote”}

 

$xpath = “//one:Notebook/one:Section”
Select-Xml -Xml ([xml]$xml.Value) -Namespace $schema -XPath $xpath |
foreach {
$node = $psitem.Node

$npath = Split-Path -Path $node.Path -Parent
 
$props = [ordered]@{
   Workbook =  Split-Path -Path $npath -Leaf
   Section = $node.Name
}
New-Object -TypeName PSObject -Property $props
}

 

The first part of the script where the application object is created, the scope set and you get the hierarchy is the same as before.  The two scripts diverge when you get to the Xpath you’re going to use.  To find the notebooks you used:

 

$xpath = “//one:Notebook”

 

which means get me any Nodes called one:Notebook

 

To find the section you use:

 

$xpath = “//one:Notebook/one:Section”

 

which means any nodes called one;Section that are children of a one:Notebook node.

 

Remember XML is case sensitive.

 

Once you have the section nodes – which look like this:

 

name             : Quick Notes
ID               : {9EFAE9AC-0388-424A-8211-02E8FFE50666}{1}{B0}
path             : https://d.docs.live.net/43cfa46a74cf3e96/Documents/Personal (Web)/Quick Notes.one
lastModifiedTime : 2014-09-04T17:48:07.000Z
color            : #B7C997
Page             : {OneNote: one place for all of your notes, OneNote Basics}

 

You can extract the data you want. The path property can be used to extract the name of the note book with a little bit of Split-Path magic.

 

Next time you’ll see how to get down to the individual pages

Posted in Office 2013, Powershell | Leave a comment