尝试通过基于 CSV 列输入的 PowerShell 删除文件

huangapple go评论53阅读模式
英文:

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

问题

我正在尝试使用PowerShell脚本删除文件,并从CSV文件中获取文件详细信息。

CSV文件-

尝试通过基于 CSV 列输入的 PowerShell 删除文件

以下是PowerShell代码。

$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"

但是我仍然无法实现这一点,请有人建议我在这里做错了什么,指导我正确的方向。

英文:

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

CSV File-

尝试通过基于 CSV 列输入的 PowerShell 删除文件

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.

答案1

得分: 1

你现在的代码只需要将 Get-Content(用于读取纯文本非结构化数据)替换为 Import-Csv(用于读取Csv文件,正如其名称所示)。用于测试路径是否存在可以使用 Test-Path

Import-Csv "C:\DeleteFiles\FilesPresent1.csv" | ForEach-Object {
    Write-Host "Checking on '$($_.ServerRelativeUrl)'..."
    # 检查文件是否存在
    if (Test-Path $_.ServerRelativeUrl) {
        # 如果存在,删除它
        Remove-Item -LiteralPath $_.ServerRelativeUrl.Trim() -Force
        Write-Host "Deleted: '$($_.ServerRelativeUrl)'..."
        # 并继续下一个文件
        return
    }

    # 如果不存在
    Write-Host "'$($_.ServerRelativeUrl)' 未找到,跳过..."
}

Write-Host -ForegroundColor Yellow "删除操作完成"
英文:

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"

huangapple
  • 本文由 发表于 2023年6月26日 23:01:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定