我試圖製作某種自動複製 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'"
}
}
根據您的評論,如果需要在 Source 文件夾內的可能子目錄中搜索從 RELEASE.txt 獲取的文件名,您可以執行以下操作:
$sourceFolder = 'C:\repo' # where the original files to copy are
$projectsFolder = 'C:\Test\Projects' # where the project subfolders and file copies need to go
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()
# search for this file inside the Source folder.
# This COULD return several files with that name in different subfolders..
# to not get into trouble with naming collisions in the ProjectX subfolder
# when copying, grab only the first one found.
$sourceFile = Get-ChildItem -Path $sourceFolder -Filter $file -File -Recurse | Select-Object -First 1
if ($sourceFile) {
$targetFolder = Join-Path -Path $projectsFolder -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
$sourceFile | Copy-Item -Destination $targetFolder
}
else {
Write-Warning "File '$file' could not be found in folder '$projectsFolder'"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句