2017-06-14 48 views
-2

我有一個文件路徑的CSV文件。對於每個路徑,我想測試該文件是否存在。如果有,請複製到新位置。如果沒有,請將該路徑寫入「丟失的文件」文件。如何編寫PowerShell腳本來測試和複製文件路徑?

這是我迄今爲止...

Import-Csv .\files.csv | ForEach { 
    If (Test-Path -Path $_.File) { 
     Write-Output "$($_.File) exists" 
    } Else { 
     Write-Output "$($_.File) does NOT exist" 
     $_.File | Out-File .\missingFiles.txt -Append 
    } 
} 
+0

你是什麼意思,它缺乏複製?你有什麼嘗試?它不起作用嗎?如果是這樣,你會收到什麼錯誤。 – Nick

+0

使用'robocopy'。 –

+0

目前它的工作原理,但我喜歡添加的功能,以便能夠將它找到的功能複製到新的位置。 –

回答

0
Import-Csv .\files.csv | ForEach { 

If (Test-Path -Path $_.File) { 

    Write-Output "$($_.File) exists" 
    Copy-Item -Path $_.File -Destination "\\Wherever\You\Want" 

} Else { 

    Write-Output "$($_.File) does NOT exist" 
    $_.File | Out-File .\missingFiles.txt -Append 

} 

} 
+0

非常感謝! –

+1

如果這對您有用,請將其標記爲接受的答案。 :) – Nick

0

你不應該相信文件系統的這種方式。文件可能會消失或更改您的Test-PathCopy-Item之間的權限。一個更安全的方法來做到這一點(你可能會認爲你不需要這種安全)...

Import-Csv -Path .\files.csv | %{ 
    try { 
     Copy-Item -Path $_ -Destination <path> 
     Write-Verbose -Message "Found: $_" 
    } catch { 
     $_ | Out-File -Append -Path .\missing.txt 
     Write-Verbose -Message "Not Found: $_" 
    } 
} 
+1

安東尼,除了原始文件不存在之外,您的副本可能因各種原因而失敗。您可能出現網絡故障,在源或目的地被拒絕訪問,磁盤空間不足等等。考慮讓你提出的文件跟蹤失敗,描述它,並在你的消息傳遞中包含例外文本。 –

+1

我會避免重新發明輪子,而是使用'robocopy'。 –

+0

Damnit,@Bill_Stewart,你是對的!作者將不得不弄清楚如何將他的CSV文件轉換爲適當的輸入,以及如何捕捉他需要的輸出(我假設這些東西是他的上下文中的要求)。 –

相關問題