5

I want to output information to a log file as such

01/08/2013 14:30 - Dynamic-Machine-Name    - Message starts
02/08/2013 07:12 - DynamicMachineName      - Log entry
02/08/2013 07:14 - Dynamic-PC-Name         - Information here
02/08/2013 08:01 - PC-Name                 - Execution continues
03/08/2013 09:00 - Dynamic-Name            - Message starts
03/08/2013 15:29 - Dynamic-Machine-Name    - Log information
03/08/2013 15:30 - Random-Machine-Name     - Message etc.

But in order to align the log message on the right hand side, I need to calculate the length of the machine name, which I have done, and deduct it from the max length to get a number spaces.

What I can't work out is how to produce a string that contains 'x' number of spaces, or append those 'x' numbers of spaces to the end of the machine name?

1 Answers1

9

You don't even have to compute the length of your machine name. You just need to know how many characters you want before your message.

Let's say you want your message to start at position 44. You already have your timestamp and your machine name strings. The timestamp is constant width, but the machine name width varies.

Create a variable that has your timestamp, followed by your machine name, followed by 43 spaces. Then take a substring of the result, preserving only the first 43 characters, and append your message.

@echo off
setlocal
set "spaces=                                           "
set "timestamp=01/08/2013 14:30"
set "machineName=PC-Name"
set "message=Message goes here"
set "line=%timestamp% - %machineName%%spaces%"
set "line=%line:~0,43%- %message%
echo %line%

-- OUTPUT --

01/08/2013 14:30 - PC-Name                 - Message goes here

For more information on variable substring operations (and also search and replace), type HELP SET or SET /? from a command prompt.

dbenham
  • 11,794