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?

  • Stupid me was thinking BASH, sorry about that... I don't use Windows much anymore to have a batch/dos/powershell equivalent. I am sure someone will be along shortly. – nerdwaller Aug 8 '13 at 17:13
  • That's okay, you wouldn't happen to know the DOS equivalent would you? – Ghandi Manning Aug 8 '13 at 17:14
  • 1
    Are you looking for DOS specifically, or the Windows cmd.exe language? – grawity Aug 8 '13 at 17:15
  • I'm not certain of the difference, basically running myfile.bat so whatever that runs, could very well be cmd.exe language – Ghandi Manning Aug 8 '13 at 17:16
7

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.