Skip to content

Instantly share code, notes, and snippets.

@jmelosegui
Last active January 2, 2017 13:26
Show Gist options
  • Save jmelosegui/5b2af145ac3aaea655889afd2554fbed to your computer and use it in GitHub Desktop.
Save jmelosegui/5b2af145ac3aaea655889afd2554fbed to your computer and use it in GitHub Desktop.
Resetting the Root Password on a Windows System
<#
.SYNOPSIS
Automation of the steps described on https://dev.mysql.com/doc/mysql-windows-excerpt/5.7/en/resetting-permissions-windows.html
to reset the Root Password of MySql server on a Windows system.
.PARAMETER MysqlServiceName
The MySql service's name (e.g. MySQL56).
.PARAMETER RootPassword
The password for the root user
#>
Param(
[Parameter(Mandatory=$true)]
[string]$MysqlServiceName,
[Parameter(Mandatory=$true)]
[string]$RootPassword
)
$service = Get-Service -Name $MysqlServiceName
Stop-Service -InputObject $service -force -PassThru | Out-Null
$service.WaitForStatus("Stopped", '00:00:15')
$filePath = Join-Path -Path $PSScriptRoot "mysql-init.txt"
# TODO: request the version to the user and maybe infer the service name,
# if the user has chosen the default installation (e.g. MySQL56)
$mysqlVersion = 575
if($mysqlVersion -gt 575)
{
$sqlCommand = "ALTER USER 'root'@'localhost' IDENTIFIED BY $RootPassword;"
}
else
{
$sqlCommand = "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$RootPassword');"
}
New-Item $filePath -type file -force -value $sqlCommand | Out-Null
$servicePath = Get-WmiObject win32_service | ?{$_.Name -like $MysqlServiceName } | Select PathName
$servicePath = ($servicePath.PathName.Split("--") | Select $_ -First 1).Trim('"', ' ')
& $servicePath --init-file=$filePath --console
# TODO: Is there any way to execute the next lines of code after the Ctrl+C needed to stop the previous command?
Remove-Item $filePath
Start-Service -InputObject $service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment