我有帶有檔案串列和操作列的 csv 檔案:
Filename Action
C:\postgres\1.tmp 1
C:\postgres222\2.txt 1
C:\postgres3333\3.jpeg 0
如果操作是 1,我需要在 上重新創建相同的目錄路徑D:\,將檔案復制到那里,然后從C:\. 如果 action 為 0,則忽略它。在上述檔案的示例中,我希望在 D:\ = 從 C:\ 和 C:\ 復制創建 2 個新檔案,以便只有 1 個檔案 3.jpeg(因為它有 0 個在起作用)
D:\postgres\1.tmp
D:\postgres222\2.txt
uj5u.com熱心網友回復:
假設您的 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
}
uj5u.com熱心網友回復:
看起來您的 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/351187.html
