Wednesday, June 13, 2007

String manipulation in NT scripts

I was working on a Citrix Login script and found out most clients are not able to perform WMI queries to get session information from the server or just simple evironment variable expansion... or is it just our GPO is just too tight?

Instead of using vbscript for the string manipulation, I opted to the old school NT scripting, since the built in usrlogon script in PS4 is native to NT.

So I searched the help files and the net for old DOS commands for string manipulation as my goal for this script is to get the first 2 characters from the environment variable %CLIENTNAME%. If the machine name's first 2 characters are "UK", then a certain drive is required to be mapped.

Now, It is possible to retrieve specific characters from a string variable.

Syntax:
%variable:~num_chars_to_skip%
%variable:~num_chars_to_skip,num_chars_to_keep%

This can include negative numbers:
%variable:~num_chars_to_skip, -num_chars_to_skip%
%variable:~-num_chars_to_skip,num_chars_to_keep%

A negative number will count backwards from the end of the string. In Windows NT 4 the syntax for negative numbers was not supported.

Examples:
The variable _test is used for all the following examples:

SET _test=123456789abcdef0

::Extract only the first 5 characters

SET _result=%_test:~0,5%
ECHO %_result% =12345

::Skip 7 characters and then extract the next 5

SET _result=%_test:~7,5%
ECHO %_result% =89abc

::Skip 7 characters and then extract everything else

SET _result=%_test:~7%
ECHO %_result% =89abcdef0

::Extract only the last 7 characters

SET _result=%_test:~-7%
ECHO %_result% =abcdef0

::Extract everything BUT the last 7 characters

SET _result=%_test:~0,-7%
ECHO %_result% =123456789

::Extract between 7 from the front and 5 from the end

SET _result=%_test:~7,-5%
ECHO %_result% =89ab

::Go back 7 from the end then extract 5 towards the end

SET _result=%_test:~-7,5%
ECHO %_result% =abcde

::Extract between 7 from the end and 5 from the end

SET _result=%_test:~-7,-5%
ECHO %_result% =ab

And this is the final script:
SET _CNAME=%CLIENTNAME%
CALL SET _ORIGIN=%_CNAME:~-0,2%

IF %_ORIGIN% EQU UK (
NET USE R: \\UKFILSERVER\CITRIX$
) ELSE (
GOTO Done
)

:Done

If at first you fail, call it version 1.0

No comments: