UG Recording

Thank you to those people who joined the Live Meeting tonight. The recording details are below.  It will be available for 365 days from now.

Richard Siddaway has invited you to view a Microsoft Office Live Meeting recording.
View Recording
Recording Details
    Subject: PowerShell UG
    Recording URL: https://www.livemeeting.com/cc/usergroups/view
    Recording ID: 5JCG5C
    Attendee Key: X8g}hNd[c

This Office Live Meeting invitation is a personal invitation meant only for you. It should not be forwarded. If you received this email by mistake or require Live Meeting Assistance, please refer to the Live Meeting Assistance Center at http://r.office.microsoft.com/r/rlidLiveMeeting?p1=12&p2=en_US&p3=LMInfo&p4=support

The slides and demo scripts can be downloaded from http://cid-43cfa46a74cf3e96.skydrive.live.com/browse.aspx/PowerShell%20User%20Group/February%5E_2010

Technorati Tags: ,
Posted by RichardSiddaway | with no comments

PSCX: Set-FileTime

The PowerShell Community Extensions have a cmdlet Set-FileTime that can do the same thing we did in a script earlier.  I have rewritten the script to use the cmdlet

001
002
003
004
005
006
007
008
009
010
011
012
013
014
Get-ChildItem -Path C:\Test\csvtests -Filter "*.xlsx" | 
Select Name, CreationTime, LastWriteTime

Get-ChildItem -Path C:\Test\csvtests -Filter "*.xlsx" | foreach {
    $oldname =  "$_" -replace ".xlsx", ".csv"
    $oldfile = Join-Path -Path c:\test\csvtests -ChildPath $oldname
    if (Test-Path -Path $oldfile) {
        $old = Get-Item -Path $oldfile
        Set-FileTime -Time $($old.CreationTime) -Created -Path $($_.Fullname) -Force -Verbose
    }
}

Get-ChildItem -Path C:\Test\csvtests -Filter "*.xlsx" | 
Select Name, CreationTime, LastWriteTime

Pretty much the same as before except we save a couple of lines by using the cmdlet.

Technorati Tags: ,,
Posted by RichardSiddaway | with no comments

Change File Dates

Interesting question on the forums about changing the date of files.  Poster was converting a bunch of video files between formats and wanted the file in the new format to have the creation date of the original file.

I had some csv files that i could convert to excel files that mimic the problem

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
Get-ChildItem -Path C:\Test\csvtests -Filter "*.xlsx" | 
Select Name, CreationTime, LastWriteTime

Get-ChildItem -Path C:\Test\csvtests -Filter "*.xlsx" | foreach {
    $oldname =  "$_" -replace ".xlsx", ".csv"
    $oldfile = Join-Path -Path c:\test\csvtests -ChildPath $oldname
    if (Test-Path -Path $oldfile) {
        $old = Get-Item -Path $oldfile
        $new = Get-Item $_.Fullname
        $new.CreationTime = $old.CreationTime
    }
}

Get-ChildItem -Path C:\Test\csvtests -Filter "*.xlsx" | 
Select Name, CreationTime, LastWriteTime

Check the date on the new files.

Get the new files and for each file replace the extension with that of the old file (I am assuming the name stays the same!). Test the old file exists and if so set the new file creation date to the old file creation date.

A final test with get-childitem shows the change.

 

PowerShell Community Extensions has a Set-FileTime cmdlet that can do this

 

Technorati Tags: ,
Posted by RichardSiddaway | with no comments

PowerShell, WMI and WQL

Don’t forget the PowerShell UG Live Meeting on Tuesday 9 February at 7:30 GMT . Details can be found here

http://msmvps.com/blogs/richardsiddaway/archive/2010/01/24/ug-meeting-9-february.aspx

Technorati Tags: ,,

WMI blog update: February 2010

I mentioned a while ago that I’d started another blog, mainly based around PowerShell and WMI. it can be found at

http://itknowledgeexchange.techtarget.com/powershell/.

Recent topics include:

  • defrag analysis of Windows volumes
  • using WMI to chkdsk a volume
  • mapping physical drives to logical drives
  • mount points
  • detailed information of logical and physical disks
  • retrieving information on partitions
  • finding installed hotfixes
  • shutting down computers
  • discovering information about the Operating System
Technorati Tags: ,

Tail-File

Continuing our ramble through the goodies in PowerShell Community Extensions 2.0 we come to Tail-File. It is fairly easy to get the first n lines of a file.

Get-Content -Path C:\Scripts\HelpFiles\About\about_activedirectory_objectmodel.help.txt -TotalCount 15

will display the first 15 lines in the file. This is comparable to the top command.  Getting the last 15 lines is a bit more difficult using get-content  - we have to read the file into an array and then display the last 15 records.

Alternatively, Tail-File comes galloping over the hill to our rescue

Tail-File -Path C:\Scripts\HelpFiles\About\about_activedirectory_objectmodel.help.txt -count 15

will display the last 15 lines.  If we don’t use the –count parameter we get the last 10 lines.

We can even wait and pick off the latest lines of a growing log file if required.

Another useful cmdlet.

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

View Access table definitions part 2

 

Following on from the last post we wanted to be able to look at the table definitions

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
$datatype = DATA {
ConvertFrom-StringData -StringData @'
3 = Integer
7 = Date
130 = String
'@

}
function Get-AccessTableDefinition {
param (
    [string]$name,
    [string]$path,
    [string]$table = ""
)
    $file = Join-Path -Path $path -ChildPath $name 
    if (!(Test-Path $file)){Throw "File Does Not Exists"}

    $conn = New-Object -ComObject ADODB.Connection
    $conn.Open("Provider = Microsoft.JET.OLEDB.4.0; Data Source = $file")
    $cat = New-Object -ComObject ADOX.Catalog
    $cat.ActiveConnection = $conn

## view tables
## note user tables are of type TABLE
    if ($table) {
        $actable = $cat.Tables | where {$_.Name -eq $table}
        $actable.Columns | Format-Table Name, DefinedSize, 
        @{Name="Data Type"; Expression={$datatype["$($_.Type)"]}}  -AutoSize
    }
    else {$cat.tables | select Name, DateCreated, DateModified}
       
    $conn.Close()
}

 

We modify our function by defining a hash table to contain the data types and adding a table parameter to the function.

We test if the table parameter has been specified and if so get the particular table and dump the column information.  Note the use of the calculated expression for the column data type.  I’ve only covered the three types I know are in this table.  The others will be added later or see http://msdn.microsoft.com/en-us/library/ms675318(VS.85).aspx if you can’t wait.

The function can be used like this:

PS> Import-Module accessfunctions -Force
PS> Get-AccessTableDefinition -name test03.mdb -path c:\test

Name                                    DateCreated                             DateModified
----                                    -----------                             ------------
MSysAccessStorage                       23/11/2009 17:22:56                     23/11/2009 17:22:56
MSysACEs                                23/11/2009 17:18:33                     23/11/2009 17:18:33
MSysNameMap                             30/11/2009 10:44:44                     30/11/2009 10:44:44
MSysNavPaneGroupCategories              23/11/2009 17:22:56                     23/11/2009 17:22:56
MSysNavPaneGroups                       23/11/2009 17:22:56                     23/11/2009 17:22:56
MSysNavPaneGroupToObjects               23/11/2009 17:22:56                     23/11/2009 17:22:56
MSysNavPaneObjectIDs                    23/11/2009 17:22:58                     23/11/2009 17:22:58
MSysObjects                             23/11/2009 17:18:33                     23/11/2009 17:18:33
MSysQueries                             23/11/2009 17:18:33                     23/11/2009 17:18:33
MSysRelationships                       23/11/2009 17:18:33                     23/11/2009 17:18:33
test1                                   23/11/2009 17:22:41                     10/01/2010 15:47:10

PS> Get-AccessTableDefinition -name test03.mdb -path c:\test -table test1

Name      DefinedSize Data Type
----      ----------- ---------
DOB                 0 Date
FirstName         255 String
ID                  0 Integer
LastName          255 String

 

Technorati Tags: ,,
Posted by RichardSiddaway | with no comments

View Access table definitions

We’ve looked quite a bit at how we can work with Access databases but how do we investigate the structure of the database.  The first thing we need to know is the tables in our database

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
function Get-AccessTableDefinition {
param (
    [string]$name,
    [string]$path
)
    $file = Join-Path -Path $path -ChildPath $name 
    if (!(Test-Path $file)){Throw "File Does Not Exists"}

    $conn = New-Object -ComObject ADODB.Connection
    $conn.Open("Provider = Microsoft.JET.OLEDB.4.0; Data Source = $file")
    $cat = New-Object -ComObject ADOX.Catalog
    $cat.ActiveConnection = $conn

## view tables
## note user tables are of type TABLE
    $cat.tables | select Name, DateCreated, DateModified
    $conn.Close()
}

 

The first part of the function tests that the file exists – we’ve seen this before when opening databases. Previous functions have mainly relied on SQL and ADO.NET capability.  In this case we are using ADO (the older brother of ADO.NET). We need to create a COM object for the connection and open it using the path to our database.  This will fail if we already have the database open!!  We will see how to cope with this later.  We then need to create a ADO Active X catalog representing the database. From that we can list our tables. This list includes the system and user tables.

Next stages are to put in some error handling and decide how we will display the structure of an individual table.

Technorati Tags: ,,
Posted by RichardSiddaway | with no comments

Test-Script

I’m going to do a few posts on the PowerShell Community Extensions 2.0 beta i mentioned earlier.  It downloads and installs without a problem.

One immediate issue on loading is that it replaces my help function – big no no.  Bad PSCX! I don’t like having my configuration arbitrarily altered.  That I can deal with and prevent. 

In this post I’ll look at test-script. This is a neat cmdlet that accepts the path to a script as input, reads the script and returns any errors.  I found a copy of a script with some errors, no not one of mine, it came from an old Scripting Games competition.

 

for ($i in Get-ChildItem C:\Scripts)
(
    if {($i.CreationTime -gt ($(Get-Date).AddMonths(-10))) and ($i.Extension = "txt")}
    {
         Copy-Item $i.FullName C:\old
         $i.Name
         $x = $x + 1
    }
)

""
"Total Files: " + $y

 

Then put the script through the cmdlet

PS> Test-Script -Path c:\test\DebugMe.ps1
WARNING: Parse error on line:1 char:9 - Unexpected token 'in' in expression or statement.
WARNING: Parse error on line:1 char:12 - Unexpected token 'Get-ChildItem' in expression or statement.
WARNING: Parse error on line:1 char:26 - Unexpected token 'C:\Scripts' in expression or statement.
WARNING: Parse error on line:2 char:1 - Missing statement body in for loop.
WARNING: Parse error on line:3 char:60 - Unexpected token 'and' in expression or statement.
WARNING: Parse error on line:3 char:64 - Unexpected token '(' in expression or statement.
WARNING: Parse error on line:3 char:65 - Unexpected token 'i' in expression or statement.
WARNING: Parse error on line:3 char:67 - Unexpected token '.Extension' in expression or statement.
WARNING: Parse error on line:3 char:78 - Unexpected token '=' in expression or statement.
WARNING: Parse error on line:3 char:80 - Unexpected token 'txt' in expression or statement.
WARNING: Parse error on line:3 char:85 - Missing closing '}' in statement block.
WARNING: Parse error on line:3 char:86 - Missing closing ')' in expression.
WARNING: Parse error on line:3 char:86 - Unexpected token '}' in expression or statement.
False
PS>

 

We can also display lines around the error as well.

This is a useful addition to the PowerShell toolkit

Technorati Tags: ,,
Posted by RichardSiddaway | with no comments
Filed under:

PowerGUI 2.0

While we are on the subject of new releases PowerGUI 2.0 recently became available. An excellent tools with a very good PowerShell editor – it should be part of everyone’s PowerShell toolbox

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

PSCX 2.0

I have mentioned  PowerShell Community Extensions many times over the last few years. I have found them a very useful set of utilities to extend the basic PowerShell install. With PowerShell v2 there was an irritation that a few of the cmdlets

Get-Random
Start-Process
Select-Xml

overrode the PowerShell v2 cmdlets of the same name.

That has been fixed with the PSCX v2 beta that is available from http://pscx.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=39405. It is module based so use it on PowerShell 2. It is a simple zip file, so download it, unblock it and unzip it to your module path.

It loads using import-module and looks to be full of goodies.  The PSCX guys have done a good job with this. Time to give it a whirl and see how it works.

Posted by RichardSiddaway | with no comments
Filed under:

Date reminders: PowerShell User Group

Quick reminders of upcoming dates for Live Meeting (virtual) sessions:

Tuesday 9 February – PowerShell, WMI and WQL

Tuesday 2 March – Powershell, Windows 7 and the Windows 7 Resource Kit

Both sessions start at 7:30 pm GMT

Technorati Tags:
Posted by RichardSiddaway | with no comments

Sites for PowerShell User Groups

If you are looking for a PowerShell User Group in your area check out

http://powershellgroup.org/

 

It includes sites for a number of groups and links to others.  The events calendar is good for showing what is happening in the PowerShell world

Technorati Tags:
Posted by RichardSiddaway | with no comments

AD cmdlets UG meeting

Thank you to everyone who linked in to the user group meeting tonight.  There were some good questions. I’ll post the scripts, demo text, slides and recording as soon as I can find a home for it – its a 30MB+ file.

Technorati Tags:
Posted by RichardSiddaway | with no comments

Correct version of PowerShell

It seems that versions of the PowerShell v2 CTP are still being used and problems are being reported because the incorrect version of PowerShell is being used.

Tobias has a great post explaining which version you should be using and providing tools to check your PowerShell installation.

http://powershell.com/cs/blogs/tobias/archive/2010/01/24/are-you-using-the-correct-powershell-version.aspx

 

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

Remember Tuesday

Tuesday 26 January 7:30 GMT

PowerShell User group meeting on Windows 2008 R2 AD cmdlets

Details from

http://msmvps.com/blogs/richardsiddaway/archive/2010/01/06/uk-user-group-meeting-jan-2010.aspx

Technorati Tags: ,
Posted by RichardSiddaway | with no comments

UG Meeting 9 February

Second Meeting of the year


When: Tuesday, Feb 9, 2010 7:30 PM (GMT)


Where:

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

Powershell, WMI and WQL

Notes


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: 5JCG5C
    Entry Code: X8g}hNd[c
    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.

Technorati Tags:

PowerShell in Practice Update

In case you were wondering what was happening with this book – the good news is that it has started progressing again.  It has been through Technical review as wel as the third general review. It is now in the hands of the editors and heading towards production.

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

Methods and properties of data types

Do you sometimes get stuck & can’t remember the methods and properties of a string or an integer?  No its not galloping senility honest.

One quick way to get the information is to pass an object of the appropriate type into get-member e.g.

"agafgf" | gm
1 | gm

 

saves having to remember everything

Technorati Tags:
Posted by RichardSiddaway | with no comments
Filed under:

Appending to a CSV file

One of the frustrations of working with files in PowerShell is that you can’t append to a pre-existing CSV file.

Dmitry has fixed that for version 2 by creating a proxy function that adds that capability.

http://dmitrysotnikov.wordpress.com/2010/01/19/export-csv-append/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+DmitrysPowerblog+%28Dmitry%27s+PowerBlog%29

Excellent

Technorati Tags:
Posted by RichardSiddaway | with no comments
Filed under:
More Posts Next page »