0

I have a powershell script that will search through the sub folders of a directory and copy any files that contain a specific string in the name and then move those into a different folder that it creates. The problem I am having is that the script is not creating and new folder but just a new file without an extension. Here is my script.

 Get-ChildItem -Path 'C:\users\user1\Documents\q3\' -Recurse | Where-Object { $_.Name -like "*test2*" -and $_.FullName -notmatch 'newfolder' } | Copy-Item -Destination 'C:\Users\user1\Documents\Q3\test'
2
  • The searching works how I want it to. The problem is that powershell is not creating the 'test' folder. If that folder already exists then there is no problem. I just want powershell to create that folder instead of me having to do it each time. Commented Jan 13, 2020 at 15:24
  • you're going to want to add if{-not (test-path $folder_path)}(mkdir $folder_path) or similar to the script beginning. test for the path of the folder, make it if it isn't there already, then continue. Commented Jan 13, 2020 at 15:35

1 Answer 1

0

There is no parameter with a behavior like: "createifnotexist" for directories in powershell's copy-item() function. (I'm using powershell 5.1 and could not find one)

This is a way to achieve your goal with a one liner

New-Item -ItemType Directory -Name "test" -Path 'C:\Users\user1\Documents\Q3' -Force; Get-ChildItem -Path 'C:\users\user1\Documents\q3\' -Recurse | Where-Object { $_.Name -like "*test2*" -and $_.FullName -notmatch 'newfolder' } | % { Copy-Item -Path "C:\Users\user1\Documents\Q3\test\"}

The New-Item will override the latest created folder with the -Force

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.