【问题标题】:powershell copy and delete files based on csvpowershell基于csv复制和删除文件
【发布时间】:2021-12-18 13:18:41
【问题描述】:

我有包含文件列表和操作列的 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 

【问题讨论】:

    标签: powershell foreach


    【解决方案1】:

    您的 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
    }
    

    【讨论】:

      【解决方案2】:

      假设您的 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 
          }
      

      【讨论】:

        猜你喜欢
        • 2015-04-05
        • 2015-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-18
        • 2023-03-27
        • 2019-01-16
        相关资源
        最近更新 更多