我为自己创建了一个随机任务。我基本上有一个git repo,其中有一个文件结构,在一个特定的文件夹中,我有几个子文件夹,嵌套在这些文件夹中的是3个同名的配置文件夹。我正在尝试创建一个powershell脚本;目标文件夹";,复制";文件夹1"文件夹2";,以及";文件夹3";,而只复制3〃的内容;配置文件夹";s、 维护该文件结构,但只复制需要的内容。理想情况下,在这个过程之后,我喜欢用文件夹名称的一部分名称重命名这些文件,以帮助区分。我确实计划集成脚本的第二部分来解析这些配置文件并导出到excel文档,但目前不确定我有多需要。预期的输出如下,使用了一些错误的文件结构命令,但没有发现太多帮助我实现以下结果。
文件结构:
- 回购
- 目标文件夹
- 数据
- 文件夹1
- 配置文件夹
- 杂项
- 文件夹2
- 配置文件夹
- 杂项
- 文件夹3
- 配置文件夹
- 等等
- 文件夹1
- 数据
- 目标文件夹
希望最终使用
- 导出文件夹
- 目标文件夹
- 文件夹1
- 配置文件夹
- 具有";FOLDER1_ogfilename.yaml">
- 配置文件夹
- 文件夹2
- 配置文件夹
- 具有";FOLDER2_ogfilename.yaml">
- 配置文件夹
- 文件夹3
- 配置文件夹
- 具有";FOLDER3_ogfilename.yaml">
- 配置文件夹
- 文件夹1
- 目标文件夹
我创建了以下项目来尝试这一点,它复制了文件结构,但它为该文件夹中的每个.yaml文件创建了一个文件夹。
$sourceDir = "C:Usershhhappdevhhhdataenvironments"
$targetDir = "C:Usershhhappdevtargetfolder"
Get-ChildItem $sourceDir -Recurse | % {
$dest = $targetDir + $_.FullName.SubString($sourceDir.Length)
If (!($dest.Contains('research,qa,production,global')) -and !(Test-Path $dest))
{
mkdir $dest
}
Copy-Item $_.FullName -Destination $dest -Force
}
您的代码存在问题。
- 您需要将开关
-File
添加到Get-ChildItem cmdlet中,使其查找文件,而不是$sourceDir中的目录 - 使用
Join-Path
构造目标文件夹路径。像这样把两个字符串加在一起,就会丢失一个反斜杠 - 从中获取子字符串时,请使用files
DirectoryName
属性而不是其FullName
,否则$dest变量也将包括文件名(为每个文件创建文件夹( - 显然,您不希望从路径名中包含某些关键字的文件夹中复制文件,因此需要将copy命令放在测试中,而不是放在它下面
尝试:
$sourceDir = "C:Usershhhappdevhhhdataenvironments"
$targetDir = "C:Usershhhappdevtargetfolder"
Get-ChildItem $sourceDir -File -Recurse | ForEach-Object {
# use the files DirectoryName, not the FullName property, otherwise the path will include the file name as well
$dest = Join-Path -Path $targetDir -ChildPath $_.DirectoryName.SubString($sourceDir.Length)
# exclude paths containing these words
if ($dest -notmatch 'research|qa|production|global') {
# create the new folder if it does not already exist
$null = New-Item -Path $dest -ItemType Directory -Force
$_ | Copy-Item -Destination $dest -Force
}
}