Share via

Simple script not working when saving log

RAN55 181 Reputation points
2022-04-13T11:11:08.31+00:00

HI,

I have this simple command and works:

Get-ChildItem -Path "C:\test" -Recurse -Force | Where-Object { !$.PSIsContainer -and $.CreationTime -lt $limit } | Remove-Item -Force

But if i save to log fails:

Get-ChildItem -Path "C:\test" -Recurse -Force | Where-Object { !$.PSIsContainer -and $.CreationTime -lt $limit } | Remove-Item -Force | out-file "C:\log.txt" -Append

What its wrong?

Thanks

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

4 answers

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2022-04-13T15:18:41.63+00:00

    The Remove-Item doesn't normally return any output. Please read the help file for that cmdlet:

    Outputs
    None

    This cmdlet does not return any output.

    There's no need to use the -Verbose switch. If you want to capture any errors, just redirect stream #2 (not 4): 2>&1

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. RAN55 181 Reputation points
    2022-04-13T12:43:04.387+00:00

    No, the log is not empty, the execution of script failed and no log file was created.

    I have a solution:

    -Verbose 4>&1 | out-file $logfile -Append

    With verbose option its works.

    Thanks !

    Was this answer helpful?

    1 person found this answer helpful.

  3. Olaf Helper 47,621 Reputation points
    2022-04-13T11:38:13.547+00:00

    "C: \log.txt" -Append

    You try to save the log file directly on the root of drive C:, that requieres always admin permissions; have you started PS as admin?
    It's not a good idea to store files on root, better save it to your user profile, e.g. on Desktop.

    Was this answer helpful?


  4. Martin Meiner Tästensen 461 Reputation points
    2022-04-13T11:28:50.283+00:00

    Not sure that would work in a oneliner like that.

    You could use a variable like this.

    $all = Get-ChildItem -Path "C:\test" -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit} 
    $all | out-file "C:\log.txt" -Append
    $all | Remove-Item -Force 
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.