Your basic ITPro blog... What's going on at work, what I'm interested in.

Friday, May 2, 2008

2008-05-02 PowerShell Exercise

Well, it's been a while since I have posted a PowerShell example. But, today's "Hey, Scripting Guy" is another great example of how PowerShell can really be the right tool for the right job. Now, to be fair, the question specifically asked about using VBScript. But, why not use PoSH when the solution is so much more elegant? Just look...

QUESTION:

Hey, Scripting Guy! I Using VBScript, how can I identify the 20 most-recently modified files in a folder?
-- TW

SCRIPTING GUY ANSWER:

Const adVarChar = 200
Const MaxCharacters = 255
Const adFldIsNullable = 32

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colFiles = objWMIService.ExecQuery _
    ("ASSOCIATORS OF {Win32_Directory.Name='C:\Scripts'} Where " _
        & "ResultClass = CIM_DataFile")

Set DataList = CreateObject("ADOR.Recordset")
DataList.Fields.Append "FileName", adVarChar, MaxCharacters, adFldIsNullable
DataList.Fields.Append "ModifiedDate", adVarChar, MaxCharacters, adFldIsNullable
DataList.Open

For Each objFile In colFiles
    DataList.AddNew
    DataList("FileName") = objFile.Name
    DataList("ModifiedDate") = objFile.LastModified
    DataList.Update
Next

DataList.Sort = "ModifiedDate DESC"

For i = 1 to 20
    dtmWMIDate = DataList.Fields.Item("ModifiedDate")
    dtmConvertedDate = CDate(Mid(dtmWMIDate, 5, 2) & "/" & Mid(dtmWMIDate, 7, 2) & _
        "/" & Left(dtmWMIDate, 4) & " " & Mid (dtmWMIDate, 9, 2) & ":" & _
            Mid(dtmWMIDate, 11, 2) & ":" & Mid(dtmWMIDate, 13, 2))
    Wscript.Echo DataList.Fields.Item("FileName") & " -- " & dtmConvertedDate
    DataList.MoveNext
Next

MY POWERSHELL ANSWER:

Get-ChildItem | Sort-Object LastWriteTime -Descending | Select-Object -First 20

No comments:

Additional Info

My photo
email: support (AT) mangrumtech (DOT) com
mobile: 480-270-4332