Powershell遍历文件夹,在每个文件夹中创建文件 [英] Powershell loop through folders, create file in each folder

查看:365
本文介绍了Powershell遍历文件夹,在每个文件夹中创建文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to recursively loop through all the folders in a directory, then do something within each directory. Create a text file, for example.

我可以将所有子文件夹放入这样的变量中:

I can get all the subfolder into a variable like so:

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

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

However, I can't seem to create a file within each subdirectory - the files are instead created in the top directory. This doesn't work:

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

这引发了一个错误,即找不到目录或路径太长.

That throws up an error that the directory is not found or that the path is too long.

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

How do I do something in each subdirectory of nested folders?

推荐答案

尝试一下:

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

基本上,Get-ChildItem命令返回一个DirectoryInfo对象序列. FullName属性包含完整路径,而Name仅包含叶目录的名称.

Basically, the Get-ChildItem command returns a sequence of DirectoryInfo objects. The FullName property contains the full path, whilst Name just contains the name of the leaf directory.

这篇关于Powershell遍历文件夹,在每个文件夹中创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