[英]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.