February 2010 - Posts

PSCX: Get-DriveInfo

A simple cmdlet that returns information about the local drives

PS> Get-DriveInfo

VolumeLabel        Name          UsedSpace          FreeSpace   TotalSize %Free
-----------        ----          ---------          ---------   --------- -----
Local Disk         C:\      57,026,994,176    114,771,693,568      160 GB  67 %
Local Disk         D:\      11,427,856,384     66,725,654,528   72.786 GB  85 %
Local Disk         G:\         759,332,864      1,337,524,224    1.953 GB  64 %

 

 

Compare it with Get-PSDrive in PowerShell v2

 

PS> Get-PSDrive | where {$_.Name -like "?"} | ft -a

Name Used (GB) Free (GB) Provider   Root CurrentLocation
---- --------- --------- --------   ---- ---------------
C        53.11    106.89 FileSystem C:\          scripts
D        10.64     62.14 FileSystem D:\
E                        FileSystem E:\
F                        FileSystem F:\
G          .71      1.25 FileSystem G:\

 

The used and free information wasn’t available in PowerShell v1

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

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:
More Posts « Previous page