Powershell Remove-Item leaving Folders Behind - powershell

So I want to clean up some of my users profiles on a nightly basis using the following "script"
Get-ChildItem 'F:\View\Profiles\' -Recurse -Force |
Where-Object {$_.Directory -match 'F:\\View\\Profiles\\((\w*).V2)\\AppData\\Roaming\\Trillian\\users\\((\w*%\w*%\w*))\\logs\\(_CLOUD|ASTRA)'} |
Remove-Item -Recurse -Force
This deletes all the log files but leaves behind the folder structure. Because of that I tried the following query.
Get-ChildItem 'C:\TestProfileClean' -Recurse -Force |
Where-Object {(($_.Name -eq "logs" -and $_.Directory) -and $_.DirectoryName -match 'C:\\TestProfileClean\\(\w*.V2)\\AppData\\Roaming\\Trillian\\Users\\((\w*)%40(\w*)%2Ecom)' )} |
Remove-Item -Recurse -Force
This ensures that the folder deleted is named "logs" it is a directory and the directory name is in this format.
C:\\TestProfileClean\\(\w*.V2)\\AppData\\Roaming\\Trillian\\Users\\((\w*)%40(\w*)%2Ecom)
The problem is when I run the second command it does not delete any files, if I cut off $_.DirectoryName then I get the following output.
Directory: C:\TestProfileClean\username.V2\AppData\Roaming\Trillian\users\username%40compcorp%2Ecom
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 12/14/2016 9:56 AM logs
Which will delete what I want but isn't specific enough for me to be comfortable running it.
What am doing wrong that is preventing folders from being deleted but the script will delete all non folder items.

You are missing the wildcard to go through all of them under the folder . I just modified your code :
Get-ChildItem 'F:\View\Profiles\*' -Recurse -Force |
Where-Object {$_.Directory -match 'F:\\View\\Profiles\\((\w*).V2)\\AppData\\Roaming\\Trillian\\users\\((\w*%\w*%\w*))\\logs\\(_CLOUD|ASTRA)'} |
Remove-Item -Recurse -Force
Note: I am not checking the Regex. I am only tweaking the get-childitem part.
Apart from this , I have 2 other suggestion for you. If you really want to delete the user profiles nightly basis, then you can use the small utility tools
1) made of batch
2) made of powershell.
Below are the links for your reference.
Delprof - Batch
Delprof - Powershell
Hope this helps...!!!

Related

Moving Current objects (For me Folders) to the parent of the directory their in using PowerShell

I am trying to search through folders on a share drive for subfolders with "*OutPuts" in the name. These folders should have folders in them but should not have files:
select fullname,#{N='SubDirectories';E={[boolean]($_ |
get-childitem -directory).count}},#{N='SubFiles';E={[boolean]($_ |
get-childitem -file).count}}
When these folders are found I want to move any folders from the output folder to the Project folder (Parent of its Parent). Example:
Starting Condition: C:\AllProjects\Projectfolder\outputs\SubProjectFolder
Wanted Outcome: C:\AllProjects\Projectfolder\SubProjectFolder
Here's the full Code:
code somewhat reformatted for readability ...
$folders=Get-ChildItem C:\AllProjects -recurse -Directory |
where {$_.name -like "*Outputs"} |
select fullname,
#{N='SubDirectories';E={[boolean]($_ |
get-childitem -directory).count}},
#{N='SubFiles';E={[boolean]($_ |
get-childitem -file).count}}
$folders
$folders |
where {$_.subdirectories -eq $true -and $_.subFile -eq $False} |
foreach {
get-childitem |
Move-Item $_ -destination $_.parent.parent}
When ever I run the code the following message comes up:
cmdlet Move-Item at command pipeline position 1
Supply values for the following parameters:
Path[0]:
I'm pretty new to PowerShell so if someone could help break this down for me and tell me what I'm supposed to put here that would be greatly appreciated. Thank you for your time.
UPDATE
*I've tried it with
-Path $_, -Path $_.PsPath, -Path $_.FullName.
I've even tried Get-Item. With the -Path though I now get a message that's a little different:
cmdlet ForEach-Object at command pipeline position 2 Supply values for the following parameters: Process[0]:

How do I remove a Folder in Powershell?

we got a small script that creates folders named by the daily date. I got a script that deletes folders which are older than 30 days.
dir "\\nas\Backup_old\*" -ErrorAction SilentlyContinue |
Where { ((Get-Date) - $_.LastWriteTime).days -gt 30} |
Get-ChildItem -Recurse | Remove-Item -Recurse -Force
Principally it works fine. The Subfolders with contend will be deleted.
But the main folder is still existing and the LastWriteTime is canged to the runtime of the script. The folder is empty. Someone have a idea to solve this problem?
You probably just need to remove the second instance of Get-ChildItem (noting that dir is just an alias for Get-ChildItem), as that is causing it to remove the children of each of the directories returned by the first:
Get-ChildItem "\\nas\Backup_old\*" -ErrorAction SilentlyContinue |
Where-Object { ((Get-Date) - $_.LastWriteTime).days -gt 30} |
Remove-Item -Recurse -Force -WhatIf
Have a look at the WhatIf output and if it looks like it will now remove what you expect, remove -WhatIf.

Powershell: Recursively search a drive or directory for a file type in a specific time frame of creation

