Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Declare variable storing target user's username.
- $User = "TEST"
- # Set working directory to C:\Users\$User\AppData\Local\Temp.
- Set-Location -LiteralPath C:\Users\$User\AppData\Local\Temp
- # Declare variable storing a timestamp of 24 hours ago.
- $CurrentTimeMinus24Hours = (Get-Date).AddHours(-24)
- # Declare variable (array) storing list of files in temp directory.
- $Files = @(Get-ChildItem -Path . -File)
- # Declare variable storing Log file.
- $Log = "C:\TempFileDeletionLog.log"
- # Function for getting a precise DateTime string for use in logging. It will be formatted for your timezone.
- function Get-DateTimeString {
- Get-Date -Format O
- }
- <#
- Function to test whether or not a file is locked. Credit to Ben Baird here:
- https://social.technet.microsoft.com/Forums/windowsserver/en-US/74ea3752-9403-4296-ab98-d03fcc12b608/how-to-check-to-see-if-a-file-is-openlocked-before-trying-to-copy-it?forum=winserverpowershell
- #>
- function Test-FileLock
- {
- param
- (
- [parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
- [Alias("FullName")]
- [string]$Path,
- [switch]$PassThru
- )
- begin {}
- Process
- {
- $oFile = New-Object System.IO.FileInfo $Path
- if ((Test-Path -Path $Path) -eq $false)
- {
- if ($PassThru.IsPresent -eq $false)
- {
- $false
- }
- return
- }
- try
- {
- $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
- if ($oStream)
- {
- $oStream.Close()
- }
- if ($PassThru.IsPresent -eq $false)
- {
- $false
- }
- else
- {
- Get-Item $Path
- }
- }
- catch
- {
- # file is locked by a process.
- if ($PassThru.IsPresent -eq $false)
- {
- $true
- }
- }
- }
- end {}
- }
- # ForEach loop that will test for multiple conditions, take actions based on those conditions, and log the results based on those actions for every file in the $Files array.
- $ErrorActionPreference = "SilentlyContinue"
- foreach ($File in $Files) {
- if ($File.LastWriteTime -lt $CurrentTimeMinus24Hours) {
- $File | Test-FileLock -PassThru | Remove-Item
- if ((Get-Item $File).Exists) {
- Add-Content -Path $Log -Value "$(Get-DateTimeString)> C:\$User\AppData\Local\Temp\$File was not deleted because it was locked."
- } else {
- Add-Content -Path $Log -Value "$(Get-DateTimeString)> C:\$User\AppData\Local\Temp\$File has been deleted."
- }
- } else {
- Add-Content -Path $Log -Value "$(Get-DateTimeString)> C:\$User\AppData\Local\Temp\$File was not deleted because it has been written to in the last 24 hours."
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment