- 1 year ago
ForEach-Object Delete & Out-File
In PowerShell, you can use the ForEach-Object
cmdlet along with the Remove-Item
cmdlet and the Out-File
cmdlet to delete files and write the deleted file names to a text file. Here's an example:
powershellGet-ChildItem -Path "C:\Path\To\Files" | ForEach-Object {
$fileName = $_.Name
Remove-Item -Path $_.FullName -Force
$fileName | Out-File -Append "C:\Path\To\DeletedFiles.txt"
}
In this example:
Get-ChildItem
is used to retrieve the files in the specified directory ("C:\Path\To\Files").The output of
Get-ChildItem
is piped (|
) toForEach-Object
, which iterates over each file object.Within the
ForEach-Object
block, the current file's name ($_.Name
) is stored in the$fileName
variable.Remove-Item
is used to delete the current file ($_.FullName
). The-Force
parameter is added to forcefully remove the file without prompting for confirmation.The file name is appended to a text file ("C:\Path\To\DeletedFiles.txt") using
Out-File
with the-Append
parameter.
By running this PowerShell script, files in the specified directory will be deleted, and the names of the deleted files will be recorded in the "DeletedFiles.txt" text file. Adjust the paths and file filters as needed for your specific scenario.
Make sure to use caution when deleting files, especially when using the -Force
parameter, as it will permanently remove files without any confirmation prompt. Double-check your paths and ensure that you have appropriate permissions to delete the files in question.