Question

Currently I have this code -

Set-ExecutionPolicy Unrestricted
$name = (Get-WmiObject win32_bios).SerialNumber.Trim()
$oldname = (Get-WmiObject win32_computersystem).Name.Trim()
IF ($oldname -eq $name){Exit}
Else{ Rename-computer -ComputerName $oldname  -NewName "$name" -force
Start-Sleep -s 5

Restart-Computer}

And I have it set to run as a scheduled task at logon and without the If Else it works perfectly however I don't want it to run every time a user logs in because it will just be a cycle of rebooting. Any help would be greatly appreciated.

Was it helpful?

Solution

I would suggest some changes:

  1. Set-ExecutionPolicy is unnecessary, because if the machine has started processing the script, then the executionpolicy isn't a problem. So remove that, and specify it in the powershell.exe-call instead, like: powershell.exe -executionpolicy unrestricted

  2. Use if($oldname -ne $name) { rename-computer .... } so you can remove the else part. Much cleaner

Try running the modified script below, and report back with the output in the scriptlog.txt-file.

$logpath = "c:\scriptlog.txt"

$name = (Get-WmiObject win32_bios).SerialNumber.Trim()
$oldname = (Get-WmiObject win32_computersystem).Name.Trim()

"NewName is '$name'" | Out-File $logpath -Append
"OldName is '$oldname'" | Out-File $logpath -Append

IF ($oldname -ne $name){
    "If-test TRUE" | Out-File $logpath -Append

    Rename-computer -ComputerName $oldname  -NewName $name -Force
    Start-Sleep -s 5

    Restart-Computer
} else { #I've added the else-part just because of logging.
    "IF-test FALSE" | Out-File $logpath -Append
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top