[英]Read text file, creater folders and copy files with Powershell scirpt
我試圖制作某種自動復制 Powershell 腳本,該腳本可以讀取帶有項目名稱和文件名的文本文件,然后使用項目名稱創建新文件夾並將這些文件復制到其中。 因此,例如,我有文件 RELEASE.txt :
project1 example1.rule
project1 example1.doc
project2 example2.sql
project3 example3.sql
我需要在我的本地機器上運行一個腳本,它可以讀取這個文件,創建文件夾 project* 並將這個 example*.* 文件復制到適當的文件夾中。
我理解 Get-Content 命令的步驟,它只是將所有文件從列表復制到特定文件夾,但我想做一些更容易管理發布的事情。
Get-Content 'c:\Test\RELEASE.txt' | ForEach-Object { Copy-Item "c:\Test\Projects\$_" c:\Test\Project-1 }
盡管您的問題不是很清楚要在哪里找到要復制的文件,但我認為這些文件都在您要創建子文件夾的同一個根文件夾中。
為此,您可以這樣做:
$sourceFolder = 'C:\repo'
$rootFolder = 'C:\Test\Projects'
Get-Content 'C:\Test\RELEASE.txt' | ForEach-Object {
# split the line from the text file in a project and filename
$project, $file = ($_ -split '\s+').Trim()
$sourceFile = Join-Path -Path $sourceFolder -ChildPath $file
if (Test-Path -Path $sourceFile -PathType Leaf) {
$targetFolder = Join-Path -Path $rootFolder -ChildPath $project
# create the subfolder if it does not already exist
$null = New-Item -Path $targetFolder -ItemType Directory -Force
# copy the file to the new Project subfolder
Copy-Item -Path $sourceFile -Destination $targetFolder
}
else {
Write-Warning "File '$file' could not be found in folder '$rootFolder'"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.