文章目录
脚本准备
解压MySQL绿色版后,在MySQL根目录下创建以下文件
Ps:可以不建立ps1-lib
目录,但是要对应的删除startup-init.bat
文件中的$ConfigFile
部分以及Pause
之类的方法
./startup-init.bat
<# : Begin batch (batch script is in commentary of powershell v2.0+)
@ECHO OFF
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' (goto UACPrompt) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
exit /B
:gotAdmin
if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
setlocal
powershell -executionpolicy remotesigned -Command "Invoke-Command -ScriptBlock ([scriptblock]::Create($([System.IO.File]::ReadAllText('%~f0')))) -ArgumentList ([string]'%*').split()"
endlocal
goto:eof
#>
#init variables
$CurrentFile=[regex]::Match($MyInvocation.MyCommand.Definition, "ReadAllText\(\`'([\s\S]+?)\`'\)").Groups[1].Value
Set-Location "$CurrentFile\.."
$CurrentPath=Get-Location
#import functions
dir "$CurrentPath\ps1-lib" -Filter "*.ps1" | foreach {
. $_.fullName
#Write-Host "Import $($_.fullName)"
}
# here start your powershell script
$MYSQL_HOME=$CurrentPath
$env:path+=";$MYSQL_HOME;$MYSQL_HOME\bin"
#读取配置文件,并更改配置文件中的配置目录信息,注意,执行后会打乱注释以及keys,如果要保留注释以及配置顺序则自行手动删除以下4行
$ConfigFile=Get-IniContent "$MYSQL_HOME\my.cnf"
$ConfigFile['mysqld']['basedir']="`"$CurrentPath`""
$ConfigFile['mysqld']['datadir']="`"$CurrentPath\data`""
Out-IniFile "Default" "$CurrentPath\my.cnf" -Force $ConfigFile -PassThru
net stop MySQL
mysqld --remove MySQL
sc.exe delete "MySQL"
mysqld --defaults-file="$MYSQL_HOME\my.cnf" --initialize --console --user=mysql --basedir="$MYSQL_HOME" --datadir="$MYSQL_HOME\data"
mysqld --install MySQL --defaults-file="$MYSQL_HOME\my.cnf"
net start MySQL
Pause
./my.cnf
[client]
loose-default-character-set=utf8mb4
port=3306
[mysql]
default-character-set=utf8mb4
[mysqld]
basedir="D:\Development\SQL\MySQL\mysql-8.0.21-winx64"
character-set-server=utf8mb4
datadir="D:\Development\SQL\MySQL\mysql-8.0.21-winx64\data"
default-storage-engine=INNODB
general_log_file="execute_sql_result.log"
general-log=1
log-error=mysql.err
log-output=FILE
long_query_time=10
lower_case_table_names=1
max_connections=151
port=3306
server-id=1
slow_query_log_file="user-slow.log"
slow-query-log=1
table_open_cache=2000
thread_cache_size=10
tmp_table_size=16M
./ps1-lib/Get-IniContent.ps1
Function Get-IniContent {
<#
.Synopsis
Gets the content of an INI file
.Description
Gets the content of an INI file and returns it as a hashtable
.Notes
Author : Oliver Lipkau <oliver@lipkau.net>
Blog : http://oliver.lipkau.net/blog/
Source : https://github.com/lipkau/PsIni
http://gallery.technet.microsoft.com/scriptcenter/ea40c1ef-c856-434b-b8fb-ebd7a76e8d91
Version : 1.0 - 2010/03/12 - Initial release
1.1 - 2014/12/11 - Typo (Thx SLDR)
Typo (Thx Dave Stiff)
#Requires -Version 2.0
.Inputs
System.String
.Outputs
System.Collections.Hashtable
.Parameter FilePath
Specifies the path to the input file.
.Example
$FileContent = Get-IniContent "C:\myinifile.ini"
-----------
Description
Saves the content of the c:\myinifile.ini in a hashtable called $FileContent
.Example
$inifilepath | $FileContent = Get-IniContent
-----------
Description
Gets the content of the ini file passed through the pipe into a hashtable called $FileContent
.Example
C:\PS>$FileContent = Get-IniContent "c:\settings.ini"
C:\PS>$FileContent["Section"]["Key"]
-----------
Description
Returns the key "Key" of the section "Section" from the C:\settings.ini file
.Link
Out-IniFile
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(ValueFromPipeline=$True,Mandatory=$True)]
[string]$FilePath
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath"
$ini = [Ordered]@{}
foreach($line in [System.IO.File]::ReadLines($FilePath))
{
switch -regex ($line)
{
"^\[(.+)\]$" # Section
{
$section = $matches[1]
$ini[$section] = [Ordered]@{}
$CommentCount = 0
}
"^(;.*)$" # Comment
{
if (!($section))
{
$section = "No-Section"
$ini[$section] = [Ordered]@{}
}
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
}
"^(#.*)$" # Comment
{
if (!($section))
{
$section = "No-Section"
$ini[$section] = [Ordered]@{}
}
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = "Comment" + $CommentCount
$ini[$section][$name] = $value
}
"(.+?)\s*=\s*(.*)" # Key
{
if (!($section))
{
$section = "No-Section"
$ini[$section] = [Ordered]@{}
}
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
}
}
}
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $FilePath"
Return $ini
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
./ps1-lib/Out-IniFile.ps1
Function Out-IniFile {
<#
.Synopsis
Write hash content to INI file
.Description
Write hash content to INI file
.Notes
Author : Oliver Lipkau <oliver@lipkau.net>
Blog : http://oliver.lipkau.net/blog/
Source : https://github.com/lipkau/PsIni
http://gallery.technet.microsoft.com/scriptcenter/ea40c1ef-c856-434b-b8fb-ebd7a76e8d91
Version : 1.0 - 2010/03/12 - Initial release
1.1 - 2012/04/19 - Bugfix/Added example to help (Thx Ingmar Verheij)
1.2 - 2014/12/11 - Improved handling for missing output file (Thx SLDR)
#Requires -Version 2.0
.Inputs
System.String
System.Collections.Hashtable
.Outputs
System.IO.FileSystemInfo
.Parameter Append
Adds the output to the end of an existing file, instead of replacing the file contents.
.Parameter InputObject
Specifies the Hashtable to be written to the file. Enter a variable that contains the objects or type a command or expression that gets the objects.
.Parameter FilePath
Specifies the path to the output file.
.Parameter Encoding
Specifies the type of character encoding used in the file. Valid values are "Unicode", "UTF7",
"UTF8", "UTF32", "ASCII", "BigEndianUnicode", "Default", and "OEM". "Unicode" is the default.
"Default" uses the encoding of the system's current ANSI code page.
"OEM" uses the current original equipment manufacturer code page identifier for the operating
system.
.Parameter Force
Allows the cmdlet to overwrite an existing read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions.
.Parameter PassThru
Passes an object representing the location to the pipeline. By default, this cmdlet does not generate any output.
.Example
Out-IniFile $IniVar "C:\myinifile.ini"
-----------
Description
Saves the content of the $IniVar Hashtable to the INI File c:\myinifile.ini
.Example
$IniVar | Out-IniFile "C:\myinifile.ini" -Force
-----------
Description
Saves the content of the $IniVar Hashtable to the INI File c:\myinifile.ini and overwrites the file if it is already present
.Example
$file = Out-IniFile $IniVar "C:\myinifile.ini" -PassThru
-----------
Description
Saves the content of the $IniVar Hashtable to the INI File c:\myinifile.ini and saves the file into $file
.Example
$Category1 = @{“Key1”=”Value1”;”Key2”=”Value2”}
$Category2 = @{“Key1”=”Value1”;”Key2”=”Value2”}
$NewINIContent = @{“Category1”=$Category1;”Category2”=$Category2}
Out-IniFile -InputObject $NewINIContent -FilePath "C:\MyNewFile.INI"
-----------
Description
Creating a custom Hashtable and saving it to C:\MyNewFile.INI
.Link
Get-IniContent
#>
[CmdletBinding()]
Param(
[switch]$Append,
[ValidateSet("Unicode","UTF7","UTF8","UTF32","ASCII","BigEndianUnicode","Default","OEM")]
[Parameter()]
[string]$Encoding = "Unicode",
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[string]$FilePath,
[switch]$Force,
[ValidateNotNullOrEmpty()]
[Parameter(ValueFromPipeline=$True,Mandatory=$True)]
[Hashtable]$InputObject,
[switch]$Passthru
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Writing to file: $Filepath"
if ($append) {$outfile = Get-Item $FilePath}
else {$outFile = New-Item -ItemType file -Path $Filepath -Force:$Force}
if (!($outFile)) {Throw "Could not create File"}
foreach ($i in $InputObject.keys)
{
if (!($($InputObject[$i].GetType().Name) -eq "Hashtable") -and !($($InputObject[$i].GetType().Name) -eq "OrderedDictionary") -and !($($InputObject[$i].GetType().Name) -eq "Dictionary"))
{
#No Sections
Write-Verbose "$($MyInvocation.MyCommand.Name):: Writing key: $i"
Add-Content -Path $outFile -Value "$i=$($InputObject[$i])" -Encoding $Encoding
} else {
#Sections
Write-Verbose "$($MyInvocation.MyCommand.Name):: Writing Section: [$i]"
Add-Content -Path $outFile -Value "[$i]" -Encoding $Encoding
Foreach ($j in $($InputObject[$i].keys | Sort-Object))
{
if ($j -match "^Comment[\d]+") {
Write-Verbose "$($MyInvocation.MyCommand.Name):: Writing comment: $j"
Add-Content -Path $outFile -Value "$($InputObject[$i][$j])" -Encoding $Encoding
} else {
Write-Verbose "$($MyInvocation.MyCommand.Name):: Writing key: $j"
Add-Content -Path $outFile -Value "$j=$($InputObject[$i][$j])" -Encoding $Encoding
}
}
Add-Content -Path $outFile -Value "" -Encoding $Encoding
}
}
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Writing to file: $path"
if ($PassThru) {Return $outFile}
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
./ps1-lib/Pause.ps1
function Pause(){
[System.Console]::Write("按任意键继续...`n")
[void][System.Console]::ReadKey(1)
}
准备完毕
双击执行startup-init.bat
看到A temporary password is generated for
这一块地方则是初始化数据后root
用户的默认密码