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

Friday, March 21, 2008

2008-03-21 PowerShell Exercise

The first thing you will probably notice is that I did not use regular expressions. There were a couple of reasons for this. One, it just seemed easier to trim the 'license' string, cutting off the ")," which is present in every record. This seemed easier to me than using regular expressions because, is at turns out, I don't really know how to use them... something I need to learn.

The first few lines of my script actually build the text file used as input. I could have done this in notepad or whatever, but thought it I would do it in the script itself...

I hope you enjoy these, or at least find them a bit interesting.

QUESTION:

Hey, Scripting Guy! I'm trying to automate a tedious license server task. To do this, I need to loop through a text file line-by-line, grab out a user name, asset number, and license ID, and then pass those values to a batch file. How can I do all that?

Sample Data:
Username1 asset1 asset1 (v24) (licserver/1000 1111), start Wed 3/19 8:50
Username2 asset2 asset2 (v24) (licserver/1000 1112), start Wed 3/19 8:55
Username3 asset3 asset3 (v24) (licserver/1000 1113), start Wed 3/19 8:59

SCRIPTING GUYS SOLUTION:

Const ForReading = 1 Set objShell = CreateObject("Wscript.Shell") Set objRegEx = CreateObject("VBScript.RegExp") objRegEx.Pattern = "\d{1,}" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("C:\Scripts\Test.txt", ForReading) Do Until objFile.AtEndOfStream strLine = objFile.ReadLine arrItems = Split(strLine, " ") strUserName = arrItems(0) strAsset = arrItems(1) strLicenseID = arrItems(5) Set colMatches = objRegEx.Execute(strLicenseID) strLicense = colMatches(0).Value strCommand = "%compsec% /c C:\Scripts\Test.cmd " & strUserName & " " & strAsset & " " & strLicense objShell.Run strCommand, 1, True Loop objFile.Close

MY SOLUTION:

# Create test data file New-Item -Name "test.txt" -ItemType "File" -Force -Value ` "Username1 asset1 asset1 (v24) (licserver/1000 1111), start Wed 3/19 8:50 Username2 asset2 asset2 (v24) (licserver/1000 1112), start Wed 3/19 8:55 Username3 asset3 asset3 (v24) (licserver/1000 1113), start Wed 3/19 8:59" #Process the records $records = Get-Content "test.txt" foreach ($record in $records) { $arrElements = $record.Split(" ") $userName = $arrElements[0] $asset = $arrElements[1] $license = $arrElements[5].Substring(0,$arrElements[5].length - 2) Invoke-Item ".\test.cmd $userName $asset $license" }

No comments:

Additional Info

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