Powershell redirect output to file

Redirection of standard and error output appending to the same log file

I need to collect the standard output and error log from several processes into one single log file.

So every output must append to this log file.

I want to call all the jobs with lines like this:

Where do I have to put the information to append?

Powershell redirect output to file. Смотреть фото Powershell redirect output to file. Смотреть картинку Powershell redirect output to file. Картинка про Powershell redirect output to file. Фото Powershell redirect output to file

4 Answers 4

In order to append to a file you’ll need to use a slightly different approach. You can still redirect an individual process’ standard error and standard output to a file, but in order to append it to a file you’ll need to do one of these things:

The first way would look like this:

The second way would look like this:

Powershell redirect output to file. Смотреть фото Powershell redirect output to file. Смотреть картинку Powershell redirect output to file. Картинка про Powershell redirect output to file. Фото Powershell redirect output to file

Powershell redirect output to file. Смотреть фото Powershell redirect output to file. Смотреть картинку Powershell redirect output to file. Картинка про Powershell redirect output to file. Фото Powershell redirect output to file

So your implementation might be:

Powershell redirect output to file. Смотреть фото Powershell redirect output to file. Смотреть картинку Powershell redirect output to file. Картинка про Powershell redirect output to file. Фото Powershell redirect output to file

Andy gave me some good pointers, but I wanted to do it in an even cleaner way. Not to mention that with the 2>&1 >> method PowerShell complained to me about the log file being accessed by another process, i.e. both stderr and stdout trying to lock the file for access, I guess. So here’s how I worked it around.

First let’s generate a nice filename, but that’s really just for being pedantic:

And here’s where the trick begins:

With start-transcript and stop-transcript you can redirect ALL output of PowerShell commands to a single file, but it doesn’t work correctly with external commands. So let’s just redirect all the output of those to the stdout of PS and let transcript do the rest.

In fact, I have no idea why the MS engineers say they haven’t fixed this yet «due to the high cost and technical complexities involved» when it can be worked around in such a simple way.

Either way, running every single command with start-process is a huge clutter IMHO, but with this method, all you gotta do is append the 2>&1 | Write-Output code to each line which runs external commands.

Источник

Out-File

Sends output to a file.

Syntax

Description

The Out-File cmdlet sends output to a file. It implicitly uses PowerShell’s formatting system to write to the file. The file receives the same display representation as the terminal. This means that the output may not be ideal for programmatic processing unless all input objects are strings. When you need to specify parameters for the output, use Out-File rather than the redirection operator ( > ). For more information about redirection, see about_Redirection.

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 does not 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 Process objects are sent down the pipeline to the Out-File cmdlet. Out-File uses the FilePath parameter 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 overwrites existing files.

The Get-Process cmdlet gets the list of processes running on the local computer. The Process objects are sent down the pipeline to the Out-File cmdlet. Out-File uses the FilePath parameter and attempts to write to a file in the current directory named Process.txt. The NoClobber parameter prevents the file from being overwritten and displays a message that the file already exists.

Example 3: Send output to a file in ASCII format

This example shows how to encode output with a specific encoding type.

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 provider drive. Use the Get-PSProvider cmdlet to view the providers on your local computer. For more information, see about_Providers.

Example 5: Set file output width for entire scope

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

The acceptable values for this parameter are as follows:

UTF-7* is no longer recommended to use. As of PowerShell 7.1, a warning is written if you specify utf7 for the Encoding parameter.

Type:Encoding
Accepted values:ASCII, BigEndianUnicode, BigEndianUTF32, 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 parameter does 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 type a command or expression that gets the objects.

Type:PSObject
Position:Named
Default value:None
Accept pipeline input:True
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 single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see about_Quoting_Rules.

Type:String
Aliases:PSPath, LP
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

NoClobber prevents an existing file from being overwritten and displays a message that the file already exists. By default, if a file exists in the specified path, Out-File overwrites the file without 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 string representations of the input objects are concatenated to form the output. No spaces or newlines are inserted 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
Type:Int32
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Inputs

