Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to delete files through power shell based on CSV column input

I am trying to delete files using PowerShell script and taking files in put details from CSV file.

CSV File-

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading