0

Assume the following directory tree:

NATIVES
    \VOL001
        file1.txt
        file2.txt
    \VOL002
        file3.txt
    \OTHERDIR
        file4.txt

I am trying to delete all folder VOL* folders and their children (only files for now) and log the results. Removing the folders and files is easy:

# Remove textfiles
Remove-Item -path C:\Sandbox\NATIVES\VOL* -Recurse

But I am unable to log this as-is. I am using a custom log Function:

Function Log-Write 
{
    Param([string]$logstring)
    Add-Content "log.txt" -value $logstring 
}

How can I use it to fill log.txt with every file and folder that has been deleted? So for instance:

Delete file C:\Sandbox\NATIVES\VOL001\file1.txt
Delete file C:\Sandbox\NATIVES\VOL001\file2.txt
Delete dir C:\Sandbox\NATIVES\VOL001\
Delete file C:\Sandbox\NATIVES\VOL002\file3.txt
...

I could write a bigger loop, but I am trying to keep the code as concise as possible (it's more of a learning thing).

Can anyone send me in the right direction?

Pr0no
  • 3,910
  • 21
  • 74
  • 121

1 Answers1

1

Use foreach (aka %) instead of recursive Remove-Item. It is possible to redirect Remove-Item's -Verbose output to a file, but that requires very cryptic syntax unless you are on Powerhell 3.0 or higher.

The foreach way looks like so,

$files = @(gci -recurse c:\path\to\files)
$files | %  {
    rm $_.FullName
    add-content c:\myLogFile.txt "Delete file $_.FullName"
}
Community
  • 1
  • 1
vonPryz
  • 22,996
  • 7
  • 54
  • 65