[英]powershell copy and delete files based on csv
我有一個帶有文件列表和操作列的 csv 文件:
Filename Action
C:\postgres\1.tmp 1
C:\postgres222\2.txt 1
C:\postgres3333\3.jpeg 0
如果 action 是 1,我需要在D:\\
上重新創建相同的目錄路徑,將文件復制到那里,然后從C:\\
刪除它。 如果 action 為 0,則忽略它。 在上述文件的示例中,我希望在 D:\\ = 從 C:\\ 和 C:\\ 復制創建 2 個新文件,以便只有 1 個文件 3.jpeg(因為它有 0 個在起作用)
D:\postgres\1.tmp
D:\postgres222\2.txt
假設您的 csv 文件名為your_file.csv並且分隔符為空白 (" "):
Get-Content ./your_file.csv |
ConvertFrom-Csv -Delimiter " " |
Where-Object { $_.Action -eq 1 } |
ForEach-Object {
Copy-Item $_.Filename -Destination $_.FileName.Replace("C:", "D:") -Force
}
看起來您的 CSV 文件使用空格字符作為分隔符來分隔字段。 如果在現實生活中並非如此,請更改下面代碼中的-Delimiter
以匹配實際使用的字符(最常見的是逗號)
下面的代碼將在 D:\\ 驅動器上創建文件路徑,然后將文件移動到那里。
Import-Csv -Path 'D:\Test\filelist.csv' -Delimiter ' ' |
Where-Object { $_.Action -ne '0' } |
ForEach-Object {
$originalDrive = [System.IO.Path]::GetPathRoot($_.FileName) # --> C:\
$originalPath = [System.IO.Path]::GetDirectoryName($_.FileName)
# construct the new path on the D:\ drive
$targetFolder = 'D:\{0}' -f $originalPath.Substring($originalDrive.Length)
# or use:
# $targetFolder = Join-Path -Path 'D:\' -ChildPath $originalPath.Substring($originalDrive.Length)
# create the target directory if this does not exist
$null = New-Item -Path $targetFolder -ItemType Directory -Force
# move the file from the original location to the target directory
Move-Item -Path $_.FileName -Destination $targetFolder
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.