Powershell Seperate Script With Multiple Sessions
Scenario:
I'm a bit new to powershell and I was hoping for a little help here. It
looks like powershell has a session memory leak after running this script.
It stops after trying to delete the 58th log location (56 if I run this
script with a batch file). After doing some research, I found it's a known
bug with microsoft in their import-Pssession command.
The Goal:
The goal is to write up an automation script that will delete folders and
files with an older date than what the user has input (using number of
days) while executing the command.
test1.ps1 contents:
# Gets number of days input by user as a variable
param($NumberOfDays)
If ($NumberOfDays -eq $null) {
Write-Output "Please enter number of days you want to keep logs for"
Write-Output "Example: test1.ps1 30"
Exit
}
elseif ($NumberOfDays -ge 0) {
Write-Output "You have entered $NumberOfDays days to keep logs"
}
#*Note* I use the -whatif switch to see if it will delete the folders and
files without actually deleting them.
dir \\server\dir1\dir2\logs -recurse | where {
((get-date)-$_.creationTime).days -ge $NumberOfDays} | remove-item -force
-recurse -whatif
Write-Output "Exiting Script"
Output After Running Command "test1.ps1 18":
What if: Performing operation "Remove Directory" on Target
"\\server\dir1\dir2\logs\192716".
What if: Performing operation "Remove Directory" on Target
"\\server\dir1\dir2\logs\192981".
What if: Performing operation "Remove Directory" on Target
"\\server\dir1\dir2\logs\193046".
What if: Performing operation "Remove Directory" on Target
"\\server\dir1\dir2\logs\193063".
What if: Performing operation "Remove Directory" on Target
"\\server\dir1\dir2\logs\193065".
What if: Performing operation "Remove Directory" on Target
"\\server\dir1\dir2\logs\191335".
Freezes once it gets to the 58th folder (should be a total of 93 folders)
The Question:
I want to know how I can get this dir command to:
execute a max number of 20 delete commands
run a check to see if there was more folders/files to delete
if there was more folders/files to delete, close the powershell session
and open a new one, rerun the dir/del command with the check.
elsif no more folders/files to delete, exit script.
P.S. if there is a better algorithm than steps 1-4, please feel free to
add useful input.
No comments:
Post a Comment