I am trying to incorporate Powershell into my everyday workflow so I can move up from a Desktop Support guy to a Systems Admin. One question that I encountered when helping a coworker was how to search for a lost or forgotten file saved in an unknown directory. The pipeline I came up with was:
dir C:\ -Recurse -Filter *.pdf -ErrorAction SilentlyContinue -Force | Out-File pdfs.txt
This code performed exactly how I wanted but now I want to extend this command and make it more efficient. Especially since my company has clients with very messy file management.
What I want to do with this pipeline:
Recursively search for a specific file-type that was created in a specified time-frame. Lets say the oldest file allowed in this search is a file from two days ago.
Save the file to a text file with the columns containing the Filename, FullName(Path), and sorted by the created time in descending order.
What I have so far:
dir C:\ -Recurse -Filter *.pdf -ErrorAction SilentlyContinue -Force | Select-Object Name, FullName | Out-File *pdfs.txt
I really need help on how to create a filter for the time that the file was created. I think I need to use the Where-Object cmdlet right after the dir pipe and before the Select Object pipe but I don't know how to set that up. This is what I wrote: Where-Object {$_.CreationTime <
You're on the right track, to get the files from a specific file creation date range, you can pipe the dir command results to:
Where-Object {$_.CreationTime -ge "06/20/2017" -and $_.CreationTime -le "06/22/2017"}
If you want something more repeatable where you don't have to hard-code the dates everytime and just want to search for files from up to 2 days ago you can set variables:
$today = (Get-Date)
$daysago = (Get-Date).AddDays(-2)
then plugin the variables:
Where-Object {$_.CreationTime -ge $daysago -and $_.CreationTime -le $today}
I'm not near my Windows PC to test this but I think it should work!
See if this helps
dir c:\ -Recurse -Filter *.ps1 -ErrorAction SilentlyContinue -Force | select LastWriteTime,Name | Where-Object {$_.LastWriteTime -ge [DateTime]::Now.AddDays(-2) } | Out-File Temp.txt

Copy the newest file from folder and exclude files by part of the name via PowerShell

I try to copy the newest file from folder (.exe files) by using this type of command:
Get-ChildItem "K:\" -File -include "*.exe" | Where-Object { $_. $_.LastWriteTime like "I don't know which parameter I should type here} Copy-Item -Path $files -Destination "C:\"
I don't want to use complex script with variables and etc. (for now)
Here is folder structure which I have:
Release_OSInstaller_2015_CL287638x64_NoDB.exe
Release_OSInstaller_2015_CL287638x64.exe
Release_OSInstaller_2015_CL287337x64_NoDB.exe
Release_OSInstaller_2015_CL287337x64.exe
And so on. Basically every day a new build is deployed in folder where from I copied the file to my machine (remote).
I need to create a script which will copy the newest build but I want to exclude all files with "NoDB.exe" parameter.
Not sure if it is the fastest way (probably not). But if you are not crawling through huge filesystems
Copy-Item -Path (Get-ChildItem "K:\" -File -include "*.exe" |
Where Name -NotMatch '.*NoDB\.exe$' | Sort-Object -Descending
LastWriteTime | Select-Object -First 1) -Destination "C:\"
should do the trick. (My first answers seems to have been wrong ;) )
And I totally missed the excluding condition so now Martin Brandl Addition is included ^^
In addition to the answer from whatever, you could add a Where condition and skip the NoDBfiles:
Get-ChildItem "K:\" -Filter '*.exe' |
Where Name -NotMatch '.*NoDB\.exe$' |
sort LastWriteTime -Descending |
select -first 1 |
Copy-Item -Destination 'C:\'

Powershell network drive Get-ChildItem issues

Essentially I'm trying to use PowerShell to find files with certain file extensions on a network drive created on or after June 1st of this year. I thought I could do that with the following statement:
Get-ChildItem NETWORKPATH*. -recurse -include .xlsx | Where-Object { $_.CreationTime -ge "06/01/2014" }
I run into 2 problems:
The command only returns files from the root and one folder on the network drive, there's over 100 folders on this network drive
The command returns 3 out of the 5 files created after 6/1/14 and one created well before my creation time date.
I have access to all of the folders on the network drive. When I run Windows 7 search it finds all of the files. It doesn't matter if I run Powershell as administrator or not. It doesn't matter if I run it from my machine (Windows 7) or from one of our 2008 servers. The network drive I'm trying to search through is on a 2003 file server. What am I doing wrong?
Make sure you add a wildcard to your Include parameter. Also you should never use strings for date comparison. See the example of why not here. Try the following:
$testDate = new-object DateTime (2014,06,01)
Get-ChildItem NETWORKPATH*. -recurse -include *.xlsx | Where-Object { $_.CreationTime -ge $testDate }
Also note that files and folders marked as hidden will not show up unless you add a -force to the get-childitem. Not sure if that is part of the issue or not.
gci -path PATH -recurse | where {$_.extension -match "xlsx"} was the silver bullet to all of this.
This is what I use.
$Extensions = '*.xlsx','*.csv','*.xls'
$path = 'Network path'
Get-ChildItem "$path" -Include $Extensions -Recurse -Force | where {$_.CreationTime -gt
[datetime]"10/05/2018"} | Select * | Export-Csv -Path C:\TestExcelfiles.csv -
NoTypeInformation | fl * #format-wide