I've got into a bit of a rut with this and I'm hoping someone can help me nail it:
I've been tasked with dropping a custom settings file into the roaming profile of the logged on user of all workstations. The file would need to deployed if one of the 2 conditions are correct:
- The file is not there.
- The size of the file is smaller than that which is being deployed.
The deployment method is good, but the detection method is giving me a headache.
Andy Dawson's blog got me most of the way there, it's the file size (length) bit that's not working for me.
So, my first script went like this:
Part 1: Get logged on user
Function CurrentUser {
$LoggedInUser = get-wmiobject win32_computersystem | select username
$LoggedInUser = [string]$LoggedInUser
$LoggedInUser = $LoggedInUser.split(“=”)
$LoggedInUser = $LoggedInUser[1]
$LoggedInUser = $LoggedInUser.split(“}”)
$LoggedInUser = $LoggedInUser[0]
$LoggedInUser = $LoggedInUser.split(“\”)
$LoggedInUser = $LoggedInUser[1]
Return $LoggedInUser
}
Part 2: Assign User Path and Targetfile variables
$user = CurrentUser
$path = C:\Users\" $user "\AppData\Roaming\folder\folder\settings.cfg"
$targetfile = Get-Item $path
Part 3: Detect path exists and check filesize
if (( Test-Path $targetfile) -and ((Get-Item $targetfile).length -ge 26831))
{
Write-Host "installed"
}
else
{
Write-Host "NOT installed"
}
This works if condition 1 is satisfied, but if not the detection method would fail because $path
variable and therefore $targetfile
could not be populated.
I was using the $targetfile
variable because other methods of getting .length seemed to be returning the character count (therefore string length) rather than the intended file size value.
Back to the drawing board. It seems I need to only commence with the rest of the script, assigning the is Condition 1 is NOT satisfied, so...
...My second (current) script goes like this:
Part 1: Get logged on user
UNCHANGED THIS BIT'S FINE, BECAUSE IS STOLE IT :)
Part 2: Assign User and Userpath variables (simplified as this one will always be found)
$user = CurrentUser
$Userpath = "C:\Users\" $user
Part 3: If path is NOT there state exists and check filesize
if (-not (Test-Path "$Userpath\AppData\Roaming\folder\folder\settings.cfg"))
{
Write-Host "NOT installed"
}
elseif.....
...and this is where the rut sets in! I want the second check to be along the lines of ((Get-Item $targetfile).length -ge 26831))
as before but I just can't seem to get the syntax/logic right here.
Any help greatly appreciated!!!
CodePudding user response:
You'll want to test whether the file doesn't exist OR is to small:
if(-not(Test-Path $targetFile) -or (Get-Item $targetFile).Length -lt $newFileSize){
# File either doesn't exist or is incomplete - go ahead and copy the new config file to $targetFile
Copy-Item .\path\to\reference\config.cfg -Destination $targetFile -Force
}