0

I am trying to append the string "KB" to a file after having written the output from a windows command:

C:\Users\Administrator> wmic OS get FreePhysicalMemory > C:\temp\temp.txt
C:\Users\Administrator> echo KB >> C:\temp\temp.txt

but in notepad I see some strange oriental characters instead of KB

FreePhysicalMemory  
1441960             
䉋ഠ∊䉋•਍਍ 

I expect to see the text "FreePhysicalMemory 1441960 KB". If possible I would like to have KB after the number, not on a new line. Once I do this I will use the file with another program (InterSystems Caché) and place it in another html file, but that should not matter.

aless80
  • 3,122
  • 3
  • 34
  • 53

1 Answers1

2

wmic writes the output as UTF-16LE (with a BOM), when you append ASCII characters to this it tends to look Chinese.

You can force cmd.exe to write UTF-16 as well with the /U switch:

wmic OS get FreePhysicalMemory > out.txt
cmd /U /C echo kb ^>^> out.txt

To write it as a single line is a lot more complicated than it should be.

FOR /F "delims=" %A IN ('wmic OS get FreePhysicalMemory /Format:list ^| more') do @FOR /F "tokens=1,* delims==" %B in ("%A") do @echo.%B %C KB > out.txt

Piping to more converts from UTF-16 and the second for loop removes empty lines.

Anders
  • 97,548
  • 12
  • 110
  • 164
  • You don't need to pipe to more.com. CMD's `for` loop runs wmic.exe with its stdout redirected to a pipe. That's all you need to make wmic.exe output OEM encoded text. In general, watch out for mojibake here because CMD decodes the output lines using the current console codepage, and otherwise uses ANSI when run without a console (i.e. detached). The console defaults to OEM, but it may have been changed via chcp.com. – Eryk Sun Aug 28 '17 at 21:37
  • The `for` loop works around a bug in wmic.exe. The C runtime low I/O file descriptor is opened in text mode, which translates LF => CRLF. wmic.exe writes lines that already end in CRLF, so the C runtime ends up writing lines that end with CRCRLF. The first `for` loop splits lines on the final CRLF, but leaves a trailing CR on each line. – Eryk Sun Aug 28 '17 at 21:41
  • In general having wmic.exe encode its output as OEM text may incorrectly encode Unicode strings such as filenames, registry text, and user names. It's better to have it write UTF-16 to a file if that's potentially a problem. – Eryk Sun Aug 28 '17 at 21:51
  • @eryksun: That FOR on NT uses a pipe is an implementation detail IMHO. Win9x/command.com used temp files for pipe operations IIRC. – Anders Aug 28 '17 at 22:18
  • ok, I'm talking about NT CMD, not DOS COMMAND. I think it's safe to assume a Windows question is in reference to at least Windows XP, and likely Windows 7+. – Eryk Sun Aug 28 '17 at 23:08