Need to put this into a loop - powershell

I have a piece of code that works but I not very elegant, it looks at a directory full of backups, deletes all but the last modified.
$path = "C:\Users\test"
Get-ChildItem "$path\*.*" -include *.data* |
Sort-Object -Descending -Property LastWriteTime |
Select-Object -Skip 1 |Remove-Item -Force
Get-ChildItem "$path\*.*" -include *.enroll* |
Sort-Object -Descending -Property LastWriteTime |
Select-Object -Skip 1 |Remove-Item -Force
Get-ChildItem "$path\*.*" -include *.govern* |
Sort-Object -Descending -Property LastWriteTime |
Select-Object -Skip 1 |Remove-Item -Force
I tried this but it does'nt work,
$sites = #("data","govern","enroll")
$path = "C:\Users\test"
for ($i=0; $i -lt $sites.Length; $i++) {
Get-ChildItem "$path\*.*" -include "*.$sites[$i]*" |
Sort-Object -Descending -Property LastWriteTime |
Select-Object -Skip 1 |Remove-Item -Force
}
Just a nice elegant loop is all I'm looking for.

Related

Get LastAccessTime for each subfolders in a csv folder list

I have a csv ($HomeDir) file like this:
Users,Comments,HomeDir
user1,account1,c:\folder1
user2,account2,c:\folder2
user3,account3,c:\folder3
I get succesfully LastAccessTime for each subfolder in 'HomeDir' column with this code:
$csv = Import-Csv $HomeDir
foreach ($folder in $csv.HomeDir) {
Get-ChildItem $folder -ErrorAction SilentlyContinue |
? {$_.PSIsContainer -eq "True"} |
Select-Object FullName, #{Name='LastAccessTime'; Expression={$_.LastAccessTime.ToString('yyyyMMdd')}} |
Sort-Object -Descending -Property LastAccessTime |
Export-Csv $newcsv -NoTypeInformation -Append
}
The result of $newcsv is:
"FullName","LastAccessTime"
"c:\folder1\Sub1","20201223"
"c:\folder1\Sub1a","20201223"
"c:\folder1\Sub1b","20201223"
"c:\folder2\Sub2","20201218"
"c:\folder2\Sub2a","20201218"
"c:\folder3\Sub3","20201212"
"c:\folder3\Sub3a","20201215"
"c:\folder3\Sub3b","20181215"
"c:\folder3\Sub3c","20201011"
The questions is: is there a way to assign the related User based on corresponding 'Users' column?
It would also be enough for me to get an output like this
"Users","FullName","LastAccessTime"
"user1","c:\felder1\Sub1","20201223"
"user1","c:\folder1\Sub1a","20201223"
"user1","c:\folder1\Sub1b","20201223"
"user2","c:\folder2\Sub2","20201218"
"user2","c:\folder2\Sub2a","20201218"
"user3","c:\folder3\Sub3","20201212"
"user3","c:\folder3\Sub3a","20201215"
"user3","c:\folder3\Sub3b","20181215"
"user3","c:\folder3\Sub3c","20201011"
Thanks in advance
Instead of pulling the HomeDir property out before the loop, just reference it inside the loop and add the Users property to your Fullname and LastAccessTime properties.
$properties = #{Name='User'; Expression={$user}},
'FullName',
#{Name='LastAccessTime'; Expression={$_.LastAccessTime.ToString('yyyyMMdd')}}
Import-Csv $HomeDir | ForEach-Object {
$user = $_.users
Get-ChildItem $_.HomeDir -ErrorAction SilentlyContinue |
Where-Object {$_.PSIsContainer -eq "True"} |
Select-Object $properties |
Sort-Object -Descending -Property LastAccessTime
} | Export-Csv $newcsv -NoTypeInformation
To make it easier to read I put the properties in a variable beforehand. Also, if you are on powershell version 3 or higher you can use -Directory parameter in lieu of $_.PSIsContainer -eq $true. Finally, if you use the Foreach-Object instead of a foreach loop you can pipe to export and not have to use -Append opening and closing the file several times.
$properties = #{Name='User'; Expression={$user}},
'FullName',
#{Name='LastAccessTime'; Expression={$_.LastAccessTime.ToString('yyyyMMdd')}}
Import-Csv $HomeDir | ForEach-Object {
$user = $_.users
Get-ChildItem $_.HomeDir -Directory -ErrorAction SilentlyContinue |
Select-Object $properties | Sort-Object -Descending -Property LastAccessTime
} | Export-Csv $newcsv -NoTypeInformation
I propose my version.
$HomeDir="c:\temp\input.csv"
$newcsv="c:\temp\output.csv"
Import-Csv $HomeDir | %{
#save user name
$User=$_.Users
Get-ChildItem $_.HomeDir -ErrorAction SilentlyContinue -Directory |
Sort LastAccessTime -Descending |
select #{N='Users'; E={$User}}, FullName, #{N='LastAccessTime'; E={$_.LastAccessTime.ToString('yyyyMMdd')}}
} | Export-Csv $newcsv -NoType

PowerShell cmdlet to get a name of recently zipped folder?

I have tried
$latest1 = gci $path -Include *.zip| ? { $_.PSIsContainer } | sort CreationTime -desc | select -f 1
but $latest1 is giving blank output.
The -Include switch will only work if the path ends in \* or when used together with the -Recurse switch.
Since in your case, you are only looking for zip files, I would use the -Filter parameter.
$latest1 = Get-ChildItem $path -Filter '*.zip' -File |
Sort-Object CreationTime -Descending | Select-Object -First 1
For PowerShell version below 3.0 use
$latest1 = Get-ChildItem $path -Filter '*.zip' | Where-Object { !$_.PSIsContainer } |
Sort-Object CreationTime -Descending | Select-Object -First 1
If a zip file was found in the path, $latest should now be a FileInfo object with properties like FullName, BaseName etc.
Try changing your where-object filter or removing it
$latest1 = gci $path -Include *.zip| ? { $_.PSIsContainer -eq $false } | sort CreationTime -desc | select -f 1
$latest1 = gci $path -Include *.zip| | sort CreationTime -desc | select -f 1

Powershell script deleting files despite -Exclude switch

I have the following script where I'm trying to delete all the SQL .bak files except for the last two. When I run it it wipes out everything in the folder. Does -Exclude not work with array values?
$excludefile=get-childitem D:\TempDB | sort lastwritetime | select-object -Last 2 | select-object -Property Name | select-object -expandproperty Name
foreach ($element in $excludefile)
{
$element
remove-item -Path D:\TempDB -Exclude ($element) -Force
}
Is this what you're looking for?
Get-ChildItem D:\TempDB |
Sort-Object LastWriteTime -Descending |
Select-Object -Skip 2 |
Remove-Item -WhatIf
Of course, you can remove -WhatIf if this is what you need.

powershell, check a backup directory and delete old ones only if there is more than one file

Hello to the whole community, I am trying to inspect directories and subdirectories of a folder and if one of them gets more than one file if it has more than 15 days to delete it and leave only the most updated.
but I still do not get the way that if I get a single file despite having more than 15 days old do not touch it as long as there is one more updated within the same directory.
I am currently working with this code
$timeLimit = (Get-Date).AddDays(-15)
Get-ChildItem D:\backup\OldFilesTemp -Directory | where LastWriteTime -lt $timeLimit | Remove-Item -Force -Recurse
grateful for the support they can give me.
You could try something like the following:
$timeLimit = (Get-Date).AddDays(-15)
Get-ChildItem D:\backup\OldFilesTemp | Where-Object { $_.PSIsContainer } | ForEach-Object { Get-ChildItem $_ | Where-Object { -not $PSIsContainer } | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip 1 | Where-Object { $_.LastWriteTime -lt $timeLimit } | Remove-Item -Force }
Replace Remove-Item -Force with Remove-Item -WhatIf to perform a dry run.
$timeLimit = ([System.DateTime]::Today).AddDays(-15) #Dont use Get-Date.
$BackupFolder = "D:\backup\OldFilesTemp"
$FolderList = Get-ChildItem $BackupFolder -Directory -Recurse | Select FullName
Foreach ($Folder in $FolderList)
{
$FileList = Get-ChildItem $Folder -File | Sort-Object -Property LastWriteTime -Descending
$Count = ($FileList | Where-Object -Property LastWriteTime -GE $timeLimit).Count
#Keep an old file if there is only 1 or no recent backups
if ($Count -le 1)
{
$FileList | Where-Object -Property LastWriteTime -LT $timeLimit | Select-Object -Skip 1 | Remove-Item -Force
}
else
{
$FileList | Where-Object -Property LastWriteTime -LT $timeLimit | Remove-Item -Force
}
}
Better do your testing before you deploy on your environment.

How to export Txt/Text file to new folder?

This code does taking newest text file from the folder.
$dir = "C:\logsnew\Application"
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.name
showing like this
C:\Users\kimi> $dir = "C:\logsnew\Application"
C:\Users\kimi> $latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
C:\Users\kimi> $latest.name
4552-4084-63585921993.txt
I would like to put this newest txt file "4552-4084-63585921993.txt" to new folder name "logstop1".
So I try like this:
$dir = "C:\logsnew\Application"
Get-ChildItem -Path $dir |
Sort-Object LastAccessTime -Descending |
Select-Object -First 1 |
Add-Content C:\logsTop1
but this error happens:
Add-Content : Access to the path 'C:\logsTop1' is denied.
How can I fix this problem?
Use Move-Item instead of Add-Content if you want to move the file or Copy-Item if you want to copy it.
Get-ChildItem -Path "C:\logsnew\Application" | Sort-Object LastAccessTime -Descending | Select-Object -First 1 | Move-Item -Destination "C:\logspath1"