Archive

Archive for the ‘Scripts’ Category

Renaming Files In A Directory

September 2nd, 2009 1 comment

So I had a problem on Windows in that I have lots of directories that are named correctly but I wish the files under them to be uniformly named.

The solution was to use PowerShell, which is an extremely effective scripting tool for Windows, especially if you come from a UNIX shell background.

There is actually quite a lot of documentation available for it and rather than go into detail I will simply show you the script:

#
# RenameDirectoryFiles.ps1
#
 
param( [string[]]$paths )
Set-PSDebug -Strict
 
foreach ( $path in $paths ) {
    if ( !(Test-Path $path -PathType Container) ) {
        Write-Error "'$path' doesn't exist or isn't a directory"
        exit 1
    }
 
    $i = 0
    Get-ChildItem $path | sort FullName | foreach {
        $tmp = "{0:000}" -f $i
        $ext = $_.Extension
        $newname = "$path - $tmp$ext"
        Rename-Item $_.fullname $newname
        $newname
        $i = $i + 1
    }
}

So the usage is extremely simple:

RenameDirectoryFiles.ps1 'My Directory'

After which all the files under ‘My Directory’ will be renamed to ‘My Directory – 000.fileextension’.

Tags: ,

Skinning A Cat

May 17th, 2009 No comments

I was recently discussing with someone about sed usage. They were having difficultly creating an appropriate regex to handle their problem:

(Orlando) sed regex kicks my ass.  I like to remove the second : in the
line. So that in 123:456:6789 it will only returns 123:456.  I can find the
first :, but I have not been able to use s/:{2}// to find the second
one, and remove the rest.

I enjoy regex (I know I’m weird, leave me alone), so I was able to provide an answer to this problem:

(@znx) Orlando: the trick is to use [^:] and \1 ..
(@znx) like:   s/\(:[^:]*\):.*/\1/

Now obviously at first glance this regex could be a bit intimating to someone who is still picking up the skills but as with most things if we break it down it becomes easier.

Working out to in, \( \):.*, that says match something with : at the end and all the character after it. The . is a special meaning “any character” and * to match multiple characters. The first match will be stored by sed and assigned into the \1 for the replacement (that is what the brackets do). Inside the brackets we have :[^:]*. The sequence [^ ] is a negated list, that means that we are asking it to match everything that is NOT inside the list, in this case :.

Putting it altogether we are saying: Match a leading : and a trailing : with any characters after it. Placing the contents between the two : in memory. Then finally we replace the contents.

% echo 123:456:6789 | sed 's/\(:[^:]*\):.*/\1/'
123:456

Sucess, however as with most things, there is more than one way to skin a cat and regex is rarely the prettiest method. So what other ways can we solve this problem?

With AWK:

% echo 123:456:6789 | awk -F: '{print $1":"$2}'
123:456

With cut:

% echo 123:456:6789 | cut -d: -f1,2
123:456

As always, experimentation with the mass of GNU tools you can find on your system will bring a greater deal of power to your tool chest. Mind you, then I wouldn’t get complements for helping would I?

(Orlando) Wow, When I grow up, I like to remember this thing like you do. :-) 

Haha, till next time!

Tags: ,

BigBrother Scripting

March 17th, 2009 No comments

I was recently asked if it was possible to monitor the Event Log for a single event and ensure that it was occurring regularly. It is rare that I handle Windows scripting and when I do I normally find myself cursing it, haha! In this case we want to ensure that a print server is constantly printing through the day, we expect that at least 1 print job will occur every 15 minutes, if not then we’d like a warning. Obviously this check should only run during work hours.

So the first step is relatively simple, access the Event Log and look for a single event by its event code.

set objWMIService = GetObject("winmgmts:\root\cimv2")
set colEvents = objWMIService.ExecQuery _
   ("Select * from Win32_NTLogEvent Where Logfile = 'System' and EventCode = 10")

What we did here was grab all the events with event code of 10 (a print job!). So if we count the number of events within a range then we will have basically completed a huge part of the work.

So next step is to make an interval that will be 15 minutes back from whatever time is current.

set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
dtmStartDate.SetVarDate DateAdd("n",-15,Now()),True

And applying that into our statement:

set colEvents = objWMIService.ExecQuery _
   ("Select * from Win32_NTLogEvent Where Logfile = 'System' and EventCode = 10" _
   & " and TimeWritten >= '" & dtmStartDate & "'")

This means that we are now collecting the events that only occurred within the last fifteen minutes. So what next, well we need to have a statement to pass to BigBrother to indicate success or failure. Fortunately enough I have another script which monitors the cluster (thanks to the awesome DeadCat repository) and it has some code to help place the file that BigBrother collects.

const HKLM = &H80000002
strBBExtPathNew = "SOFTWARE\Quest Software\BigBrother\bbnt\ExternalPath"
strBBExtPathOld = "SOFTWARE\BigBrother\bbnt\ExternalPath"
set oReg = GetObject("winmgmts:\root\default:StdRegProv")
 
oReg.GetStringValue HKLM,strBBExtPathNew,,strExtPath
if isNull(strExtPath) then
  oReg.GetStringValue HKLM,strBBExtPathOld,,strExtPath
end if
if isNull(strExtPath) then
  WScript.Quit
end if

Read more…

Tags: ,

File Oddity

February 13th, 2009 No comments

Today at work I was attempting to parse a file and discovered something odd happening. When I simply viewed the file with cat, I could see this:

<html><head><title>Status</title></head>
<table>
<tr><td>Failed</td><td>Backup Group</td></tr>
<tr><td>Success</td><td>Another Backup Group</td></tr>
</table>
</body>
</html>

Nothing odd there, the file is normal but when I tried this command:

$ grep -i failed status.html
$

Huh? No output, suggesting that there is no lines with the words failed on them. The same occurs with awk and sed, indeed I could not find any tool to be able to grep out the status. So the next step was to check what was odd about the file:

$ file status.html
status.html: HTML document text

Still, nothing unusual. So now I am in full head scratching mode, I open up the file with vim to see if I can discover anything strange about the file but nothing. At this point I happened to switch to more rather than cat and the result was the start of how I solved it.

$ more status.html
��<

$

Ah, so now I can see why grep and the others cannot view anything in the file. So this time I switch to vim again and check what file encoding we have:

:set fileencoding
fileencoding=ucs-2le

For those that are unaware, this is UCS-2 (little endian), also know as UTF-16. So the issue was simply that we had UTF-16 characters, now for the trick to get around it:

$ iconv -f UTF-16 -t UTF-8 status.html | grep -i failed
<tr><td>Failed</td><td>Backup Group</td></tr>
$

Tada. Once more a solution!

Tags: ,

Fun With Bmotion

February 4th, 2009 No comments

I help out now and then with little bits of code for BMotion, the main coder is JamesOff. It is a wonderful set of scripts for AI on eggdrops. Sometimes bmotion can just spark. Check this conversation I had, both NoTopic and MonicaOff are running bmotion.

 (@  NoTopic) Uh oh, it's mark.
 (+      znx) listen nt .. im tired of your shit
 (         *) znx kicks the crap out of nt
 (         *) NoTopic passes it on to james
 (+      znx) um
 (+      znx) :[
 (@MonicaOff) cheer up mak
 (@MonicaOff) *hugs*
 (+      znx) aww
 (+      znx) i love you mon
 (         *) znx hugs
 (@MonicaOff) Hehe, want to go out on a date someplace? :)
 (+      znx) sure!
 (+      znx) where would you like to go mon?
 (@MonicaOff) Amsterdam.
 (+      znx) ooo
 (         *) znx books the flights
 (+ JamesOff) sounds nice :P
 (@  NoTopic) oh categorically abyss what do you think, talking ass?
 (+      znx) your just annoyed im not taking you nt
 (         *) znx shows nt the flight tickets
 (@  NoTopic) ooooh, impressive!
 (+      znx) :P !!
 (         *) NoTopic steals the flight tickets and runs off
 (@  NoTopic) ALL MINE NOW^@~#%~£~$$~*£$$$
 (+      znx) W T F
 (         *) NoTopic sells the flight tickets on ebay
 (+      znx) NOOOOOOOOOOooooooooooooooooooo
 (         *) znx sulks at nt
 (@  NoTopic) what

Of course sometimes bmotion is just plain evil!

Tags: , ,