delete folder and contents with Powershell - powershell

I'm trying to delete the contents of the users folder. It works for files but it leaves folders. How can I take folders with it? This is what i have tried using powershell:
$folders = #(
"C:\Users\*\Downloads\*",
"C:\Users\*\Downloads\*.*",
"C:\Users\*\Documents\*.*",
"C:\Users\*\Documents\*.*",
"C:\Users\*\Pictures\*",
"C:\Users\*\Pictures\*.*",
"C:\Users\*\Desktop\*",
"C:\Users\*\Desktop\*.*",
"C:\Users\*\Videos\*",
"C:\Users\*\Videos\*.*")
foreach ($folder in $folders) {Remove-Item $folder -force -recurse -ErrorAction SilentlyContinue}
exit 0
How can i take parents folders in those folders and their child elemetns? I want complete empty Document, desktop etc.

I got it, im slightly stupid in my script i noted:
"C:\Users*\Documents*.",
"C:\Users*\Documents*.",
rip and that was the folder i was working with.. RIP! i changed it to
"C:\Users*\Documents*",
"C:\Users*\Documents*.*",
now it works!! thanks

Related

Why doesn't my Powershell loop grab a PDF file if im calling -Include "*.pdf"

foreach ($file in Get-ChildItem -Path $srcRoot -File -Include "*.pdf" -Force -Recurse {
Above is just a line out of my script that is moving files from one directory to another. Long story short.. My script is working and has been for months. However, today I came across where it didnt move two files that were named like the following.
Thisismyfile.pdf2.pdf
Thisisanotherfile.pdf2.pdf
Now like I said.. the script has been working fine until these files came about. Of course I told the users to make sure they name files correctly ect.. but I dont know why it still didnt move those files. It still contains "*.pdf" as an extenstion.. so what gives?
I suspect that files are not moved in scenario where you have file in folder A with the same name as in folder B. Moving files to the one destination folder will cause name collision with error like Move-Item : Cannot create a file when that file already exists.
If that is the case, please use one of snippets from this answer: Powershell Move-Item Rename If File Exists
I placed few .pdf files (named like a.pdf.pdf, b.pdf.pdf ...) in src directory, running snippet below moves those files to dst folder correctly.
$srcRoot = "C:\Users\$env:username\Desktop\src\"
foreach ($file in Get-ChildItem -Path $srcRoot -File -Include "*.pdf" -Force -Recurse)
{
Move-Item -Path $file -Destination "C:\Users\$env:username\Desktop\dst\"
}

PowerShell script does not copy subfolders and their content

It's my first time using a custom Powershell script and I think I might be missing something. Everything works, except it doesn't copy subfolders and their content.
$sourcePath = 'C:\Users\User\Desktop\test\test1'
$destinationPath = 'C:\Users\User\Desktop\test\test2'
$files = Get-ChildItem -Path $sourcePath -Recurse
$filecount = $files.count
$i=0
Foreach ($file in $files) {
$i++
Write-Progress -activity "Moving files..." -status "($i of $filecount) $file" -percentcomplete (($i/$filecount)*100)
# Determine the absolute path of this object's parent container. This is stored as a different attribute on file and folder objects so we use an if block to cater for both
if ($file.psiscontainer) {$sourcefilecontainer = $file.parent} else {$sourcefilecontainer = $file.directory}
# Calculate the path of the parent folder relative to the source folder
$relativepath = $sourcefilecontainer.fullname.SubString($sourcepath.length)
# Copy the object to the appropriate folder within the destination folder
copy-Item $file.fullname ($destinationPath + $relativepath)
}
i'm sure it's something to do with Path instead of Root or the Recurse option that's not used corretly.
If someone could help me it would be really appreciated.
Thank you!
To copy recursively, use
Copy-Item -Path <src> -Destination <dest> -Recurse
See Official documentation.
This may very well work for you.
As for walking through a previously built list of source files and copying one-by-one as you did, it should work. I did not check/debug the code you put together.
If you actually need this walk through, simply debug your code by printing $files and the source and target of your copy-Item, this will tell you the source of problems. Please post this output in the OP.
You may have to use the option -Directory for Get-ChildItem, or class [System.IO.Path].

How to exclude hidden folder/files from getting copied using Copy-Item in PowerShell?

I have this below code which is used to copy DBUpgrade folder to another location, but it copies the hidden folder present inside it as well.
$Demo="F:\source\DBUpgrade"
$new="F:\Test"
Copy-Item $demo $new -Recurse -Force
Is there any command by which I can exclude the hidden folder and one more thing the name of the hidden folder is $tf because of which i am not able to use remove-item command to remove the folder itself as another option.
You could do a
$list = get-childitem $demo $new -recurse -attributes !H | select fullname
And than a foreach loop
foreach ($file in $list){
Copy commands go here
}
Mind you copy commands will require some finesse to get it in the right folder and may not be worth the hassle
You'll have to trim the path out and do checks if it's $demo or $new to get it to the correct folder.
Get-Childitem by default doesn't show hidden items

PowerShell--Finding any and all Subdirectories and Moving them

This has been sort of asked, but none of the questions I've found have quite answered what I'm looking to do. I'm working with PowerShell (brand new to it) to write a script that will search for subdirectories within a directory and move those to a designated directory if found.
My problem lies within the following code:
$Folders = C:\Users\temp
$MoveFolders = Test-Path $Folders -PathType Container
Write-Host $MoveFolders
#I'm writing this with ISE, so I'm using write-host to view output for testing.
The problem I'm running into is that every time this code is ran, it returns true, even when there are no folders within the temp directory. I've tried it with about every conceivable way I can imagine, and tested with get-childitem piped with a where-object, but I want to only execute the move if a subdirectory is present.
The idea behind it is that, if a user somehow adds a file or folder to this specific one, it will be moved when the task scheduler runs the script.
EDIT
Redirecting my question; It always returns true, and a couple of people have pointed out that what I have written will test the temp folder itself; so is there a way to test for any subfolders and store it as a boolean value, which I can then pass to an if statement that will finish the move process?
I believe this is what you want to do.
#get the folders/subfolders from the directory
$folders = Get-ChildItem C:\Users\temp -Recurse -Directory
#loop through the folders
foreach($folder in $folders) {
#copy the the folder(s) and item(s) within to the destination
Copy-Item -Path $folder.FullName -Destination C:\test -Recurse
}
Here is the updated answer since you edited your question.
$items = Get-ChildItem -Path C:\Users\mkrouse\Desktop\test -Directory -Recurse
#if items is equal to null, then there are no subfolders so assign the boolean to true
if($items -eq $null) {
[bool]$NoSubfolders = $true;
} else {
[bool] $NoSubfolders = $false;
}
Your code tests whether "c:\users\temp" is a folder - which is always true. You need to look for folders within "c:\users\temp". One approach:
$Folders = "C:\temp"
$MoveFolders = Get-ChildItem -Path $folders -Directory
Write-Host $MoveFolders.Count
$MoveFolders now contains a list of all folders within "c:\users\temp". Now you have a list of folders to be moved.

Powershell getfiles.count() to exclude thumbs.db

We have a script running daily that removes old files and directories from an area that people use to transfer data around. Everything works great except for one little section. I want to delete a folder if it's older than 7 days and it's empty. The script always shows 1 file in the folder because of the thumbs.db file. I guess I could check to see if the one file is thumb.db and if so just delete the folder but I'm sure there is a better way.
$location = Get-ChildItem \\dropzone -exclude thumbs.db
foreach ($item in $location) {
other stuff here going deeper into the tree...
if(($item.GetFiles().Count -eq 0) -and ($item.GetDirectories().Count -eq 0)) {
This is where I delete the folder but because the folder always has
the Thumbs.db system file we never get here
}
}
$NumberOfFiles = (gci -Force $dir | ?{$_ -notmatch "thumbs.db"}).count
You can try the get-childitem -exclude option where all files/items in your directory will be
counted except those that end in db:
$location = get-childitem -exclude *.db
It also works out if you specify the file to exclude, in this case thumbs.db
$location = get-childitem -exclude thumb.db
Let me know if this works out.
Ah, I also just noticed something,
$location = get-childitem -exclude *.db
Will only handle .db items in the location directory, if you're going deeper into the tree (say from your GetFiles() and GetDirectories() methods) then you may still find a thumb.db. Hence you'll have to add the exclude option in these methods to ignore thumbs.db.
So, for example in your $item.getFiles() method, if you use get-childitem you will have to specify the -exclude option as well.
Sorry, I should have read your question more closely.
Use this method to provide a exclusion list in the form of a simple text file to exclude specific files or extensions from your count:
$dir = 'C:\YourDirectory'
#Type one filename.ext or *.ext per line in this txt file
$exclude = Get-Content "C:\Somefolder\exclude.txt"
$count = (dir $dir -Exclude $exclude).count
$count