Powershell循环遍历文件夹,在每个文件夹中创建文件

问题描述 投票:0回答:2

我试图递归地循环遍历目录中的所有文件夹,然后在每个目录中执行某些操作。例如,创建一个文本文件。

我可以将所有子文件夹放入变量中,如下所示:

$folders = Get-ChildItem -Recurse | ?{ $_.PSIsContainer }

但是,我似乎无法在每个子目录中创建文件 - 这些文件是在顶级目录中创建的。这不起作用:

$folders | ForEach-Object { New-Item -ItemType file -Name "$_.txt" -path $_}

这会引发错误,指出找不到目录或路径太长。

如何在嵌套文件夹的每个子目录中执行某些操作?

loops powershell
2个回答
42
投票

试试这个:

Get-ChildItem -Recurse -Directory | ForEach-Object {New-Item -ItemType file -Path "$($_.FullName)" -Name "$($_.Name).txt" }

基本上,

Get-ChildItem
命令返回一系列
DirectoryInfo
对象。
FullName
属性包含完整路径,而
Name
仅包含叶目录的名称。


0
投票

你们已经很接近了。我建议迭代按文件循环内的前缀过滤的目标文件夹,如下所示:

$sourceDirectory = "C:\Directory\Source"
$files = Get-ChildItem -File -Path $sourceDirectory
$destination = "C:\Directory\Destination"
$filesDictionary = @{}
foreach ($file in $files) {
    $prefix = $file.Name.Substring(0, 6)
    Get-ChildItem -Recurse -Directory -Path $destination | where {$_.name.StartsWith($prefix)} | ForEach-Object {
        $folderPath = Join-Path -Path $_.FullName -ChildPath "Correspondence" 
        $destinationPath = Join-Path -Path $folderPath -ChildPath $file.Name
        Move-Item -Path $file.FullName -Destination $destinationPath
        break #break if you want to put the file in the first folder with the prefix; or maybe copy it in all of them?
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.