user6705306
user6705306

Reputation: 137

Powershell V2 - Logging remove-item

I've seen a few answers to similar problems however I cannot get any of them to work. Probably as I'm using V2 of powershell and cannot redirect streams. My question is simple, I wish to log the verbose stream of remove-item cmdlet in the following script:

$CSVList = (Get-Content "C:\Users\Leeds TX 11\Desktop\Test folder\Watchfolder\DAZN Production Numbers - purgelist.csv" | select -Skip 1) -split ','| Where {$_}

$Netappdirectory = "C:\Users\Leeds TX 11\Desktop\Test folder\NetApp"
$Logfile = "C:\Users\Leeds TX 11\Desktop\Test folder\logfile.txt"

Get-ChildItem $Netappdirectory |
  Where-Object {$CSVList -contains $_.BaseName} |
  Remove-Item -Verbose

Upvotes: 0

Views: 1635

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200393

PowerShell v2 allows only redirection of the Success (STDOUT) and Error (STDERR) output streams. Redirection for other streams is not available prior to PowerShell v3. Also, Remove-Item doesn't have a parameter for defining a variable for verbose (or debug) output, so you can't capture that output in a variable like you can with warning and error output.

Your best option if you can't upgrade to PowerShell v3 or newer is probably creating a transcript of the operation:

Start-Transcript $Logfile -Append
Get-ChildItem $Netappdirectory | ... | Remove-Item -Verbose
Stop-Transcript

Otherwise you would need to run the operation in a separate PowerShell process. Additional streams of external processes are mangled into the Success and Error output streams (STDOUT, STDERR) when the output is returned to the parent process.

powershell.exe -Command "&{Get-ChildItem $Netappdirectory | ... | Remove-Item -Verbose}" >> $Logfile

That's a pretty ugly approach, though, so I wouldn't recommend it.


Side note: Even PowerShell v2 has an Import-Csv cmdlet, so I fail to see why you would want to emulate it via Get-Content and -split.

Upvotes: 1

Related Questions