Outputs

None

Out-File does not generate any output.

Notes

Input objects are automatically formatted as they would be in the terminal, but you can use a Format-* cmdlet to explicitly control the formatting of the output to the file. For example, Get-Date | Format-List | Out-File out.txt

To send a PowerShell command’s output to the Out-File cmdlet, use the pipeline. Alternatively, you can store data in a variable and use the InputObject parameter to pass data to the Out-File cmdlet.

Out-File saves data to a file but it does not produce any output objects to the pipeline.

Источник

I’m writing a script to download several repositories from GitHub. Here is the command to download a repository:

When I run this command it displays some nice progress information in the console window that I want displayed.

The problem is that I also want to be able to detect if any errors have occurred while downloading. I found this post that talks about redirecting the various streams, so I tried:

This pipes any errors from stderr to my file, but no longer displays the nice progress information in the console.

I can use the Tee-Object like so:

and I still get the nice progress output, but this pipes stdout to the file, not stderr; I’m only concerned with detecting errors.

Is there a way that I can store any errors that occur in a file or (preferably) a variable, while also still having the progress information piped to the console window? I have a feeling that the answer might lie in redirecting various streams into other streams as discusses in this post, but I’m not really sure.

I’m not sure if the git.exe is different than your typical executable, but I’ve done some more testing and here is what I’ve found:

$output always contains the text «Cloning into ‘[localRepoDirectory]’. «, whether the command completed successfully or produced an error. Also, the progress information is still written to the console when doing this. This leads me to think that the progress information is not written via stdout, but by some other stream?

The error message is written to the file, so that makes me think that it does write to stderr. So now I’m confused.

So with Byron’s help I’ve tried a couple of more solutions using a new process, but still can’t get what I want. When using a new process I never get the nice progress written to the console.

The three new methods that I’ve tried both use this bit of code in common:

Even though this looks like it would write the output while the process is running, it doesn’t write anything until after the process exits.

This does output data while the process is working which is good, but it still doesn’t display the nice progress information 🙁

Источник

Powershell redirect output to file. Смотреть фото Powershell redirect output to file. Смотреть картинку Powershell redirect output to file. Картинка про Powershell redirect output to file. Фото Powershell redirect output to file

Powershell redirect output to file. Смотреть фото Powershell redirect output to file. Смотреть картинку Powershell redirect output to file. Картинка про Powershell redirect output to file. Фото Powershell redirect output to file

A common task when working with the command prompt is to write the output of commands to a file. As with cmd.exe, PowerShell supports the redirection of output but has more options. PowerShell also comes with a couple of cmdlets that support further features.

Whether you want to permanently save the output of complex calculations or log details of a script, you usually need a procedure to redirect the console output to a file. You can accomplish this job using redirect operators that work in a way that is similar to the conventional command prompt (at least as long as the task is relatively simple). If you just want to redirect the regular and successful output of a command to a file, the redirect operators “>” and “>>” are all you need:

If process.out already exists, PowerShell would overwrite the file’s previous contents, in contrast to the next example where the redirected output will be appended to the file:

Redirecting five output streams ^

In addition to the actual results, most cmdlets and scripts return further information such as errors, warnings, and status messages. If a script is supposed to return data through the appropriate streams, its programmer has to follow a few rules. In particular, this means that he has to use the suitable cmdlets to write the information to the right stream. For instance, Write-Debug, Write-Verbose, and Write-Warning are cmdlets that are typically used to deliver information about the command processing.

Whereas cmd.exe is only able to redirect error messages to an alternative device, PowerShell supports five different output types (streams):

To redirect only a particular output type, you have to add the stream number to the redirect operator:

Like usual, this command would display a list of the running processes, whereas all debug information would be written to debug.out. If you want to append the file with debug data, you would use 5>> instead.

Redirecting to different streams ^

If you want to redirect to another stream instead of to a file, the redirect operator expects the following syntax:

“m” stands for the stream that you want to redirect, and “n” represents the target stream. For example, the following command redirects debug information to the regular output stream of Get-Process:

If you want to redirect not only a single stream but all streams, PowerShell allows you to work with wildcards:

This command redirects the contents of all five streams to process.out. The same command can be used with “>>” in order to append the data to the file. Redirecting all streams to a single stream is just as admissible:

Splitting output with tee ^

If you redirect the output of a command to a file, the data is no longer available in the pipeline to process it with another cmdlet. Sticking with the above example, if you want to write the entire output of Get-Process to a file and only display the attributes ID, Name, and CPU, the following command wouldn’t work:

In this case, nothing would arrive at Select and, accordingly, its output would be empty. The remedy for this is the Tee-Object cmdlet, which splits the output like its UNIX counterpart. This enables you to store the output in a file and process it on the console, where you can pass it through the pipeline to another cmdlet:

Powershell redirect output to file. Смотреть фото Powershell redirect output to file. Смотреть картинку Powershell redirect output to file. Картинка про Powershell redirect output to file. Фото Powershell redirect output to file

Splitting output with Tee-Object

Using additional options with Out-File ^

In most cases, redirecting via “>” and “>>” proves to be sufficient to write the desired information to a file. However, these operators only allow you to overwrite or append files, and they don’t offer any options. In contrast, the Out-File cmdlet comes with a variety of additional features such as the ability to use another character set, work with an alternative line length, or store data in write-protected files. It accepts input through the pipeline or the -InputObject parameter:

This command writes the output of Get-Process to the file temp.out, uses the ASCII character set, and sets the line length to 256 characters to ensure that no information is lost in the table.

Because of the -Force parameter, Out-File would overwrite an existing file without warning even if the read-only attribute is set. If you want to append the output to a file, you have to use the -NoClobber parameter.

Alternatively, you can pass the output of Get-Process to Out-File through the pipeline:

Writing to multiple files ^

Because the redirect operators and Out-File don’t accept wildcards for file names, you can only use them to write to one file. This is usually sufficient when you only want to save the output of a command.

However, if you want to update the contents of multiple files, the cmdlets Set-Content and Add-Content are suitable for the task. The first one replaces the contents of the specified file, whereas the latter appends the data to the file.

Set-Content cannot modify existing text in the file; it creates new files with the contents that you pass through the -Value parameter. If you only want to replace distinct strings, you have to first read all files with Get-Content, process the contents with simple substitution patterns or regular expressions, and then write back the result with Set-Content.

However, it is easier if you only want to append information to existing files. In this case, you can pass one or more file names, separated by commas, through the parameter -Path. It is also possible to target several files with the help of wildcards. The parameter -Value takes the output of the corresponding cmdlet as input:

Источник

Cannot redirect EXE output to file

When trying to redirect all output or just stdout to a file, the program stops giving output. For example

I did not write the program but what I know is that it was written in C++. Is there any trick to get the output into a file? I tried running in python and writing output to a file, running in python without fetching the output and redirecting, running from another powershell, and lots of other combinations but they don’t seem to be working. Also, when running from Git Bash, I get no output at all.

I was thinking about some checks on the descriptors but I’m not sure since I don’t have the source code, only the asm code

1 Answer 1

It looks like Program.exe is actually generating an error, and not output, first commenter is trying to get you to see that, but not really explaining that part.

(NOTE: You aren’t actually using any powershell besides an implied «Invoke-Expression»)I think you might be dealing with STDERR vs. STDOUT, when I invoke reg.exe in that fashion from powershell I get no output to the text file. This is because the text I was seeing was an error message ( Contents of STDERR ) from reg.exe, not the output ( contents of STDOUT ) from the command. When I passed proper parameters to it ( reg query HKLM\Software\Microsoft > C:\Users\foo\Documents\foo.txt) it wrote the Contents of STDOUT to the text file instead of the screen.

Here is an article that explains it better than I just did:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *