Recursively deleting files within folders without prompting the user via Powershell - powershell

I'm currently trying to remove all the files within a folder named Local. The script below does this, but it prompts the user in a PowerShell window. If I append the -Force flag my script then removes all files within all folders. I'm not sure how to remove all the files within the Local folder and not prompt the user. Below is the script in question.
$Path = "C:\Program Files (x86)\folder1\folder2\"
Function Clear-Cache
{
Get-ChildItem 'C:\Users\Admin\Documents\GI Studies' -File -Recurse | Where-Object {$_.FullName -match "data\\local"} | % {del $_.FullName #-Force}
}
Clear-Cache

You could first do a recursive search for the directory(ies) from which to delete files, then do a non-recursive delete of the files in each of those.
Function Clear-Cache
{
$localFolders = Get-ChildItem 'C:\Users\Admin\Documents\GI Studies' -Directory -Recurse | Where-Object {$_.FullName -match 'data\\local$'}
$localFolders |% { dir $_.FullName -File | del -Force }
}
Edit
Use FullName of directory when searching for files

Function Clear-Cache
{
$localFolders = Get-ChildItem 'C:\Users\Admin\Documents\GI Studies' -Directory -Recurse | Where-Object {$_.FullName -match 'data\\local$'}
$localFolders |% { dir $_.Fullname -File | del -Force }
}
Appending .FullName to the fifth line of your suggested code actually solved my problem. Thank you latkin for assisting me!

You can also use .NET Delete() function, it does not ask for confirmation:
$Path = "C:\folder"
$exclude = "file1.txt","file2.txt"
Get-ChildItem -Path $Path -Include * -Exclude $exclude -Recurse | foreach {
$_.Delete()
}

Related

How to loop through all subfolders in a directory, and remove files with a specific filename

I am trying to write a script in Powershell to remove some files automatically with a certain file name.
My idea is to get all the folders in the directory, then loop through the subdirectory, and remove all items with the file name, but it doesn't seem to be working as expected.
Here is my script
$folders = Get-ChildItem -path "C:\Website-Backup" -Recurse | Where-Object {$_.PsIsContainer} |Group-Object {$_.FullName.Split('_')[0] }
$subfolders = Get-ChildItem -path $folders -Recurse | Where-Object {$_.PsIsContainer} | Group-Object {$_.FullName.Split('_')[0] }
ForEach($subfolder in $subfolders)
{
Remove-Item * -Include *100x*
}
Any idea why the script doesn't seem to be doing anything?
I think you can simplify your code if I understand correctly to:
Get-ChildItem "C:\Website-Backup" -Recurse -include "*100x*" -file | remove-item
The Group-Object command is likely what's confusing things here - Remove-Item is expecting a path - you're not referencing the subfolder variable in your loop as well, so this is the same as just running the Remove-Item command as many times as there are items in the array.
You can try this instead;
Get-ChildItem -Path "C:\Website-Backup" -Recurse | Where-Object -FilterScript { $_.name -like 'MyFile.txt' } | Remove-Item
This will pipe the returned child items into Where-Object, filter it to the specified file name, then pass that to Remove-Item as a file path.
You can also skip the Where-Object, but you lose a bit of control this way;
Get-ChildItem -Path 'C:\WebSiteBackup\*MyFile.txt' -Recurse | Remove-Item

Exclude multiple folders from get-childitem

I have this script that compares 2 directories with each other if it matches it copies it to the other directory. But i need 2 folders to be excluded on the source folder because there are old files there. I excluded one folder but i can't add an second one. Can someone help me out? (I'm a beginner in Powershell) I know the foreach loop is empty, this is for testing purposes.
$aDir = "C:\Replace TEST SCRIPT\A"
$bDir = "C:\Replace TEST SCRIPT\Y"
$aFiles = Get-ChildItem -Path "$bDir\" -Exclude "Folder1","Folder2" | Get-ChildItem -Path "$bDir\*.pdf" -Recurse -File | select -exp FullName
ForEach ($file in $aFiles) {
$laatste = (Get-Item $file).LastWriteTime
$filenaam = Split-Path -Path "$file" -Leaf
if(Test-Path -Path "C:\Replace TEST SCRIPT\A\$filenaam") {
Write-Output "$filenaam exists in $aDir. Copying."
Copy-Item -Path "$file" -Recurse -Destination "$aDir"
} else {
}
}
You can do it the following way:
$aFiles = Get-ChildItem -Path "$bDir\" -Exclude "PDF","folder2" | Get-ChildItem -filter "*.pdf" -Recurse -File | select -exp FullName
Btw.
There is already a post to your certain question:
How can I exclude multiple folders using Get-ChildItem -exclude?
Please take a look at it and let us know.

PowerShell Delete everything else except one file in root and one in sub folder

