Search code examples
powershelllogfileverbose

PowerShell Verbose-Parameter


I have a few questions about the verbose-parameter. Example script:

try {
    New-Item -Path "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose
}
catch {
    Write-Host $Error[0]
}

Output:

VERBOSE: Execute the "Create file" operation for the target "Target: C:\Test.txt".
Access to the path "C: \ Test.txt" was denied.

How do I save the verbose message in a variable?

Is it possible to edit the verbose message automatically generated by PowerShell before saving it in a log file (add date and time)? Example script (not working):

try {
    New-Item -Path "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose *> $LogFile
}
catch {
    Write-Host $Error[0]
}

Are there better suggestions to write a "success" log file than with the parameter verbose and without having to write it manually?

Thank you!


Solution

  • You can assign the verbose output to a variable if you merge the Verbose stream into standard output stream (4>&1):

    $output = New-Item "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose 4>&1
    

    Since New-Item also returns the newly created file, you'll want to split the output into verbose vs normal again:

    $verboseOutput,$normalOutput = $output.Where({$_ -is [System.Management.Automation.VerboseRecord]}, 'Split')
    

    And now you can prepend timestamps to the records in $verboseOutput before writing them to disk