I want to delete a list of folders in temp.
Name of folders are numeric- 2, 3, 4 etc..
PS C:\Users\sos$> Get-ChildItem -path C:\Temp
Is there a PowerShell way to get this scripted
Soheil Hashemi opened the bag on answering this question so lets have a look at a basic option.
You need to have all the files that are just a number from the temp directory. Let use Where-Object to match the files we are looking for.
$Path = "C:\temp"
Get-ChildItem $Path -Directory | Where-Object{$_.BaseName -notmatch "\D"} | Remove-Item -Confirm:$false -WhatIf
Get all the files from the $path and match any files where the file name (without extension) only contains numbers. Then pipe the results into Remove-Item. Remove the -WhatIf when you are sure it is finding the right files.
If you don't have PowerShell 3.0 then you can change the Where clause and remove the -Directory switch.
Get-ChildItem $Path | Where-Object{$_.BaseName -notmatch "\D" -and $_.PSIsContainer} | Remove-Item -Confirm:$false -WhatIf
your question is not complete but first create list like me
$a = #'
1.txt
2.txt
3.txt
4.txt
'#
or $a = (get-content c:\filelist.txt)
then
$a | foreach { Remove-Item c:\temp\$_ }
Related
Im still generally new to powershell, and I am trying to create a program that will take files based on their name, and move them into folders that have a similar name but not exactly the same.
For example, Lets say I have 3 files, Apples.txt, Grapes.txt, and Oranges.txt. And I want to move them into corresponding folders, ApplesUSA, GrapesNY, OrangesFL.
I could just hard code it using a loop and a If-Then Statement. i.e If Apples.txt exists move to ApplesUSA. But I want it to be dynamic, so if other files and folders are added later I dont have to update the code. Is there a way to write a statement that would say if FileA and FolderB are similar in name (both contain apples in the name somewhere) then move fileA to FolderB and so on.
Any help appreciated. Thanks!!!!
try Something like this
$PathWithFile="C:\temp\Test"
$PathWithDir="C:\temp\Test"
Get-ChildItem $PathWithFile -file -Filter "*.txt" | %{
$CurrentFile=$_
$Dirfounded=Get-ChildItem $PathWithDir -Directory | where {$_ -match $CurrentFile.BaseName} | select FullName -First 1
if ($Dirfounded -ne $null)
{
move-Item $CurrentFile.FullName -Destination $Dirfounded.FullName -WhatIf
}
}
A oneliner similar to #Esperento's
gci *.txt -af|%{$File=$_.FullName;gci "$($_.BaseName)*" -ad|%{Move $File -Dest $($_.FullName) -whatif}}
The verbose version:
PushD "X:\path\to\base\folder"
Get-ChildItem *.txt -File | ForEach-Object{
$File = $_.FullName
Get-ChildItem "$($_.BaseName)*" -Directory | ForEach-Object {
Move-Item $File -Destination $_.FullName -whatif
}
}
PopD
Both versions require PowerShell V3 for the -File and -Directory parameters (and their aliases -af/-ad) This can be substituted by an additional |Where-Object{ $_.PSIsContainer} respective | Where-Object{!$_.PSIsContainer}
I've been struggling with this all day now. I'm trying to delete any files in a given directory if the filenames match a word in a CSV list.
I have imported the CSV list as text then try to match words with the filenames in the target directory, however I'm not sure which operator to use or how to go about this. Obviously 'Match' is not a cmdlet.
#store csv file as variable
$CSVList = Get-content -Delimiter (',') -path "C:\Users\Leeds TX 11\Desktop\Test folder\Watchfolder\DAZN Production Numbers - purgelist.csv"
write-host $CSVList
#delete if word matches .csv entry
$targetdirectory = "C:\Users\Leeds TX 11\Desktop\Test folder\AVMedia"
$Files = Get-childItem $targetdirectory | Match ("\w") $CSVList | remove-item -whatif
write-host $Files
Just add a Where-Object to the pipe where you check whether the Name property is -In the $CSVList:
# ...
$Files = Get-ChildItem $targetdirectory | Where-Object Name -In $CSVList | Remove-Item -whatif
Note: I consider the filenames within your CSV contains a file extension. If not, you want to change Where-Object Name to Where-Object BaseName.
Edit. Since you are using PowerShell Version 2, you have to use -contains and swap the variables:
$Files = Get-ChildItem $targetdirectory | Where-Object {$CSVList -contains $_.BaseName} | Remove-Item -whatif
try Something like this
#store csv file as variable and take first column
$CSVList = (import-csv "c:\temp\missing.csv" -Header col1).col1
#delete if word matches .csv entry
$targetdirectory = "C:\temp2"
$Files = Get-childItem $targetdirectory -Recurse | Where-Object {$CSVList -contains $_.BaseName } | remove-item -whatif
write-host $Files
I am really new into powershell, I googled alot and merged my results into this, but to begin with, my folder structure is like this:
test-neu
_bewertet
1.txt
2.txt
1
1.txt
2.txt
2
1.txt
3.txt
4.txt
...
My goal is to look for all the files stored in _bewertet and if these files also exist in any other subfolder than itself (regarding, filename and size), it should be deleted in there. So to be clear, the files should stay in _bewertet but nowhere else.
$ignore = #("*_bewertet*");
$one = Get-ChildItem -Recurse -path C:\Users\name\Desktop\test-neu\_bewertet
$two = Get-ChildItem -Recurse -path C:\Users\name\Desktop\test-neu -Exclude $ignore | ? { $_.PSIsContainer }
$matches = (Compare-Object -ReferenceObject $one -DifferenceObject $two -Property Name,Length -ExcludeDifferent -IncludeEqual)
foreach ($file in $matches)
{
Remove-Item C:\Users\name\Desktop\test-neu\$($file.Name)
}
So far, it really does nothing if I run my script..., my guess is, the Remove-Item part needs to be adjusted. The path just goes to C:\Users\name\Desktop\test-neu\1.txt for example and so the appropriate subfolder is missing.
If you guys could help me out there, that would mean alot to me. Any suggestions are welcome. Have a nice day. :)
This is the simplest logic I could come up with, to achieve this goal
$keep = Dir -Path t:\bewertet -Recurse
$allFiles = Dir -Path t:\ -Recurse -Include *.txt | Where Directory -NotLike "t:\bewertet*"
$allFiles | Where Name -in $keep.Name | Remove-Item
$Keep defines the list of files in the bewertet folder.
$allFiles defines a list of all files recursively, specifying only .txt files, and where the directory is not t:\bewertet.
Finally, we filter through $allFiles, finding files with matching name to the files in $keep and then remove each of those.
Even more better
OP came back and said We forgot to check if it's the same size!, so being that I'm in the Christmas Spirit, I wrote this lazy comparison.
$keep = gci t:\bewertet -Recurse
$allFiles = dir -Path t:\ -Recurse -Include *.txt | Where Directory -NotLike "t:\bewertet*"
$matches = $allFiles | ? Name -in $keep.Name
ForEach ($match in $matches){
$source = $keep | ? Name -eq $match.Name
$Samefile = ($source.Length -eq $match.length)
"Does file size match? [$Samefile]"
if ($Samefile){
"deleting..."
Remove-item $match
}
}
I have a folder where I need to delete all files and folders except a small list of files and folders.
I can already exclude a list of files, but don't see a way to exclude a folder and its contents.
Here is the folder structure:
|-C:\temp
\-C:\temp\somefile.txt
\-C:\temp\someotherfile.txt
| |-C:\temp\foldertodelete
\-C:\temp\foldertodelete\file1.txt
| |-C:\temp\foldertokeep
| \-C:\temp\foldertokeep\file2.txt
I want to keep somefile.txt and the folder foldertokeep and its content.
This is what I have right now:
Get-ChildItem -Path 'C:\temp' -Recurse -exclude somefile.txt | Remove-Item -force -recurse
This really does not delete somefile.txt. Is there a way to exclude folder foldertokeep and its content from the delete list?
Get-ChildItem -Path 'C:\temp' -Recurse -exclude somefile.txt |
Select -ExpandProperty FullName |
Where {$_ -notlike 'C:\temp\foldertokeep*'} |
sort length -Descending |
Remove-Item -force
The -recurse switch does not work properly on Remove-Item (it will try to delete folders before all the child items in the folder have been deleted). Sorting the fullnames in descending order by length insures than no folder is deleted before all the child items in the folder have been deleted.
In PowerShell 3.0 and below, you can try simply doing this:
Remove-Item -recurse c:\temp\* -exclude somefile.txt,foldertokeep
Unless there's some parameter I'm missing, this seems to be doing the trick...
Edit: see comments below, the behavior of Remove-Item has changed after PS3, this solution doesn't seem applicable anymore.
Select everything excluding what needs to be keep and pipe that to a delete command.
Say you have those folders
C:.
├───delme1
│ │ delme.txt
│ │
│ └───delmetoo
├───delme2
├───keepme1
│ keepmetoo.txt
│
└───keepme2
To delete everything but preserve the keepme1 and keepme2 folders.
Get-ChildItem -Exclude keepme1,keepme2 | Remove-Item -Recurse -Force
Other solutions are fine but I found this easy to understand and to remember.
I used the below and just removed -Recurse from the 1st line and it leaves all file and sub folders under the exclude folder list.
Get-ChildItem -Path "PATH_GOES_HERE" -Exclude "Folder1", "Folder2", "READ ME.txt" | foreach ($_) {
"CLEANING :" + $_.fullname
Remove-Item $_.fullname -Force -Recurse
"CLEANED... :" + $_.fullname
}
Yes I know this is an old thread. I couldn't get any of the answers above to work in Powershell 5, so here is what I figured out:
Get-ChildItem -Path $dir -Exclude 'name_to_ignore' |
ForEach-Object {Remove-Item $_ -Recurse }
This moves the -Recurse to Remove-Item instead of where the items are found.
According to MSDN Remove-Item has a known issue with the -exclude param. Use this variant instead.
Get-ChildItem * -exclude folderToExclude | Remove-Item
I ran into this and found a one line command that works for me. It will delete all the folders and files on the directory in question, while retaining anything on the "excluded" list. It also is silent so it won't return an error if some files are read-only or in-use.
#powershell Remove-item C:\Random\Directory\* -exclude "MySpecialFolder", "MySecondSpecialFolder" -force -erroraction 'silentlycontinue'
This would also help someone...
Adding a variable for PATH_GOES_HERE that is empty or isn't defined prior can cause a recursive deletion in the user directory (or C:\windows\system32 if the script is ran as admin). I found this out the hard way and had to re-install windows.
Try it yourself! (below will only output the file directories into a test.txt)
Get-ChildItem -Path $dir2 -Recurse -Exclude "Folder1 ", FileName.txt | foreach ($_) {
$_.fullname >> C:\temp\test.txt
}
I used this, that works perfectly for me
Get-ChildItem -Path 'C:\Temp\*' -Recurse | Where-Object {($_.FullName -notlike "*windirstat*") -and ($_.FullName -notlike "C:\Temp\GetFolderSizePortable*")} | Remove-Item -Recurse
If your paths include regex special characters then you need to use the -LiteralPath option which does not allow piping. The correct solution in that case looks like this:
Remove-Item -force -LiteralPath(
Get-ChildItem -Path 'C:\temp' -Recurse -exclude somefile.txt |
Select-Object -ExpandProperty FullName |
Where-Object { $_ -notlike 'C:\temp\foldertokeep*' } |
Sort-Object length -Descending
)
This would also help someone...
Get-ChildItem -Path PATH_GOES_HERE -Recurse -Exclude "Folder1 ", "Folder2", FileName.txt | foreach ($_) {
"CLEANING :" + $_.fullname
Remove-Item $_.fullname -Force -Recurse
"CLEANED... :" + $_.fullname
}
I want get contribution for this idea
delete all folder and files include hidden folder
$get-childitem -Path D:\path\folder\to\delete* -Force |select-object -Expandproperty Fullname |remove-item -recurse -Confirm:$false -Force
delete all folder and file include hidden folder but retain exclude folder
$get-childitem -Path D:\path\folder\to\delete* -Exclude nameexludefolder -Force | select-object -Expandproperty Fullname | remove-item -Force
$get-childitem -Path D:\path\folder\to\delete\ -Exclude nameexludefolder -Force | select-object -Expandproperty Fullname | remove-item -Force
first line remain folders,
2nd line remove remain folder
Is it possible to define an array of filenames (all files in different folders) and then in a loop delete them all, or do something else?
Actually I need to create a few symbolic links using mklink to one file, putting those links in a different folders, replacing the old links if there was any.
Deleting an array of filenames is simple:
Remove-Item foo.txt,c:\temp\bar.txt,baz\baz.txt
Or via a variable:
$files = 'foo.txt','c:\temp\bar.txt','baz\baz.txt'
Remove-Item $files
And then based on all files in different folders:
$folders = 'C:\temp','C:\users\joe\foo'
Get-ChildItem $folders -r | Where {!$_.PSIsContainer} | Remove-Item -WhatIf
Remove the -WhatIf to do the actual removal.
If you want to delete a file with a specific name you could use the -Filter parameter on Get-ChildItem. This would be the best performing approach:
$folders = 'C:\temp','C:\users\joe\foo'
Get-ChildItem $folders -r -filter foo.bak | Remove-Item -WhatIf
If the name requires more sophisticated matching then you can use a regex in a Where scriptblock e.g.:
$folders = 'C:\temp','C:\users\joe\foo'
Get-ChildItem $folders -r | Where {$_.Name -match 'f\d+.bak$'} |
Remove-Item -WhatIf
something like this should work:
can't test right now, sorry
$filenames = #('filename1.txt', 'filename2.txt', 'filename3.txt')
foreach($file in $filenames)
{
#GCI recursive to find all instances of this filename
$filesToDelete = Get-ChildItem -R | where {$_.Name -eq $file}
foreach($f in $filesToDelete)
{
#delete the file that matches, etc. here
# just using Write-Host to echo out the name for now
Write-Host $f.Name
}
}
As with most powershell, you can really compress this, but wanted to extend for explanation.
You could extend this to match your needs. For example if you needed all files that contain the word "delete", you could do gci | where {$_.Name -like "$file"}