提前准备事项
直接上脚本代码,需要保存为Power shell脚本文件,然后在执行
脚本执行策略
注意:Windows默认是禁止脚本运行的,需要放开一下脚本执行策略
临时更改执行策略(仅对当前会话有效):
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
这只会在当前 PowerShell 会话中临时绕过执行策略,关闭 PowerShell 窗口后恢复默认设置。
永久更改执行策略:
如果你想永久更改执行策略(需要管理员权限),可以运行以下命令:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
脚本代码
本脚本可以实现,在脚本目录下判断有无minio.exe程序,有的话,则自动运行,无的话,则自动下载最新版本并运行。
# 获取当前脚本的路径
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path# 切换到当前脚本目录
cd $scriptDir$url = "https://dl.minio.org.cn/server/minio/release/windows-amd64/minio.exe"
$destination = Join-Path -Path $scriptDir -ChildPath "minio.exe"# 判断minio.exe不存在则自动下载,并显示下载进度
if(-not (Test-Path $destination -PathType Leaf))
{Write-Host "当前目录不存在MinIO,自动开始下载..." -ForegroundColor Green$webRequest = [System.Net.HttpWebRequest]::Create($url)$response = $webRequest.GetResponse()$stream = $response.GetResponseStream()$fileStream = [System.IO.File]::Create($destination)$buffer = New-Object byte[] 8192$totalBytesRead = 0$contentLength = $response.ContentLengthwhile (($bytesRead = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) {$fileStream.Write($buffer, 0, $bytesRead)$totalBytesRead += $bytesReadWrite-Progress -Activity "Downloading MinIO" -Status "$($totalBytesRead / $contentLength * 100)% completed" -PercentComplete (($totalBytesRead / $contentLength) * 100)}$fileStream.Close()$stream.Close()$response.Close()Write-Host "下载完成" -ForegroundColor Green
}
else{Write-Host "当前目录存在MinIO,正在自动执行..." -ForegroundColor Green
}# 设置环境变量到当前用户
Set-ItemProperty -Path "HKCU:\Environment" -Name "MINIO_ROOT_USER" -Value "superadmin"
Set-ItemProperty -Path "HKCU:\Environment" -Name "MINIO_ROOT_PASSWORD" -Value "superadmin"# 设置环境变量到当前线程,可立即生效
[System.Environment]::SetEnvironmentVariable("MINIO_ROOT_USER", "superadmin", [System.EnvironmentVariableTarget]::Process)
[System.Environment]::SetEnvironmentVariable("MINIO_ROOT_PASSWORD", "superadmin", [System.EnvironmentVariableTarget]::Process)# 重启一个新的线程运行MinIO
Start-Process powershell -ArgumentList "-NoExit", "-Command", "./minio.exe server Data --console-address ':9001'"