0

The following script find all folders containing txt files

PS D:\Testfolder> Get-ChildItem -Recurse -Filter *.txt | Select-Object -ExpandProperty DirectoryName -Unique
D:\Testfolder\2nd
D:\Testfolder\3rd
D:\Testfolder\4th
D:\Testfolder\5th
D:\Testfolder\first

Now I want to move these folders to

D:\Testfolder\_dn

So that it looks the following -

D:\Testfolder\_dn\2nd
D:\Testfolder\_dn\3rd
D:\Testfolder\_dn\4th
D:\Testfolder\_dn\5th
D:\Testfolder\_dn\first

How can I do that?

Ahmad Ismail
  • 11,636
  • 6
  • 52
  • 87
  • 1
    What have you tried? Have any work to show? What part exactly are you stuck at? Stack Overflow is not a code writing service. If you need help learning how to code or troubleshoot something then this is the place for you. If you need code from scratch then you should hire a developer. – guiwhatsthat Mar 20 '18 at 14:01

1 Answers1

1

From here, you can do something like this -

$targetDir = 'D:\Testfolder\_dn'
Get-ChildItem -Recurse -Filter *.txt | Select-Object -ExpandProperty DirectoryName -Unique | Move-Item -Destination $targetDir -Recurse -Container
Vivek Kumar Singh
  • 3,223
  • 1
  • 14
  • 27
  • worked for me : Get-ChildItem -Recurse -Filter *.txt | Select-Object -ExpandProperty DirectoryName -Unique | Move-Item -Destination 'D:\Testfolder\_dn' – Ahmad Ismail Mar 20 '18 at 14:56
  • If this answered your question then you should accept it as the answer. – EBGreen Mar 20 '18 at 15:01
  • I upvoted the answer but the last "-Recurse -Container" giving error in my ps prompt. So, I gave the code that worked for me in the comment. However, as you mentioned "Move-Item will accept input from the pipe", how can I use that value for example to move the folder to a relative path. I mean, if I use -Path, than what will be the variable after that? – Ahmad Ismail Mar 20 '18 at 15:08
  • Relative paths don't need a variable. They are literally relative to the item being moved – EBGreen Mar 20 '18 at 15:17
  • What I meant is suppose here the destination is 'D:\Testfolder\_dn'. But I want to move it to D:\Testfolder\2nd\..\_dn. So now I need the variable which has the value D:\Testfolder\2nd. So, now the last part will look like "Move-Item -Destination $_var"\..\_dn. What will be $_var. – Ahmad Ismail Mar 20 '18 at 15:22
  • 1
    That is not a relative path then it is a literal path – EBGreen Mar 20 '18 at 15:30