2020. 12. 7. 08:39ㆍ카테고리 없음
- Cmd Append Output To File Bash
- Windows Command Append To File
- Windows Command Prompt Append Output To File
- Dos Command Output To File
I'm trying to generate a log file (text file) that is appended to every time I run a batch file. It will enable me to see a history of my network problems. I have two questions: 1) How can I get the date and time to append on one line of the text file. I am currently using date /t output.txt & time /t output.txt. To close Notepad, select Exit from the File menu. To close the command window, type exit at the command prompt and press Enter. NOTE: If you use the same filename a second time, that file will be overwritten and any output it previously contained will be lost. To preserve your previous output, use a different filename or you can append the output to the end of an existing file. The type command does echo all contents of file1 and will append it to file2 – Top-Master Nov 28 '18 at 5:51.
How can I run a command-line application in the Windows command prompt and have the output both displayed and redirected to a file at the same time?
If, for example, I were to run the command dir > test.txt
, this would redirect output to a file called test.txt
without displaying the results.
How could I write a command to display the output and redirect output to a file in the Windows command prompt, similar to the tee
command on Unix?
30 Answers
To expand on davor's answer, you can use PowerShell like this:
If you're trying to redirect the output of an exe in the current directory, you need to use .
on the filename, eg:
I was able to find a solution/workaround of redirecting output to a file and then to the console:
where dir is the command which output needs to be redirected, a.txt a file where to store output.
Christopher PainterThere's a Win32 port of the Unix tee
command, that does exactly that. See http://unxutils.sourceforge.net/ or http://getgnuwin32.sourceforge.net/
Check this out: wintee
No need for cygwin.
I did encounter and report some issues though.
Also you might check unxutils because it contains tee (and no need for cygwin), but beware that output EOL's are UNIX-like here.
Last, but not least, is if you have PowerShell, you could try Tee-Object. Type get-help tee-object
in PowerShell console for more info.
@tori3852
I found that Manual 270962 for free.
didn't work (first few lines of dir listing only - suspect some sort of process forking and the second part, the 'type' command terminated before the dire listing had completed? ),so instead I used:
which did - sequential commands, one completes before the second starts.
Brian WebsterA simple C# console application would do the trick:
To use this you just pipe the source command into the program and provide the path of any files you want to duplicate the output to. For example:
Will display the results of dir as well as store the results in both files1.txt and files2.txt.
Note that there isn't much (anything!) in the way of error handling above, and supporting multiple files may not actually be required.
T.S.Unfortunately there is no such thing.
Windows console applications only have a single output handle. (Well, there are two STDOUT
, STDERR
but it doesn't matter here) The >
redirects the output normally written to the console handle to a file handle.
If you want to have some kind of multiplexing you have to use an external application which you can divert the output to. This application then can write to a file and to the console again.
Daniel RikowskiDaniel RikowskiThis works, though it's a bit ugly:
It's a little more flexible than some of the other solutions, in that it works statement-by-statement so you can use it to append as well. I use this quite a bit in batch files to log and display messages:
Yes, you could just repeat the ECHO statement (once for the screen and the second time redirecting to the logfile), but that looks just as bad and is a bit of a maintenance issue. At least this way you don't have to make changes to messages in two places.
Note that _ is just a short filename, so you'll need to make sure to delete it at the end of your batch file (if you're using a batch file).
mtee is a small utility which works very well for this purpose. It's free, source is open, and it Just Works.
You can find it at http://www.commandline.co.uk.
Used in a batch file to display output AND create a log file simultaneously, the syntax looks like this:
Where /+ means to append output.
This assumes that you have copied mtee into a folder which is in the PATH, of course.
I agree with Brian Rasmussen, the unxutils port is the easiest way to do this. In the Batch Files section of his Scripting Pages Rob van der Woude provides a wealth of information on the use MS-DOS and CMD commands. I thought he might have a native solution to your problem and after digging around there I found TEE.BAT, which appears to be just that, an MS-DOS batch language implementation of tee. It is a pretty complex-looking batch file and my inclination would still be to use the unxutils port.
Steve CraneSteve CraneIf you have cygwin in your windows environment path you can use:
jkdbajkdbaI’d like to expand a bit on Saxon Druce’s excellent answer.
As stated, you can redirect the output of an executable in the current directory like so:
However, this only logs stdout
to test.txt
. It doesn’t also log stderr
.
The obvious solution would be to use something like this:
However, this won’t work for all something.exe
s. Some something.exe
s will interpret the 2>&1
as an argument and fail. The correct solution is to instead only have apostrophes around the something.exe
and its switches and arguments, like so:
dir 1>a.txt 2>&1 | type a.txt
This will help to redirect both STDOUT and STDERR
rashokrashokI was also looking for the same solution, after a little try, I was successfully able to achieve that in Command Prompt. Here is my solution :
It even captures any PAUSE command as well.
Here's a sample of what I've used based on one of the other answers
I know this is a very old topic, but in previous answers there is not a full implementation of a real time Tee written in Batch. My solution below is a Batch-JScript hybrid script that use the JScript section just to get the output from the piped command, but the processing of the data is done in the Batch section. This approach have the advantage that any Batch programmer may modify this program to fit specific needs. This program also correctly process the output of CLS command produced by other Batch files, that is, it clear the screen when CLS command output is detected.
AaciniAacinisend output to console, append to console log, delete output from current command
mrtThis will create a log file with the current datetime and you can the console lines during the process
VladimirThis is a variation on a previous answer by MTS, however it adds some functionality that might be useful to others. Here is the method that I used:
- A command is set as a variable, that can be used later throughout the code, to output to the command window and append to a log file, using
set _Temp_Msg_Cmd=
- the command has escaped redirection using the carrot
^
character so that the commands are not evaluated initially
- the command has escaped redirection using the carrot
- A temporary file is created with a filename similar to the batch file being run called
%~n0_temp.txt
that uses command line parameter extension syntax%~n0
to get the name of the batch file. - The output is appended to a separate log file
%~n0_log.txt
Here is the sequence of commands:
- The output and error messages are sent to the temporary file
^> %~n0_temp.txt 2^>^&1
- The content of the temporary file is then both:
- appended to the logfile
^& type %~n0_temp.txt ^>^> %~n0_log.txt
- output to the command window
^& type %~n0_temp.txt
- appended to the logfile
- The temporary file with the message is deleted
^& del /Q /F %~n0_temp.txt
Here is the example:
set _Temp_Msg_Cmd= ^> %~n0_temp.txt 2^>^&1 ^& type %~n0_temp.txt ^>^> %~n0_log.txt ^& type %~n0_temp.txt ^& del /Q /F %~n0_temp.txt
This way then the command can simply be appended after later commands in a batch file that looks a lot cleaner:
echo test message %_Temp_Msg_Cmd%
This can be added to the end of other commands as well. As far as I can tell it will work when messages have multiple lines. For example the following command outputs two lines if there is an error message:
net use M: /D /Y %_Temp_Msg_Cmd%
I use a batch subroutine with a 'for' statement to get the command output one line at a time and both write that line to a file and output it to the console.
If you're on the CLI, why not use a FOR loop to 'DO' whatever you want:
Great resource on Windows CMD for loops: https://ss64.com/nt/for_cmd.htmlThe key here is setting the delimeters (delims), that would break up each line of output, to nothing. This way it won't break on the default of white-space. The %a is an arbitrary letter, but it is used in the 'do' section to, well.. do something with the characters that were parsed at each line. In this case we can use the ampersands (&&) to execute the 2nd echo command to create-or-append (>>) to a file of our choosing. Safer to keep this order of DO commands in case there's an issue writing the file, we'll at least get the echo to the console first. The at sign (@) in front of the first echo suppresses the console from showing the echo-command itself, and instead just displays the result of the command which is to display the characters in %a. Otherwise you'd see:
https://comlilutcer.tistory.com/1. echo Volume in drive [x] is Windows
Volume in drive [x] is Windows
UPDATE: /F skips blank lines and only fix is to pre-filter the output adding a character to every line (maybe with line-numbers via the command find). Solving this in CLI isn't quick or pretty. Also, I didn't include STDERR, so here's capturing errors as well:
The carets (^) are there to escape the symbols after them, because the command is a string that's being interpreted, as opposed to say, entering it directly on the command-line.
Just like unix.
dir | tee a.txt
Does work On windows XP, it requires mksnt
installed.
Cmd Append Output To File Bash
It displays on the prompt as well as appends to the file.
CoreyFollowing helps if you want something really seen on the screen - even if the batch file was redirected to a file. The device CON maybe used also if redirected to a file
Example:
Also see good redirection description: http://www.p-dd.com/chapter7-page14.html
How do I display and redirect output to a file. Suppose if I use dos command, dir > test.txt ,this command will redirect output to file test.txt without displaying the results. how to write a command to display the output and redirect output to a file using DOS i.e., windows command prompt, not in UNIX/LINUX.
You may find these commands in biterscripting ( http://www.biterscripting.com ) useful.
This works in real time but is also kind a ugly and the performance is slow. Not well tested either:
djangofandjangofanAn alternative is to tee stdout to stderr within your program:
in java:
Then, in your dos batchfile: java program > log.txt
The stdout will go to the logfile and the stderr (same data) will show on the console.
The CoordinatorThe CoordinatorI install perl on most of my machines so an answer using perl: tee.pl
dir | perl tee.plor dir | perl tee.pl dir.bat
crude and untested.
Another variation is to split the pipe, and then re-direct the output as you like.
Proteus 8.4 download for computer. Save the above to a .bat file. It splits text output on filestream 1 to filestream 3 also, which you can redirect as needed. In my examples below, I called the above script splitPipe.bat ..
Syntax
Description
The Out-File
cmdlet sends output to a file. When you need to specify parameters for the output useOut-File
rather than the redirection operator (>
).
Examples
Example 1: Send output and create a file
This example shows how to send a list of the local computer's processes to a file. If the file doesnot exist, Out-File
creates the file in the specified path.
The Get-Process
cmdlet gets the list of processes running on the local computer. The Processobjects are sent down the pipeline to the Out-File
cmdlet. Out-File
uses the FilePathparameter and creates a file in the current directory named Process.txt. The Get-Content
command gets content from the file and displays it in the PowerShell console.
Example 2: Prevent an existing file from being overwritten
This example prevents an existing file from being overwritten. By default, Out-File
overwritesexisting files.
The Get-Process
cmdlet gets the list of processes running on the local computer. The Processobjects are sent down the pipeline to the Out-File
cmdlet. Out-File
uses the FilePathparameter and attempts to write to a file in the current directory named Process.txt. TheNoClobber parameter prevents the file from being overwritten and displays a message that thefile already exists.
Example 3: Send output to a file in ASCII format
This example shows how to encode output with a specific encoding type.
The Get-Process
cmdlet gets the list of processes running on the local computer. The Processobjects are stored in the variable, $Procs
. Out-File
uses the FilePath parameter and createsa file in the current directory named Process.txt. The InputObject parameter passes theprocess objects in $Procs
to the file Process.txt. The Encoding parameter converts theoutput to ASCII format. The Width parameter limits each line in the file to 50 characters sosome data might be truncated.
Example 4: Use a provider and send output to a file
This example shows how to use the Out-File
cmdlet when you are not in a FileSystem providerdrive. Use the Get-PSProvider
cmdlet to view the providers on your local computer. For moreinformation, see about_Providers.
The Set-Location
command uses the Path parameter to set the current location to the registryprovider Alias:
. The Get-Location
cmdlet displays the complete path for Alias:
.Get-ChildItem
sends objects down the pipeline to the Out-File
cmdlet. Out-File
uses theFilePath parameter to specify the complete path and filename for the output,C:TestDirAliasNames.txt. The Get-Content
cmdlet uses the Path parameter and displays thefile's content in the PowerShell console.
Parameters
Adds the output to the end of an existing file.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the type of encoding for the target file. The default value is UTF8NoBOM.
The acceptable values for this parameter are as follows:
- ASCII: Uses the encoding for the ASCII (7-bit) character set.
- BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order.
- OEM: Uses the default encoding for MS-DOS and console programs.
- Unicode: Encodes in UTF-16 format using the little-endian byte order.
- UTF7: Encodes in UTF-7 format.
- UTF8: Encodes in UTF-8 format.
- UTF8BOM: Encodes in UTF-8 format with Byte Order Mark (BOM)
- UTF8NoBOM: Encodes in UTF-8 format without Byte Order Mark (BOM)
- UTF32: Encodes in UTF-32 format.
Beginning with PowerShell 6.2, the Encoding parameter also allows numeric IDs of registered codepages (like -Encoding 1251
) or string names of registered code pages (like-Encoding 'windows-1251'
). For more information, see the .NET documentation forEncoding.CodePage.
Type: | Encoding |
Accepted values: | ASCII, BigEndianUnicode, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 |
Position: | 1 |
Default value: | UTF8NoBOM |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the path to the output file.
Type: | String |
Aliases: | Path |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Overrides the read-only attribute and overwrites an existing read-only file. The Force parameterdoes not override security restrictions.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the objects to be written to the file. Enter a variable that contains the objects or typea command or expression that gets the objects.
Type: | PSObject |
Position: | Named |
Default value: | None |
Accept pipeline input: | True (ByValue) |
Accept wildcard characters: | False |
Specifies the path to the output file. The LiteralPath parameter is used exactly as it is typed.Wildcard characters are not accepted. If the path includes escape characters, enclose it in singlequotation marks. Single quotation marks tell PowerShell not to interpret any characters as escapesequences. For more information, see about_Quoting_Rules.
Type: | String |
Aliases: | PSPath |
Position: | Named |
Default value: | None |
Accept pipeline input: | True (ByPropertyName) |
Accept wildcard characters: | False |
NoClobber prevents an existing file from being overwritten and displays a message that the filealready exists. By default, if a file exists in the specified path, Out-File
overwrites the filewithout warning.
Type: | SwitchParameter |
Aliases: | NoOverwrite |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies that the content written to the file does not end with a newline character. The stringrepresentations of the input objects are concatenated to form the output. No spaces or newlines areinserted between the output strings. No newline is added after the last output string.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the number of characters in each line of output. Any additional characters are truncated,not wrapped. If this parameter is not used, the width is determined by the characteristics of thehost. The default for the PowerShell console is 80 characters.
Type: | Int |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
Windows Command Append To File
System.Management.Automation.PSObject
You can pipe any object to Out-File
.
Windows Command Prompt Append Output To File
Outputs
None
Out-File
does not generate any output.
Notes
The Out
cmdlets do not format objects; they just render them and send them to the specifieddisplay destination. If you send an unformatted object to an Out
cmdlet, the cmdlet sends it to aformatting cmdlet before rendering it.
To send a PowerShell command's output to the Out-File
cmdlet, use the pipeline. You can store datain a variable and use the InputObject parameter to pass data to the Out-File
cmdlet.
Dos Command Output To File
Out-File
sends data but it does not produce any output objects. If you pipe the output ofOut-File
to Get-Member
, the Get-Member
cmdlet reports that no objects were specified.