How to check if local file modified date is different then replace file if it is

Hi, I’m pretty new to powershell and was looking for some assistance

I would like a PowerShell script for log on script to do the following when a user logs on

Check if the following file exists
C:\Users%username%\AppData\LocalLow\Sun\Java\Deployment\security\exception.sites
If it does then compare the modified date of the file with a copy on a server share
If the file on the server share is newer then replace the file

So I can test if the file exists with

Test-Path C:\Users\$env:username\AppData\LocalLow\Sun\Java\Deployment\security\exception.sites

Then I can check the last write time with

Get-Item C:\Users\$env:username\AppData\LocalLow\Sun\Java\Deployment\security\exception.sites | select LastWriteTime

I can also copy the file from the server with

Copy-Item "\\server01\share$\java_exceptions\exception.sites" "C:\Users\$env:username\AppData\LocalLow\Sun\Java\Deployment\security\"

I’m just not sure how to compare the files and string it all together.

Any help would be much appreciated

Darren

You’ve done most of the work. You just need to add your conditionals. Try something like this:

# if the file exists already
if (Test-Path C:\Users\$env:username\AppData\LocalLow\Sun\Java\Deployment\security\exception.sites) {
	# get local file info
	$localFile = Get-Item "C:\Users\$env:username\AppData\LocalLow\Sun\Java\Deployment\security\exception.sites"
	# get remote file info
	$remoteFile = Get-Item "\\server01\share$\java_exceptions\exception.sites"
	
	# if the remote file is newer than the local file
	if ($remoteFile.LastWriteTime -gt $localFile.LastWriteTime)
	{
		Copy-Item "\\server01\share$\java_exceptions\exception.sites" "C:\Users\$env:username\AppData\LocalLow\Sun\Java\Deployment\security\"
	}
}
# if the file does not already exist
else
{
	Copy-Item "\\server01\share$\java_exceptions\exception.sites" "C:\Users\$env:username\AppData\LocalLow\Sun\Java\Deployment\security\"
}

Brilliant!

First run and it works exactly as it should, just need to fire it into login script and test again

Thanks for your help

Live long and prosper PowerShell :slight_smile:

Darren

Only had to add one line to get it working 100%

Just need to add command to create the folder if it didn’t exist to the else statement. Then when Java creates the rest of the structure and files the exception.sites file is already there :smiley:

New-Item -ItemType directory -Path C:\Users\$env:username\AppData\LocalLow\Sun\Java\Deployment\security

Thanks again

Darren

No worries. Glad it worked!