1

I have a script that deletes anything older than a set time. I want to replicate this for other delete jobs with different times and different folders

I am new to Powershell, this script was written with a lot of google assistance

$Minutes=[DateTime]::Now.AddMinutes(-5)
$Timestamp = Get-Date -Format "yyyy-MM-ddTHH-mm-ss"
$Log = "C:\test\logs\_" + $Timestamp + ".log"

Start-Transcript -path $Log -append -Force -NoClobber 
try {

function Write-Log($string)
{    
    $outStr = "" + $Timestamp +" "+$string

    Write-Output $outStr 

   }

  Write-Log "------------ Start of Log  ------------"
  #Write-Log ""

  # get all file objects to use in erasing
  $files=Get-ChildItem -path 'c:\test\*' -Include *.* -Recurse |
  Where-Object{ $_.LastWriteTime -lt $Minutes}

# Remove the file and its folder.
$files |
    ForEach-Object{
        Write-Log " Deleting File --> $_."; Remove-Item $_.Fullname  
    }

# output statistics
Write-Output "**********************"
Write-Output "Number of old files deleted: $($files.Count)"
Write-Log "------------- End of Log -------------"
} 
catch {
Write-Error -Message "Something bad happened!" -ErrorAction Stop
}

Stop-Transcript

1 Answer 1

2

Welcome to PowerShell, and good for you on the web search approach. Yet remember, it is vital that being new to this, that you take some time to ramp up on all the basic before you diving into this space, in order to avoid as much undue confusion, frustration, etc., that you will encounter.

You really need to do this also to understand what you need, and to avoid having / causing catastrophic issues to your system and or your enterprise. Of course, never run any code you do not fully understand, and always list out your goals and address them one at a time to make sure you are getting the results you'd expect.

Live on YouTube, Microsoft Virtual Academy, Microsoft Learn, TechNet Virtual Labs, MS Channel9, leveraging all the videos you can consume; then hit the documentation/help files, and all the no cost eBooks all over the web.

As for ...

I want to replicate this for other delete jobs with different times and different folders

… this is why functions and parameters exist.

Function Start-DeleteJob
{
    [CmdletBinding()]
    [Alias('sdj')]

    Param
    (
        $JobTime,
        $JobFolder
    )

    # Code begins here

}

So, spend time researching PowerShell functions, advance functions, and parameters.

Get-Help -Name About_*Functions*

Get-Help -Name About_*Parameters*
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I will do some research around your suggestions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.