Home > Software design >  How to add a folder to every folder called "Photographs"?
How to add a folder to every folder called "Photographs"?

Time:06-16

I am new to PowerShell. I have only recently learned how to add a folder to a folder while currently in it.

I have a couple hundred file folders that each contain a copy of a folder called "Photographs". I want to select each folder called "Photographs" and then add a folder called "drafts" to it.

How do I do this?

CodePudding user response:

Combine Get-ChildItem with New-Item as follows:

# Note: 
#  "." targets the current dir; adapt as needed.
#  New-Item outputs a [System.IO.DirectoryInfo] instance for
#  each directory it creates; to suppress, append "| Out-Null"
Get-ChildItem . -Recurse -Directory -Filter Photographs |
  New-Item -Type Directory -Path { $_.FullName } -Name drafts -Force -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

Note the use of a delay-bind script block ({ ... }) to dynamically derive the value for the
-Path parameter from each input object ($_).

-Force causes New-Item -Type Directory to not report an error when a target directory by that name already exists (in that event, the [System.IO.DirectoryInfo] instance that is output describes the preexisting, not a newly created directory).

  • Related