安装脚本v3.0:脚本与exe同级,基于PSScriptRoot自动定位,无需硬编码路径

main
haoliang 16 hours ago
parent 9b12c76323
commit 09efa51b0c

@ -1,24 +1,21 @@
# CNC 采集服务 - 一键安装脚本 # CNC 采集服务 - 一键安装脚本
# 需要管理员权限运行 # 脚本与CncCollector.exe放在同一目录右键以管理员身份运行
# 用法: # 用法:
# .\install.ps1 # 默认 InstallUtil 方式(推荐) # .\install.ps1 # 默认 InstallUtil 方式(推荐)
# .\install.ps1 -Method nssm # 使用 NSSM 包装方式
# .\install.ps1 -Method sc # 使用 sc.exe 方式 # .\install.ps1 -Method sc # 使用 sc.exe 方式
param( param(
[ValidateSet("installutil", "nssm", "sc")] [ValidateSet("installutil", "sc")]
[string]$Method = "installutil" [string]$Method = "installutil"
) )
$ErrorActionPreference = "Continue" $ErrorActionPreference = "Continue"
$serviceName = "CncCollector" $serviceName = "CncCollector"
$installDir = "C:\CncCollector" $installDir = $PSScriptRoot
$projectDir = Split-Path -Parent $PSScriptRoot $exePath = Join-Path $installDir "CncCollector.exe"
$binDir = Join-Path $projectDir "bin"
$exePath = Join-Path $binDir "CncCollector.exe"
Write-Host "================================================" -ForegroundColor Cyan Write-Host "================================================" -ForegroundColor Cyan
Write-Host " CNC 机床数据采集服务 - 安装脚本 v2.1" -ForegroundColor Cyan Write-Host " CNC 机床数据采集服务 - 安装脚本 v3.0" -ForegroundColor Cyan
Write-Host " 安装方式: $Method" -ForegroundColor Cyan Write-Host " 安装方式: $Method" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan Write-Host "================================================" -ForegroundColor Cyan
@ -33,42 +30,21 @@ if (-not $isAdmin) {
# 检查 exe 是否存在 # 检查 exe 是否存在
if (-not (Test-Path $exePath)) { if (-not (Test-Path $exePath)) {
Write-Host "[错误] 找不到 CncCollector.exe请先编译项目。" -ForegroundColor Red Write-Host "[错误] 找不到 CncCollector.exe请确认脚本和程序在同一目录。" -ForegroundColor Red
Write-Host " 预期路径: $exePath" -ForegroundColor Yellow Write-Host " 当前目录: $installDir" -ForegroundColor Yellow
Write-Host " 编译命令: dotnet build src\CncCollector\CncCollector.csproj -c Debug" -ForegroundColor Yellow
Write-Host "`n按回车键退出..." -ForegroundColor Gray Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host Read-Host
exit 1 exit 1
} }
# 步骤1创建安装目录 # 检查 collector.json 是否存在
Write-Host "`n[1/5] 创建安装目录: $installDir" -ForegroundColor Green $configFile = Join-Path $installDir "collector.json"
if (-not (Test-Path $installDir)) { if (-not (Test-Path $configFile)) {
New-Item -ItemType Directory -Path $installDir -Force | Out-Null Write-Host "[警告] 找不到 collector.json服务启动后可能无法正常工作。" -ForegroundColor Yellow
}
# 步骤2复制文件
Write-Host "[2/5] 复制程序文件..." -ForegroundColor Green
$files = Get-ChildItem -Path $binDir -Include "*.dll", "*.exe" -Recurse | Where-Object { -not $_.PSIsContainer } | Select-Object -ExpandProperty FullName
$configFiles = @(
(Join-Path $projectDir "collector.json"),
(Join-Path $projectDir "log4net.config")
)
foreach ($f in $files) {
Copy-Item $f $installDir -Force
}
foreach ($f in $configFiles) {
if (Test-Path $f) {
Copy-Item $f $installDir -Force
}
} }
Write-Host " 已复制 $($files.Count) 个程序文件 + 配置文件" -ForegroundColor Gray
$targetExe = Join-Path $installDir "CncCollector.exe" # 步骤1检查并清理旧服务
Write-Host "`n[1/3] 检查旧服务..." -ForegroundColor Green
# 步骤3检查并清理旧服务
Write-Host "[3/5] 检查服务状态..." -ForegroundColor Green
$existingService = Get-Service -Name $serviceName -ErrorAction SilentlyContinue $existingService = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($existingService) { if ($existingService) {
Write-Host " 服务已存在,正在停止并卸载..." -ForegroundColor Yellow Write-Host " 服务已存在,正在停止并卸载..." -ForegroundColor Yellow
@ -77,20 +53,23 @@ if ($existingService) {
Start-Sleep -Seconds 3 Start-Sleep -Seconds 3
} }
# 卸载旧服务 # 卸载旧服务
& $targetExe --uninstall 2>$null & $exePath --uninstall 2>$null
if ($LASTEXITCODE -ne 0) { if ($LASTEXITCODE -ne 0) {
sc.exe delete $serviceName | Out-Null sc.exe delete $serviceName | Out-Null
} }
Start-Sleep -Seconds 2 Start-Sleep -Seconds 2
Write-Host " 旧服务已卸载" -ForegroundColor Gray
} else {
Write-Host " 无旧服务,跳过" -ForegroundColor Gray
} }
# 步骤4安装服务 # 步骤2:安装服务
Write-Host "[4/5] 安装Windows服务方式: $Method..." -ForegroundColor Green Write-Host "[2/3] 安装Windows服务方式: $Method..." -ForegroundColor Green
switch ($Method) { switch ($Method) {
"installutil" { "installutil" {
# 使用内嵌的 ProjectInstaller + InstallUtil # 使用内嵌的 ProjectInstaller + InstallUtil
Write-Host " 使用 InstallUtil 安装(支持原生 ServiceBase 生命周期)..." -ForegroundColor Gray Write-Host " 使用 InstallUtil 安装..." -ForegroundColor Gray
# 查找 InstallUtil.exe # 查找 InstallUtil.exe
$installUtilPath = $null $installUtilPath = $null
@ -109,52 +88,25 @@ switch ($Method) {
} }
if ($installUtilPath) { if ($installUtilPath) {
$result = & $installUtilPath "/LogFile=" "/LogToConsole=true" $targetExe 2>&1 $result = & $installUtilPath "/LogFile=" "/LogToConsole=true" $exePath 2>&1
Write-Host " $result" -ForegroundColor Gray Write-Host " $result" -ForegroundColor Gray
} else { } else {
Write-Host " [警告] 未找到 InstallUtil使用程序内置 --install 安装..." -ForegroundColor Yellow Write-Host " [警告] 未找到 InstallUtil使用程序内置 --install 安装..." -ForegroundColor Yellow
& $targetExe --install & $exePath --install
}
}
"nssm" {
# 使用 NSSM 包装控制台应用
Write-Host " 使用 NSSM 安装服务..." -ForegroundColor Gray
$nssmAvailable = $false
try {
$nssmCheck = Get-Command nssm -ErrorAction SilentlyContinue
if ($nssmCheck) { $nssmAvailable = $true }
} catch {}
if ($nssmAvailable) {
nssm install $serviceName $targetExe
nssm set $serviceName AppDirectory $installDir
nssm set $serviceName DisplayName "CNC 机床数据采集服务"
nssm set $serviceName Description "CNC机床HTTP采集、数据解析、产量跟踪和日终汇总"
nssm set $serviceName Start SERVICE_AUTO_START
nssm set $serviceName AppStdout (Join-Path $installDir "service_stdout.log")
nssm set $serviceName AppStderr (Join-Path $installDir "service_stderr.log")
} else {
Write-Host " [错误] 未找到 NSSM请先安装 NSSM 或使用其他安装方式。" -ForegroundColor Red
Write-Host " 替代方案: .\install.ps1 -Method installutil" -ForegroundColor Yellow
Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host
exit 1
} }
} }
"sc" { "sc" {
# 使用 sc.exe 注册,传 --console 让程序以控制台模式跑在 sc.exe 下 Write-Host " 使用 sc.exe 安装..." -ForegroundColor Gray
Write-Host " 使用 sc.exe 安装服务..." -ForegroundColor Gray sc.exe create $serviceName binPath= "`"$exePath`"" start= auto DisplayName= "CNC 机床数据采集服务" | Out-Null
sc.exe create $serviceName binPath= "`"$targetExe`"" start= auto DisplayName= "CNC 机床数据采集服务" | Out-Null
sc.exe description $serviceName "CNC机床HTTP采集、数据解析、产量跟踪和日终汇总" | Out-Null sc.exe description $serviceName "CNC机床HTTP采集、数据解析、产量跟踪和日终汇总" | Out-Null
} }
} }
# 步骤5配置服务恢复策略失败自动重启 # 步骤3配置恢复策略并启动
Write-Host "[5/5] 配置恢复策略并启动服务..." -ForegroundColor Green Write-Host "[3/3] 配置恢复策略并启动服务..." -ForegroundColor Green
# 配置失败后自动重启第一次1分钟第二次1分钟之后每5分钟 # 失败后自动重启第一次1分钟第二次1分钟之后每5分钟
sc.exe failure $serviceName reset= 0 actions= restart/60000/restart/60000/restart/300000 | Out-Null sc.exe failure $serviceName reset= 0 actions= restart/60000/restart/60000/restart/300000 | Out-Null
# 启动服务 # 启动服务
@ -171,8 +123,6 @@ if ($svc -and $svc.Status -eq 'Running') {
# 尝试调用管理API验证 # 尝试调用管理API验证
try { try {
# 从collector.json读取apiKey
$configFile = Join-Path $installDir "collector.json"
$apiKey = "collector_api_key_2026" $apiKey = "collector_api_key_2026"
if (Test-Path $configFile) { if (Test-Path $configFile) {
$configJson = Get-Content $configFile -Raw | ConvertFrom-Json $configJson = Get-Content $configFile -Raw | ConvertFrom-Json
@ -188,7 +138,6 @@ if ($svc -and $svc.Status -eq 'Running') {
Write-Host " 日志目录: $installDir\logs\" -ForegroundColor Gray Write-Host " 日志目录: $installDir\logs\" -ForegroundColor Gray
Write-Host " 运行日志: collector.log" -ForegroundColor Gray Write-Host " 运行日志: collector.log" -ForegroundColor Gray
Write-Host " 错误日志: collector_error.log" -ForegroundColor Gray Write-Host " 错误日志: collector_error.log" -ForegroundColor Gray
Write-Host " 查看事件日志: Get-EventLog -LogName Application -Source CncCollector -Newest 10" -ForegroundColor Gray
} }
Write-Host "`n常用命令:" -ForegroundColor Cyan Write-Host "`n常用命令:" -ForegroundColor Cyan
@ -196,7 +145,7 @@ Write-Host " 启动: Start-Service $serviceName" -ForegroundColor Gray
Write-Host " 停止: Stop-Service $serviceName" -ForegroundColor Gray Write-Host " 停止: Stop-Service $serviceName" -ForegroundColor Gray
Write-Host " 状态: Get-Service $serviceName" -ForegroundColor Gray Write-Host " 状态: Get-Service $serviceName" -ForegroundColor Gray
Write-Host " 卸载: .\uninstall.ps1" -ForegroundColor Gray Write-Host " 卸载: .\uninstall.ps1" -ForegroundColor Gray
Write-Host " 控制台调试: CncCollector.exe --console" -ForegroundColor Gray Write-Host " 控制台调试: .\CncCollector.exe --console" -ForegroundColor Gray
Write-Host "`n按回车键退出..." -ForegroundColor Gray Write-Host "`n按回车键退出..." -ForegroundColor Gray
Read-Host Read-Host

@ -1,17 +1,18 @@
# CNC 采集服务 - 卸载脚本 # CNC 采集服务 - 卸载脚本
# 需要管理员权限运行 # 脚本与CncCollector.exe放在同一目录右键以管理员身份运行
# 用法: .\uninstall.ps1 # 用法: .\uninstall.ps1
$ErrorActionPreference = "Continue" $ErrorActionPreference = "Continue"
$serviceName = "CncCollector" $serviceName = "CncCollector"
$installDir = "C:\CncCollector" $installDir = $PSScriptRoot
$exePath = Join-Path $installDir "CncCollector.exe"
Write-Host "================================================" -ForegroundColor Cyan Write-Host "================================================" -ForegroundColor Cyan
Write-Host " CNC 机床数据采集服务 - 卸载脚本 v2.1" -ForegroundColor Cyan Write-Host " CNC 机床数据采集服务 - 卸载脚本 v3.0" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan Write-Host "================================================" -ForegroundColor Cyan
# 检查管理员权限 # 检查管理员权限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $isAdmin = ([Security.Principal.WindowsPrincipal] [Windows.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) { if (-not $isAdmin) {
Write-Host "[错误] 请以管理员权限运行此脚本!" -ForegroundColor Red Write-Host "[错误] 请以管理员权限运行此脚本!" -ForegroundColor Red
Write-Host "`n按回车键退出..." -ForegroundColor Gray Write-Host "`n按回车键退出..." -ForegroundColor Gray
@ -31,7 +32,6 @@ if (-not $svc) {
if ($svc.Status -eq 'Running') { if ($svc.Status -eq 'Running') {
Write-Host "[1/3] 停止服务..." -ForegroundColor Green Write-Host "[1/3] 停止服务..." -ForegroundColor Green
Stop-Service -Name $serviceName -Force Stop-Service -Name $serviceName -Force
# 等待服务完全停止
$svc.WaitForStatus('Stopped', (New-TimeSpan -Seconds 30)) $svc.WaitForStatus('Stopped', (New-TimeSpan -Seconds 30))
Start-Sleep -Seconds 2 Start-Sleep -Seconds 2
Write-Host " 服务已停止" -ForegroundColor Gray Write-Host " 服务已停止" -ForegroundColor Gray
@ -39,26 +39,22 @@ if ($svc.Status -eq 'Running') {
Write-Host "[1/3] 服务当前状态: $($svc.Status),无需停止" -ForegroundColor Gray Write-Host "[1/3] 服务当前状态: $($svc.Status),无需停止" -ForegroundColor Gray
} }
# 步骤2卸载服务(优先使用程序自带的 --uninstall降级到 sc.exe # 步骤2卸载服务
Write-Host "[2/3] 卸载服务..." -ForegroundColor Green Write-Host "[2/3] 卸载服务..." -ForegroundColor Green
$targetExe = Join-Path $installDir "CncCollector.exe"
$uninstalled = $false $uninstalled = $false
# 尝试使用 InstallUtil 卸载(通过程序 --uninstall 参数) # 优先使用程序内置 --uninstall
if (Test-Path $targetExe) { if (Test-Path $exePath) {
Write-Host " 尝试使用程序内置卸载..." -ForegroundColor Gray Write-Host " 尝试使用程序内置卸载..." -ForegroundColor Gray
try { try {
& $targetExe --uninstall 2>&1 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray } & $exePath --uninstall 2>&1 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
if ($LASTEXITCODE -eq 0) { if ($LASTEXITCODE -eq 0) { $uninstalled = $true }
$uninstalled = $true
}
} catch { } catch {
Write-Host " 内置卸载失败,尝试 InstallUtil..." -ForegroundColor Yellow Write-Host " 内置卸载失败,尝试 InstallUtil..." -ForegroundColor Yellow
} }
} }
# 降级到 InstallUtil.exe # 降级到 InstallUtil
if (-not $uninstalled) { if (-not $uninstalled) {
$installUtilPath = $null $installUtilPath = $null
$runtimeDir = [System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() $runtimeDir = [System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
@ -69,10 +65,10 @@ if (-not $uninstalled) {
if (Test-Path $fwPath) { $installUtilPath = $fwPath } if (Test-Path $fwPath) { $installUtilPath = $fwPath }
} }
if ($installUtilPath -and (Test-Path $targetExe)) { if ($installUtilPath -and (Test-Path $exePath)) {
Write-Host " 使用 InstallUtil 卸载..." -ForegroundColor Gray Write-Host " 使用 InstallUtil 卸载..." -ForegroundColor Gray
try { try {
& $installUtilPath "/u" "/LogFile=" "/LogToConsole=true" $targetExe 2>&1 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray } & $installUtilPath "/u" "/LogFile=" "/LogToConsole=true" $exePath 2>&1 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
$uninstalled = $true $uninstalled = $true
} catch { } catch {
Write-Host " InstallUtil 卸载失败" -ForegroundColor Yellow Write-Host " InstallUtil 卸载失败" -ForegroundColor Yellow
@ -89,21 +85,22 @@ if (-not $uninstalled) {
Start-Sleep -Seconds 2 Start-Sleep -Seconds 2
# 步骤3验证卸载结果 # 步骤3验证
Write-Host "[3/3] 验证卸载..." -ForegroundColor Green Write-Host "[3/3] 验证卸载..." -ForegroundColor Green
$check = Get-Service -Name $serviceName -ErrorAction SilentlyContinue $check = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if (-not $check) { if (-not $check) {
Write-Host "`n[成功] 服务已完全卸载。" -ForegroundColor Green Write-Host "`n[成功] 服务已完全卸载。" -ForegroundColor Green
# 询问是否清理安装目录 # 询问是否清理日志目录
if (Test-Path $installDir) { $logsDir = Join-Path $installDir "logs"
Write-Host "`n 安装目录 $installDir 仍然存在。" -ForegroundColor Yellow if (Test-Path $logsDir) {
$answer = Read-Host " 是否删除安装目录?(y/N)" Write-Host "`n 日志目录 $logsDir 仍然存在。" -ForegroundColor Yellow
$answer = Read-Host " 是否删除日志目录?(y/N)"
if ($answer -eq 'y' -or $answer -eq 'Y') { if ($answer -eq 'y' -or $answer -eq 'Y') {
Remove-Item -Path $installDir -Recurse -Force Remove-Item -Path $logsDir -Recurse -Force
Write-Host " 安装目录已删除。" -ForegroundColor Green Write-Host " 日志目录已删除。" -ForegroundColor Green
} else { } else {
Write-Host " 安装目录已保留(含日志文件,可手动清理)" -ForegroundColor Gray Write-Host " 日志目录已保留" -ForegroundColor Gray
} }
} }
} else { } else {

Loading…
Cancel
Save