I need to delete all files and folders except one file in root folder and one other file in sub folder. Furthermore file names are passed as an argument to the script as comma sep1rated string like 'file1.txt,Subfolder\file2.txt'.
I was trying to do something like this,
$Path = "C:\\Delete\\"
$Argument= "file1.txt,Subfolder\\file2.txt"
$ExcludedFiles = [string]::Join(',', $Argument);
$files = [System.IO.Directory]::GetFiles($Path, "*", "AllDirectories")
foreach($file in $files) {
$clearedFile = $file.replace($Path, '').Trim('\\');
if($ExcludedFiles -contains $clearedFile){
continue;
}
Remove-Item $file
}
By doing this all the folders remain and all the files get deleted.
Can any one please suggest that how should I try to do this since I am having difficulty in doing this.
The easiest way to get it done is using the -Exclude paramater in get-childitem.
Here are the examples to Exclude a file:
Get-ChildItem C:\Path -Exclude SampleFileToExclude.txt| Remove-Item -Force
Exclude files with a specific extension using wildcard:
Get-ChildItem C:\Path -Exclude *.zip | Remove-Item -Force
Get all the files recursively and exclude the same:
Get-ChildItem C:\Path -Recurse -Exclude *.zip | Remove-Item -Force
Exclude list of items as per your wish in the same command:
Get-ChildItem C:\Path -Recurse -Exclude *.zip, *.docx | Remove-Item -Force
You can even use with array and where condition:
$exclude_ext = #(".zip", ".docx")
$path = "C:\yourfolder"
Get-ChildItem -Path $path -Recurse | Where-Object { $exclude_ext -notcontains $_.Extension }
And then you can remove using Remove-Item
Hope it helps.

I need to find a Folder on the Network Share

How can I find Folders called BlueMountain when this folder could be nested anywhere in my Users home folder
\\Server\Users\<personsname>\
Ultimately I want to delete the folder but just to be on the safe side. The BlueMountain folder must have one of these subfolder
Certs
Config
Macros
Scripts
Spool
Traces
Transfer
This is what I have so far
Get-ChildItem -Path \\Server\Users -Recurse -Directory -Filter $_.FOLDERNAME | ForEach-Object {
If $_.FullName --eq "BlueMountain" {
}
}
You can use -recurse to look for the last thing in your path recursively. So this:
Get-ChildItem \\server\Users\BlueMountain -recurse
Will look in all subfolders of "\server\Users" for anything named "BlueMountain". Then you just need to make sure it has one of your folders.
$SubFolders = 'Certs','Config','Macros','Scripts','Spool','Traces','Transfer'
Get-ChildItem \\server\Users\BlueMountain -recurse | Where{Get-ChildItem "$($_.FullName)\*" -Include $SubFolders}
That should list only the BlueMountain folders found recursively in \server\Users which contain one of the specified subfolders. Then you can just pipe that to Remove-Item -force and call it a day. Or if you want to track things pipe it to tee-object and then to remove-item.
try this :
$SubFolders = 'Certs','Config','Macros','Scripts','Spool','Traces','Transfer'
$wordtosearch="BlueMountain"
$SearchPattern= ($SubFolders | %{ "$wordtosearch\\$_" }) -join "|"
get-childitem "\\Server\Users" -directory -Recurse |
where FullName -match $SearchPattern |
Split-Path -path {$_.FullName} -Parent |
remove-item -Recurse -ErrorAction SilentlyContinue

How to rename files using HttpUtility.UrlEncode method in PowerShell?

I have a bunch of html files that I need to rename with url encoding before I upload them to the server. I've tried:
Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html | Rename-Item -NewName { $_.Name.replace("*.html",[Web.Httputility]::UrlEncode("*.html")) }
But that doesn't apply the encoding, can this be even done somehow?
Here's a basic way to do it, based on this answer:
(Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html -File) |
foreach { ren $_.fullname ([uri]::EscapeDataString($_))}
Originally I had written it without the () around the Get-ChildItem, but found it was still reading directory information while the rename had already renamed the first item. Then the rename reencoded the first item a second time, thus making it a bit munged up.
Here's a cleaner version that handles the files first and then folders:
$files = Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html -File
$folders = Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html -Directory
$files | foreach { ren $_.fullname ([uri]::EscapeDataString($_))}
$folders | foreach { ren $_.fullname ([uri]::EscapeDataString($_))}
Based on your answers i did this to make it work
(Get-ChildItem -Path c:\temp\ -Recurse -Filter *.html) |
foreach { ren $_.fullName ([uri]::EscapeDataString($_.Name))} | Out-Null
Get-ChildItem -Path c:\temp\ -Recurse | ?{ $_.PSIsContainer } |
foreach { ren $_.fullName ([uri]::EscapeDataString($_.Name))}
First I had to do only files and then folders, because when top folder gets renamed, then the path to files inside it doesn't exist any more.