I am trying to delete files using PowerShell script and taking files in put details from CSV file.
CSV File-
Below is PowerShell code.
$files = Get-Content "C:\DeleteFiles\FilesPresent1.csv"
foreach ($file in $files) {
Remove-Item -Path $file.ServerRelativeUrl.Trim() -Force
}
Write-Host -foregroundcolor yellow "Delete action complete"
But still i am not able achieve this, can any one suggest me what exactly i am doing wrong here, Guide me with right direction.
>Solution :
Your code as you have it right now would work by only changing Get-Content (meant to read plain text unstructured data) to Import-Csv (meant for reading Csvs as its name implies). For testing if the paths exist you can use Test-Path:
Import-Csv "C:\DeleteFiles\FilesPresent1.csv" | ForEach-Object {
Write-Host "Checking on '$($_.ServerRelativeUrl)'..."
# Check if the file exists
if (Test-Path $_.ServerRelativeUrl) {
# If it does, delete it
Remove-Item -LiteralPath $_.ServerRelativeUrl.Trim() -Force
Write-Host "Deleted: '$($_.ServerRelativeUrl)'..."
# And go to the next file
return
}
# If it doesn't exist
Write-Host "'$($_.ServerRelativeUrl)' couldn't be found, skipping..."
}
Write-Host -ForegroundColor Yellow "Delete action complete"
