简体   繁体   English

基于csv的powershell复制和删除文件

[英]powershell copy and delete files based on csv

I have csv file with list of files and action column:我有一个带有文件列表和操作列的 csv 文件:

Filename Action
C:\postgres\1.tmp 1
C:\postgres222\2.txt 1
C:\postgres3333\3.jpeg 0

If action is 1 I need to recreate the same directory path on D:\\ , to copy file there and then to delete it from C:\\ .如果 action 是 1,我需要在D:\\上重新创建相同的目录路径,将文件复制到那里,然后从C:\\删除它。 If action is 0, just ignore it.如果 action 为 0,则忽略它。 In example for above files I want to have 2 new files created on D:\\ = copied from C:\\ and on C:\\ to have only 1 file 3.jpeg (because it has 0 in action)在上述文件的示例中,我希望在 D:\\ = 从 C:\\ 和 C:\\ 复制创建 2 个新文件,以便只有 1 个文件 3.jpeg(因为它有 0 个在起作用)

D:\postgres\1.tmp 
D:\postgres222\2.txt 

Supposing your csv file is named your_file.csv and the delimiter is a blank (" "):假设您的 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 
    }

It looks like your CSV file uses a space character as delimiter to separate the fields from each other.看起来您的 CSV 文件使用空格字符作为分隔符来分隔字段。 If in real life this is not the case, change the -Delimiter in the code below to match the character that is actually used (most common is the comma)如果在现实生活中并非如此,请更改下面代码中的-Delimiter以匹配实际使用的字符(最常见的是逗号)

The below code will create the file path on the D:\\ drive and then move the file to there.下面的代码将在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM