I did the same thing but in a different way as I prefer not to use scripts where I can. (I like to keep things simple!!!)
I added a "Set Task Sequence Variable" step to my task sequence for OSDComputerName with the value of %_SMSTSMachineName%, this will look up the name of the computer in SCCM and use this as the computer name for the new image.
Now if you have a unknown computer and are prompted to enter a value for OSDComputerName at the start of the task sequence, you need to stop the "Set Task Sequence Variable" step from overwritting the current value for OSDComputerName. To do this I changed the options for the "Set Task Sequence Variable" step in the task sequence to only run if this "Task Sequence Variable" does not exist.
Therefore I can use the same Task Sequence for known and unknown computers in SCCM, I just need to deploy the Task Sequences to the relevant collections.
I hope this helps someone.