英文:
Trying to delete files through power shell based on CSV column input
问题
我正在尝试使用PowerShell脚本删除文件,并从CSV文件中获取文件详细信息。
CSV文件-
以下是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-
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论