简体   繁体   中英

Powershell loop through folders, create file in each folder

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?

Try this:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM