You can't modify the output of Remove-Item when run with -WhatIf but you could wrap your pipeline in a function that supports -WhatIf and provides its own customized -WhatIf output:
function Test-Something {
[CmdletBinding(SupportsShouldProcess)] # This enables -WhatIf processing
param (
[string] $path,
[datetime] $limit,
[string] $ignore
)
Get-ChildItem $path -Recurse |
Where-Object { $_.LastWriteTime -lt $limit } |
Select-Object -ExpandProperty FullName |
Select-String -SimpleMatch -Pattern $ignore -NotMatch |
Select-Object -ExpandProperty Line |
Get-ChildItem -Recurse | ForEach-Object {
# If -WhatIf is passed, output the message and skip the deletion.
# Else enter the if-block and delete the file.
if( $PSCmdlet.ShouldProcess(
"Performing the operation `"Remove File`" on target `"$_`" (LastWriteTime: $($_.LastWriteTime))",
"Are you sure you want to delete file `"$_`" ?",
"Confirm" ) ) {
Remove-Item $_
}
}
}
Note that I didn't have to define the -WhatIf parameter within the function because it is added automatically by specifying SupportsShouldProcess. Now you can pass -WhatIf to your function to do a dry run:
Test-Something $del30 $limit $ignore -WhatIf
Sample output:
What if: Performing the operation "Remove File" on target "C:\test\file1.txt" (LastWriteTime: 12/30/2020 19:47:10)
What if: Performing the operation "Remove File" on target "C:\test\file2.txt" (LastWriteTime: 01/12/2021 00:59:59)
I've used the $PSCmdlet.ShouldProcess overload that takes three arguments to provide a detailed -WhatIf message. The other two arguments provide a message and a headline for the related -Confirm argument, which is also supported by the function:
Test-Something $del30 $limit $ignore -Confirm
Now PowerShell will ask before deletion:
Confirm
Are you sure you want to delete file "C:\test\file1.txt" ?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Yes"):
Another cool feature you get for free is the verbose output. When you call the function with -Verbose the message supplied to $PSCmdlet.ShouldProcess() will be used as the verbose output:
Test-Something $del30 $limit $ignore -Verbose
Output:
VERBOSE: Performing the operation "Remove File" on target "C:\test\file1.txt" (LastWriteTime: 12/30/2020 19:47:10)
VERBOSE: Performing the operation "Remove File" on target "C:\test\file2.txt" (LastWriteTime: 01/12/2021 00:59:59)
Further reading: Everything you wanted to know about ShouldProcess