{"加载配置文件时出错: 参数“exePath”无效。\r\n参数名: exePath"}

本文介绍了一种在配置文件与可执行文件不在同一目录下时读取config文件的方法。通过使用ExeConfigurationFileMap和OpenMappedExeConfiguration,可以灵活地定位并读取不同路径下的配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用System.Configuration.ConfigurationManager.OpenExeConfiguration(string exePath)方法读取config文件时,配置文件与可执行文件位于同一目录中。如图

如果配置文件与可执行文件位于同一目录中,那怎么读取呢?用下面的方法可以实现。

 ExeConfigurationFileMap webconfigMap = new ExeConfigurationFileMap();
                webconfigMap.ExeConfigFilename =CreateConfig(adsWebConfigPath);
                Configuration webconfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(webconfigMap, ConfigurationUserLevel.None);//不需要后缀名
                                                                                                                           //根据Key读取<add>元素的Value
                string webConnectionStrings = webconfig.AppSettings.Settings["ConnectionStrings"].Value;
                string webBussinessServiceAddress = webconfig.AppSettings.Settings["BussinessServiceAddress"].Value;
    private static string CreateConfig(string configFile)
        {
            try
            {
                //string configFile = @"D:\wk\config\Webs.config";// + @"app.config";
                if (!File.Exists(configFile))
                {
                    string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration>\r\n</configuration>";
                    using (StreamWriter sw = new StreamWriter(configFile))
                    {
                        sw.Write(xml);
                    }
                }
                return configFile;
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                throw;
            }
        }

 

我咋感觉 这次输入系统没反应呢?PS C:\Users\Administrator> function Get-CurlVersion { >> <# >> .SYNOPSIS >> 获取已安装curl的版本信息 >> >> .DESCRIPTION >> 返回curl的版本号、协议支持等详细信息 >> >> .EXAMPLE >> PS> Get-CurlVersion >> 7.88.1 >> #> >> [CmdletBinding()] >> param() >> >> try { >> if (-not $script:ModuleInitialized) { >> Initialize-Module | Out-Null >> } >> >> $curlExe = if ($script:CurlPath) { >> $exeName = if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" } >> Join-Path $script:CurlPath $exeName >> } else { >> throw "curl路径未配置" >> } >> >> if (-not (Test-Path $curlExe)) { >> throw "curl可执行文件不存在: $curlExe" >> } >> >> # 执行curl --version获取详细信息 >> $versionInfo = & $curlExe --version 2>&1 >> if ($LASTEXITCODE -ne 0) { >> throw "curl版本获取失败: $versionInfo" >> } >> >> # 解析版本号 >> $versionLine = $versionInfo | Select-Object -First 1 >> if ($versionLine -match 'curl\s+(\d+\.\d+\.\d+)') { >> $version = $matches[1] >> } else { >> $version = "未知版本" >> } >> >> return [PSCustomObject]@{ >> Version = $version >> FullInfo = $versionInfo -join "`n" >> Executable = $curlExe >> LastChecked = (Get-Date) >> } >> } catch { >> Write-Error "获取curl版本失败: $_" >> return $null >> } >> } >> PS C:\Users\Administrator> function Set-CurlPath { >> <# >> .SYNOPSIS >> 设置自定义curl路径 >> >> .DESCRIPTION >> 验证并设置新的curl安装路径 >> >> .EXAMPLE >> PS> Set-CurlPath -Path "C:\Program Files\curl\bin" >> #> >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [ValidateScript({ >> if (-not (Test-Path $_)) { >> throw "路径不存在: $_" >> } >> $exe = Join-Path $_ $(if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" }) >> if (-not (Test-Path $exe)) { >> throw "路径不包含curl可执行文件: $exe" >> } >> $true >> })] >> [string]$Path >> ) >> >> try { >> if (-not $script:ModuleInitialized) { >> Initialize-Module | Out-Null >> } >> >> # 更新配置 >> $script:Config.CurlPath = $Path >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> >> # 重载路径 >> $script:CurlPath = $Path >> Write-Host "✅ curl路径更新为: $Path" -ForegroundColor Green >> >> # 验证新路径 >> $version = Get-CurlVersion >> if ($version) { >> Write-Host "当前curl版本: $($version.Version)" -ForegroundColor Cyan >> } >> >> return $true >> } catch { >> Write-Error "设置curl路径失败: $_" >> return $false >> } >> } >> PS C:\Users\Administrator> function Install-Curl { >> # ... 之前的安装代码 ... >> >> # 安装后添加版本验证 >> $exePath = Join-Path $installDir $(if ($platform -eq "Windows") { "curl.exe" } else { "curl" }) >> if (-not (Test-Path $exePath)) { >> throw "安装后curl可执行文件不存在: $exePath" >> } >> >> # 验证版本 >> $versionInfo = & $exePath --version 2>&1 >> if ($LASTEXITCODE -ne 0) { >> throw "安装后curl验证失败: $versionInfo" >> } >> >> Write-Verbose "curl安装成功: $($versionInfo[0])" >> return $installDir >> } >> PS C:\Users\Administrator> # 模块主文件内容保持不变... >> >> # 初始化模块后添加版本检查 >> function Initialize-Module { >> try { >> # ... 之前的初始化代码 ... >> >> # 验证curl可执行性 >> $exePath = Join-Path $script:CurlPath $(if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" }) >> if (-not (Test-Path $exePath)) { >> Write-Warning "配置的curl路径无效: $exePath" >> $script:Config.CurlPath = Find-CurlPath >> $script:CurlPath = $script:Config.CurlPath >> } >> >> # 测试curl基本功能 >> $null = Get-CurlVersion -ErrorAction Stop >> Write-Verbose "模块初始化完成, curl路径: $script:CurlPath" >> >> return $true >> } catch { >> Write-Warning "模块初始化失败: $_" >> return $false >> } >> } >> PS C:\Users\Administrator> # ... 之前的安装脚本 ... >> >> # ===== 保存所有公共函数 ===== >> # Get-CurlPath.ps1 (已存在) >> # Get-CurlVersion.ps1 >> $getCurlVersionContent = @' >> function Get-CurlVersion { >> # 上面的完整实现 >> } >> '@ >> Set-Content -Path "$publicDir\GetCurlVersion.ps1" -Value $getCurlVersionContent -Force >> >> # Set-CurlPath.ps1 >> $setCurlPathContent = @' >> function Set-CurlPath { >> # 上面的完整实现 >> } >> '@ >> Set-Content -Path "$publicDir\SetCurlPath.ps1" -Value $setCurlPathContent -Force >> >> # Invoke-SecureDownload.ps1 (已存在) >> >> # ===== 保存所有私有函数 ===== >> # InstallCurl.ps1 (已存在) >> # FindCurlPath.ps1 >> $findCurlPathContent = @' >> function Find-CurlPath { >> # 上面的完整实现 >> } >> '@ >> Set-Content -Path "$privateDir\FindCurlPath.ps1" -Value $findCurlPathContent -Force >> >> # GetPlatform.ps1 >> $getPlatformContent = @' >> function Get-Platform { >> # 从Initialize-Module移出的实现 >> } >> '@ >> Set-Content -Path "$privateDir\GetPlatform.ps1" -Value $getPlatformContent -Force >> >> # ... 其余安装脚本不变 ... >> PS C:\Users\Administrator> # 测试模块 >> if (Get-Module CurlTools) { >> Write-Host "✅ CurlTools 模块安装成功!" -ForegroundColor Green >> >> try { >> # 测试路径获取 >> $curlPath = Get-CurlPath >> Write-Host "Curl路径: $curlPath" >> >> # 测试版本获取 >> $version = Get-CurlVersion >> if ($version) { >> Write-Host "Curl版本: $($version.Version)" >> Write-Host "支持协议: $($version.FullInfo | Select-String 'Protocols:' | ForEach-Object { $_.ToString().Split(':')[1].Trim() })" >> } >> >> # 测试路径设置 >> $newPath = "C:\Program Files\Git\usr\bin" >> if (Test-Path $newPath) { >> Set-CurlPath -Path $newPath -Verbose >> } >> >> # 测试下载功能 >> $testUrl = "https://raw.githubusercontent.com/PowerShell/PowerShell/master/README.md" >> $outputPath = Join-Path $env:TEMP "PowerShell_README_$(Get-Date -Format 'yyyyMMddHHmmss').md" >> Invoke-SecureDownload -Url $testUrl -OutputPath $outputPath >> Write-Host "✅ 测试下载成功: $outputPath" -ForegroundColor Green >> } >> catch { >> Write-Warning "⚠️ 测试失败: $_" >> } >> } >> PS C:\Users\Administrator>
08-13
PS C:\Users\Administrator> param( >> [Parameter(Mandatory=$true)] >> [ValidateSet("Install", "Uninstall", "Start", "Stop")] >> [string]$Action >> ) >> >> $serviceName = "ProjectEcosystemManager" >> $scriptPath = "E:\ProjectEcosystem\ProjectMonitor\Scripts\ProjectEcosystemManager.ps1" >> >> # 验证脚本是否存在 >> if (-not (Test-Path $scriptPath)) { >> Write-Host "❌ 主脚本不存在: $scriptPath" -ForegroundColor Red >> exit 1 >> } >> >> # 获取PowerShell可执行文件完整路径 >> $powershellExe = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe" >> if (-not (Test-Path $powershellExe)) { >> Write-Host "❌ PowerShell可执行文件不存在: $powershellExe" -ForegroundColor Red >> exit 1 >> } >> >> switch ($Action) { >> "Install" { >> # 检查服务是否已存在 >> $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue >> if ($service) { >> Write-Host "ℹ️ 服务已存在,先卸载..." -ForegroundColor Yellow >> & $PSCommandPath -Action Uninstall >> Start-Sleep -Seconds 3 >> } >> >> # 关键修复:正确的二进制路径格式 >> $binaryPath = "`"$powershellExe`" -ExecutionPolicy Bypass -File `"$scriptPath`" -WindowStyle Hidden" >> >> # 使用 New-Service 的正确方式 >> try { >> $service = New-Service -Name $serviceName ` >> -BinaryPathName $binaryPath ` >> -DisplayName "Project Ecosystem Manager" ` >> -Description "自动化管理项目生态系统" ` >> -StartupType Automatic ` >> -ErrorAction Stop >> >> Write-Host "✅ 服务创建成功" -ForegroundColor Green >> } >> catch { >> Write-Host "❌ 服务创建失败: $_" -ForegroundColor Red >> exit 1 >> } >> >> # 授予服务必要的权限 >> try { >> $sdResult = sc.exe sdset $serviceName "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)" >> if ($LASTEXITCODE -ne 0) { >> throw $sdResult >> } >> Write-Host "✅ 服务权限设置成功" -ForegroundColor Green >> } >> catch { >> Write-Host "❌ 服务权限设置失败: $_" -ForegroundColor Red >> } >> >> # 启动服务 >> try { >> Start-Service -Name $serviceName -ErrorAction Stop >> Write-Host "✅ 服务启动成功" -ForegroundColor Green >> } >> catch { >> Write-Host "❌ 服务启动失败: $_" -ForegroundColor Red >> # 提供诊断信息 >> Write-Host "`n=== 诊断信息 ===" >> Write-Host "服务路径: $binaryPath" >> Write-Host "测试命令: $binaryPath -TestMode" >> exit 1 >> } >> } >> >> "Uninstall" { >> $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue >> if ($service) { >> try { >> if ($service.Status -eq 'Running') { >> Stop-Service -Name $serviceName -Force -ErrorAction Stop >> } >> >> # 使用SC命令删除服务更可靠 >> $delResult = sc.exe delete $serviceName >> if ($LASTEXITCODE -ne 0) { >> throw $delResult >> } >> Write-Host "✅ 服务卸载成功" -ForegroundColor Green >> } >> catch { >> Write-Host "❌ 服务卸载失败: $_" -ForegroundColor Red >> } >> } >> else { >> Write-Host "ℹ️ 服务不存在,无需卸载" -ForegroundColor Cyan >> } >> } >> >> "Start" { >> try { >> Start-Service -Name $serviceName -ErrorAction Stop >> Write-Host "✅ 服务已启动" -ForegroundColor Green >> } >> catch { >> Write-Host "❌ 服务启动失败: $_" -ForegroundColor Red >> } >> } >> >> "Stop" { >> try { >> Stop-Service -Name $serviceName -Force -ErrorAction Stop >> Write-Host "✅ 服务已停止" -ForegroundColor Yellow >> } >> catch { >> Write-Host "❌ 服务停止失败: $_" -ForegroundColor Red >> } >> } >> } >> 位于命令管道位置 1 的 cmdlet 请为以下参数提供值: Action: # 配置默认值 无法对参数“Action”执行参数验证。参数“# 配置默认值”不属于 ValidateSet 属性指定的集合“Install,Uninstall,Start,Stop” 。请提供一个此集合中的参数,然后重试此命令。 + CategoryInfo : InvalidData: (:) [],ParentContainsErrorRecordException + FullyQualifiedErrorId : ParameterArgumentValidationError PS C:\Users\Administrator> $global:projectRoot = "E:\ProjectEcosystem" PS C:\Users\Administrator> $global:ecosystemConfig = Join-Path $projectRoot "Config\EcosystemConfig.xml" PS C:\Users\Administrator> PS C:\Users\Administrator> # 确保日志目录存在 PS C:\Users\Administrator> $global:logDir = Join-Path $projectRoot "Logs" PS C:\Users\Administrator> if (-not (Test-Path $logDir)) { >> New-Item -ItemType Directory -Path $logDir -Force | Out-Null >> } PS C:\Users\Administrator> PS C:\Users\Administrator> # 启动日志记录 PS C:\Users\Administrator> $global:serviceLog = Join-Path $logDir "Service_$(Get-Date -Format 'yyyyMMdd').log" PS C:\Users\Administrator> Start-Transcript -Path $global:serviceLog -Append -ErrorAction SilentlyContinue 已启动脚本,输出文件为 E:\ProjectEcosystem\Logs\Service_20250813.log PS C:\Users\Administrator> PS C:\Users\Administrator> Write-Host "=== 生态系统管理服务启动于 $(Get-Date) ===" === 生态系统管理服务启动于 08/13/2025 21:18:35 === PS C:\Users\Administrator> PS C:\Users\Administrator> # 加载配置(带默认值) PS C:\Users\Administrator> function Load-Configuration { >> param( >> [string]$ConfigPath = $global:ecosystemConfig >> ) >> >> # 默认配置结构 >> $defaultConfig = [PSCustomObject]@{ >> Monitoring = [PSCustomObject]@{ >> Interval = 60 # 默认60秒 >> AlertEmail = "admin@example.com" >> } >> Projects = @( >> [PSCustomObject]@{ >> Name = "APIServer" >> Type = "NodeJS" >> RepoUrl = "https://github.com/yourrepo/api-server.git" >> StartCommand = "npm start" >> } >> # 其他项目默认配置... >> ) >> } >> >> if (Test-Path $ConfigPath) { >> try { >> $loadedConfig = Import-Clixml -Path $ConfigPath -ErrorAction Stop >> Write-Host "✅ 配置加载成功" >> >> # 合并默认值和加载的配置 >> foreach ($prop in $defaultConfig.PSObject.Properties) { >> if (-not $loadedConfig.PSObject.Properties[$prop.Name]) { >> $loadedConfig | Add-Member -NotePropertyName $prop.Name -NotePropertyValue $prop.Value >> } >> } >> >> return $loadedConfig >> } >> catch { >> Write-Host "❌ 配置加载失败: $_" -ForegroundColor Red >> return $defaultConfig >> } >> } >> else { >> Write-Host "⚠️ 配置文件不存在,使用默认配置" -ForegroundColor Yellow >> return $defaultConfig >> } >> } PS C:\Users\Administrator> PS C:\Users\Administrator> $global:config = Load-Configuration ⚠️ 配置文件不存在,使用默认配置 PS C:\Users\Administrator> PS C:\Users\Administrator> # 主监控循环(带默认值处理) PS C:\Users\Administrator> while ($true) { >> try { >> # 确保监控间隔有效 >> $interval = $global:config.Monitoring.Interval >> if (-not $interval -or $interval -le 0) { >> $interval = 60 >> Write-Host "⚠️ 使用默认监控间隔: 60秒" -ForegroundColor Yellow >> } >> >> # 项目监控逻辑 >> foreach ($project in $global:config.Projects) { >> Monitor-Project -ProjectName $project.Name -StartCommand $project.StartCommand >> } >> >> # 等待下一个监控周期 >> Start-Sleep -Seconds $interval >> } >> catch { >> Write-Host "全局错误: $_" -ForegroundColor Red >> Start-Sleep -Seconds 10 # 错误后短暂等待 >> } >> } 全局错误: 无法将“Monitor-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 全局错误: 无法将“Monitor-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 全局错误: 无法将“Monitor-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 全局错误: 无法将“Monitor-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 PS C:\Users\Administrator> PS C:\Users\Administrator> Stop-Transcript 已停止脚本,输出文件为 E:\ProjectEcosystem\Logs\Service_20250813.log PS C:\Users\Administrator> function Test-ServiceInstallation { >> param( >> [string]$ServiceName = "ProjectEcosystemManager" >> ) >> >> # 检查服务是否存在 >> $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue >> if (-not $service) { >> Write-Host "❌ 服务未安装: $ServiceName" -ForegroundColor Red >> return $false >> } >> >> # 获取服务配置 >> $serviceConfig = sc.exe qc $ServiceName >> if ($LASTEXITCODE -ne 0) { >> Write-Host "❌ 无法获取服务配置" -ForegroundColor Red >> return $false >> } >> >> # 解析二进制路径 >> $binaryLine = $serviceConfig | Where-Object { $_ -match "BINARY_PATH_NAME" } >> if (-not $binaryLine) { >> Write-Host "❌ 找不到二进制路径配置" -ForegroundColor Red >> return $false >> } >> >> $binaryPath = $binaryLine -split ":", 2 | Select-Object -Last 1 | ForEach-Object { $_.Trim() } >> Write-Host "服务路径: $binaryPath" >> >> # 测试路径是否有效 >> if ($binaryPath -match '^"(.+?)" (.+)$') { >> $exePath = $matches[1] >> $arguments = $matches[2] >> >> if (Test-Path $exePath) { >> Write-Host "✅ 可执行文件存在: $exePath" -ForegroundColor Green >> >> # 测试执行 >> try { >> Write-Host "`n=== 测试执行 ===" >> & $exePath $arguments -Command "Write-Host '测试成功'; exit 0" >> >> if ($LASTEXITCODE -eq 0) { >> Write-Host "✅ 测试执行成功" -ForegroundColor Green >> return $true >> } >> else { >> Write-Host "❌ 测试执行失败 (退出码: $LASTEXITCODE)" -ForegroundColor Red >> } >> } >> catch { >> Write-Host "❌ 测试执行异常: $_" -ForegroundColor Red >> } >> } >> else { >> Write-Host "❌ 可执行文件不存在: $exePath" -ForegroundColor Red >> } >> } >> else { >> Write-Host "❌ 无法解析二进制路径格式" -ForegroundColor Red >> } >> >> return $false >> } >> >> function Repair-ServicePath { >> param( >> [string]$ServiceName = "ProjectEcosystemManager", >> [string]$CorrectBinaryPath >> ) >> >> # 检查服务是否存在 >> $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue >> if (-not $service) { >> Write-Host "❌ 服务未安装: $ServiceName" -ForegroundColor Red >> return >> } >> >> # 停止服务 >> if ($service.Status -eq 'Running') { >> try { >> Stop-Service -Name $ServiceName -Force -ErrorAction Stop >> Write-Host "✅ 服务已停止" -ForegroundColor Green >> Start-Sleep -Seconds 2 >> } >> catch { >> Write-Host "❌ 停止服务失败: $_" -ForegroundColor Red >> return >> } >> } >> >> # 修改服务配置 >> try { >> $result = sc.exe config $ServiceName binPath= "$CorrectBinaryPath" >> if ($LASTEXITCODE -ne 0) { >> throw $result >> } >> Write-Host "✅ 服务路径更新成功" -ForegroundColor Green >> >> # 启动服务 >> Start-Service -Name $ServiceName -ErrorAction Stop >> Write-Host "✅ 服务已启动" -ForegroundColor Green >> } >> catch { >> Write-Host "❌ 服务路径更新失败: $_" -ForegroundColor Red >> } >> } >> >> # 使用示例: >> # $correctPath = "`"$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe`" -ExecutionPolicy Bypass -File `"E:\ProjectEcosystem\ProjectMonitor\Scripts\ProjectEcosystemManager.ps1`" -WindowStyle Hidden" >> # Test-ServiceInstallation >> # Repair-ServicePath -CorrectBinaryPath $correctPath >> PS C:\Users\Administrator> # 1. 保存修复后的主脚本 >> $scriptPath = "E:\ProjectEcosystem\ProjectMonitor\Scripts\ProjectEcosystemManager.ps1" >> $ecosystemManagerScript = @' >> # 包含所有修复的主脚本内容 >> '@ >> Set-Content -Path $scriptPath -Value $ecosystemManagerScript -Encoding UTF8 >> >> # 2. 保存服务安装脚本 >> $serviceScriptPath = "E:\Install-EcosystemService.ps1" >> $serviceScript = @' >> # 终极修复的服务安装脚本内容 >> '@ >> Set-Content -Path $serviceScriptPath -Value $serviceScript -Encoding UTF8 >> >> # 3. 卸载旧服务 >> & $serviceScriptPath -Action Uninstall >> >> # 4. 安装新服务 >> & $serviceScriptPath -Action Install >> >> # 5. 验证服务状态 >> $service = Get-Service -Name "ProjectEcosystemManager" -ErrorAction SilentlyContinue >> if ($service.Status -ne 'Running') { >> # 使用故障排除工具修复 >> .\ServiceTroubleshooter.ps1 >> >> # 手动启动 >> Start-Service -Name "ProjectEcosystemManager" -ErrorAction SilentlyContinue >> } >> >> # 6. 查看服务日志 >> Get-Content "E:\ProjectEcosystem\Logs\Service_*.log" -Tail 50 -ErrorAction SilentlyContinue >> .\ServiceTroubleshooter.ps1 : 无法将“.\ServiceTroubleshooter.ps1”项识别为 cmdlet、函数、脚本文件或可运行程序的称。 请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:25 字符: 5 + .\ServiceTroubleshooter.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (.\ServiceTroubleshooter.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException } return $loadedConfig } catch { Write-Host "❌ 配置加载失败: $_" -ForegroundColor Red return $defaultConfig } } else { Write-Host "⚠️ 配置文件不存在,使用默认配置" -ForegroundColor Yellow return $defaultConfig } } PS C:\Users\Administrator> $global:config = Load-Configuration ⚠️ 配置文件不存在,使用默认配置 PS C:\Users\Administrator> # 主监控循环(带默认值处理) PS C:\Users\Administrator> while ($true) { try { # 确保监控间隔有效 $interval = $global:config.Monitoring.Interval if (-not $interval -or $interval -le 0) { $interval = 60 Write-Host "⚠️ 使用默认监控间隔: 60秒" -ForegroundColor Yellow } # 项目监控逻辑 foreach ($project in $global:config.Projects) { Monitor-Project -ProjectName $project.Name -StartCommand $project.StartCommand } # 等待下一个监控周期 Start-Sleep -Seconds $interval } catch { Write-Host "全局错误: $_" -ForegroundColor Red Start-Sleep -Seconds 10 # 错误后短暂等待 } } 全局错误: 无法将“Monitor-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 全局错误: 无法将“Monitor-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 全局错误: 无法将“Monitor-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 全局错误: 无法将“Monitor-Project”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 PS C:\Users\Administrator> TerminatingError():“管道已被停止。” >> TerminatingError():“管道已被停止。” PS C:\Users\Administrator> Stop-Transcript ********************** Windows PowerShell 脚本结束 结束: 20250813211909 ********************** PS C:\Users\Administrator> .\ServiceTroubleshooter.ps1 -Command Test-ServiceInstallation >> .\ServiceTroubleshooter.ps1 : 无法将“.\ServiceTroubleshooter.ps1”项识别为 cmdlet、函数、脚本文件或可运行程序的称。 请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + .\ServiceTroubleshooter.ps1 -Command Test-ServiceInstallation + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (.\ServiceTroubleshooter.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator> $correctPath = "`"$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe`" -ExecutionPolicy Bypass -File `"E:\ProjectEcosystem\ProjectMonitor\Scripts\ProjectEcosystemManager.ps1`" -WindowStyle Hidden" >> .\ServiceTroubleshooter.ps1 -Command Repair-ServicePath -CorrectBinaryPath $correctPath >> .\ServiceTroubleshooter.ps1 : 无法将“.\ServiceTroubleshooter.ps1”项识别为 cmdlet、函数、脚本文件或可运行程序的称。 请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:2 字符: 1 + .\ServiceTroubleshooter.ps1 -Command Repair-ServicePath -CorrectBinar ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (.\ServiceTroubleshooter.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator> $testScript = @' >> Start-Transcript -Path "E:\ServiceTest.log" >> Write-Host "服务测试成功" >> Stop-Transcript >> exit 0 >> '@ >> Set-Content -Path "E:\ServiceTest.ps1" -Value $testScript >> >> # 测试服务配置 >> sc config ProjectEcosystemManager binPath= "`"$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe`" -File `"E:\ServiceTest.ps1`"" >> Start-Service ProjectEcosystemManager >> Get-Content "E:\ServiceTest.log" >> Set-Content : 找不到接受实际参数“binPath=”的位置形式参数。 所在位置 行:10 字符: 1 + sc config ProjectEcosystemManager binPath= "`"$env:SystemRoot\System3 ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Set-Content],ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetContentCommand Start-Service : 由于以下错误无法启动服务“ProjectEcosystemManager (ProjectEcosystemManager)”: 无法启动计算机“.”上的 服务 ProjectEcosystemManager。 所在位置 行:11 字符: 1 + Start-Service ProjectEcosystemManager + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand Get-Content : 找不到路径“E:\ServiceTest.log”,因为该路径不存在。 所在位置 行:12 字符: 1 + Get-Content "E:\ServiceTest.log" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (E:\ServiceTest.log:String) [Get-Content], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand PS C:\Users\Administrator> # 使用Process Monitor捕获服务启动过程 >> $procmonPath = "E:\Procmon.exe" >> if (Test-Path $procmonPath) { >> & $procmonPath /AcceptEula /Quiet /Minimized /BackingFile "E:\ProcmonLog.pml" /LoadConfig "E:\ProcmonConfig.pmc" >> Start-Service ProjectEcosystemManager >> Start-Sleep -Seconds 10 >> & $procmonPath /Terminate >> } >> PS C:\Users\Administrator> Get-WinEvent -LogName System -MaxEvents 100 | >> Where-Object { >> $_.ProviderName -eq "Service Control Manager" -and >> $_.Id -in @(7000, 7001, 7009, 7011, 7023, 7024, 7031, 7032, 7034) >> } | >> Format-List TimeCreated, Message >> TimeCreated : 2025/8/13 21:20:39 Message : 由于下列错误,ProjectEcosystemManager 服务启动失败: 系统找不到指定的文件。 TimeCreated : 2025/8/13 21:19:42 Message : 由于下列错误,ProjectEcosystemManager 服务启动失败: 系统找不到指定的文件。 TimeCreated : 2025/8/13 21:10:55 Message : 由于下列错误,ProjectEcosystemManager 服务启动失败: 系统找不到指定的文件。 TimeCreated : 2025/8/13 21:04:57 Message : 由于下列错误,ProjectEcosystemManager 服务启动失败: 系统找不到指定的文件。 TimeCreated : 2025/8/13 20:57:25 Message : 由于下列错误,ProjectEcosystemManager 服务启动失败: 系统找不到指定的文件。 TimeCreated : 2025/8/13 20:57:02 Message : 由于下列错误,ProjectEcosystemManager 服务启动失败: 系统找不到指定的文件。 PS C:\Users\Administrator> # 配置默认值 >> $global:projectRoot = "E:\ProjectEcosystem" >> $global:ecosystemConfig = Join-Path $projectRoot "Config\EcosystemConfig.xml" >> >> # 确保日志目录存在 >> $global:logDir = Join-Path $projectRoot "Logs" >> if (-not (Test-Path $logDir)) { >> New-Item -ItemType Directory -Path $logDir -Force | Out-Null >> } >> >> # 启动日志记录 >> $global:serviceLog = Join-Path $logDir "Service_$(Get-Date -Format 'yyyyMMdd').log" >> Start-Transcript -Path $global:serviceLog -Append -ErrorAction SilentlyContinue >> >> Write-Host "=== 生态系统管理服务启动于 $(Get-Date) ===" >> >> # 加载配置(带默认值) >> function Load-Configuration { >> param( >> [string]$ConfigPath = $global:ecosystemConfig >> ) >> >> # 默认配置结构 >> $defaultConfig = [PSCustomObject]@{ >> Monitoring = [PSCustomObject]@{ >> Interval = 60 # 默认60秒 >> AlertEmail = "admin@example.com" >> } >> Projects = @( >> [PSCustomObject]@{ >> Name = "APIServer" >> Type = "NodeJS" >> RepoUrl = "https://github.com/yourrepo/api-server.git" >> StartCommand = "npm start" >> }, >> [PSCustomObject]@{ >> Name = "BackendService" >> Type = ".NET" >> RepoUrl = "https://github.com/yourrepo/backend.git" >> StartCommand = "dotnet run" >> } >> ) >> } >> >> if (Test-Path $ConfigPath) { >> try { >> $loadedConfig = Import-Clixml -Path $ConfigPath -ErrorAction Stop >> Write-Host "✅ 配置加载成功" >> >> # 合并默认值和加载的配置 >> foreach ($prop in $defaultConfig.PSObject.Properties) { >> if (-not $loadedConfig.PSObject.Properties[$prop.Name]) { >> $loadedConfig | Add-Member -NotePropertyName $prop.Name -NotePropertyValue $prop.Value >> } >> } >> >> return $loadedConfig >> } >> catch { >> Write-Host "❌ 配置加载失败: $_" -ForegroundColor Red >> return $defaultConfig >> } >> } >> else { >> Write-Host "⚠️ 配置文件不存在,使用默认配置" -ForegroundColor Yellow >> return $defaultConfig >> } >> } >> >> $global:config = Load-Configuration >> >> # 项目监控函数 >> function Monitor-Project { >> param( >> [string]$ProjectName, >> [string]$StartCommand >> ) >> >> $logFile = Join-Path $global:logDir "$ProjectName-$(Get-Date -Format 'yyyyMMdd').log" >> Write-Host "🔍 监控项目: $ProjectName" >> >> # 检查进程是否运行(简化版) >> $isRunning = $false >> $processes = Get-Process | Where-Object { $_.ProcessName -like "*$ProjectName*" } >> >> if ($null -ne $processes -and $processes.Count -gt 0) { >> $isRunning = $true >> Write-Host "✅ $ProjectName 正在运行 (PID: $($processes[0].Id))" >> } else { >> Write-Host "⚠️ $ProjectName 未运行" >> } >> >> if (-not $isRunning) { >> Write-Host "🚀 正在启动 $ProjectName..." >> try { >> # 启动项目 >> Start-Process -FilePath "pwsh" ` >> -ArgumentList "-Command `"$StartCommand 2>&1 | Tee-Object -FilePath '$logFile'`"" ` >> -WindowStyle Hidden >> >> Write-Host "✅ $ProjectName 启动成功" >> } >> catch { >> Write-Host "❌ 启动失败: $_" -ForegroundColor Red >> } >> } >> } >> >> # 主监控循环 >> try { >> while ($true) { >> # 确保监控间隔有效 >> $interval = $global:config.Monitoring.Interval >> if (-not $interval -or $interval -le 0) { >> $interval = 60 >> Write-Host "⚠️ 使用默认监控间隔: 60秒" -ForegroundColor Yellow >> } >> >> # 项目监控逻辑 >> foreach ($project in $global:config.Projects) { >> Monitor-Project -ProjectName $project.Name -StartCommand $project.StartCommand >> } >> >> # 等待下一个监控周期 >> Write-Host "⏱️ 等待 $interval 秒后再次检查..." >> Start-Sleep -Seconds $interval >> } >> } >> catch { >> Write-Host "❌ 全局错误: $_" -ForegroundColor Red >> } >> finally { >> Stop-Transcript >> } >> 已启动脚本,输出文件为 E:\ProjectEcosystem\Logs\Service_20250813.log === 生态系统管理服务启动于 08/13/2025 21:29:05 === ⚠️ 配置文件不存在,使用默认配置 🔍 监控项目: APIServer ⚠️ APIServer 未运行 🚀 正在启动 APIServer... ❌ 启动失败: 由于出现以下错误,无法运行此命令: 系统找不到指定的文件。。 🔍 监控项目: BackendService ⚠️ BackendService 未运行 🚀 正在启动 BackendService... ❌ 启动失败: 由于出现以下错误,无法运行此命令: 系统找不到指定的文件。。 ⏱️ 等待 60 秒后再次检查...
最新发布
08-14
PS C:\Users\Administrator> function Test-CurlPath { >> <# >> .SYNOPSIS >> 验证curl路径是否有效 >> >> .PARAMETER Path >> 要验证的curl安装目录 >> #> >> param( >> [Parameter(Mandatory=$true)] >> [string]$Path >> ) >> >> $platform = Get-Platform >> $exeName = if ($platform -eq "Windows") { "curl.exe" } else { "curl" } >> $exePath = Join-Path $Path $exeName >> >> if (-not (Test-Path $exePath)) { >> return $false >> } >> >> try { >> $null = & $exePath --version 2>$null >> return ($LASTEXITCODE -eq 0) >> } catch { >> return $false >> } >> } >> PS C:\Users\Administrator> function Initialize-Module { >> try { >> # ... 其他初始化代码 ... >> >> # 修复路径验证逻辑 >> $isPathValid = $false >> if ($script:Config.CurlPath) { >> $isPathValid = Test-CurlPath -Path $script:Config.CurlPath >> } >> >> if (-not $isPathValid) { >> Write-Warning "配置的curl路径无效,正在重新查找..." >> $script:Config.CurlPath = Find-CurlPath >> $script:CurlPath = $script:Config.CurlPath >> } >> >> # 最终验证 >> if (-not (Test-CurlPath -Path $script:CurlPath)) { >> throw "无法找到有效的curl安装路径" >> } >> >> # ... 其他代码 ... >> } >> catch { >> # 添加详细的错误日志 >> $errorDetails = @" >> 初始化失败: $_ >> 调用堆栈: >> $(Get-PSCallStack | Out-String) >> 配置路径: $script:ConfigPath >> 当前路径: $script:CurlPath >> "@ >> Set-Content -Path (Join-Path $script:ConfigDir "init-error.log") -Value $errorDetails >> throw $_ >> } >> } >> PS C:\Users\Administrator> function Invoke-SecureDownload { >> <# >> .SYNOPSIS >> 使用curl执行安全下载 >> >> .PARAMETER Url >> 要下载的URL >> >> .PARAMETER OutputPath >> 保存文件的路径 >> >> .EXAMPLE >> PS> Invoke-SecureDownload -Url "https://example.com/file.zip" -OutputPath "C:\downloads\file.zip" >> #> >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [ValidatePattern('^https?://')] >> [string]$Url, >> >> [Parameter(Mandatory=$true)] >> [string]$OutputPath >> ) >> >> try { >> if (-not $script:ModuleInitialized) { >> Initialize-Module | Out-Null >> } >> >> $curlExe = Join-Path $script:CurlPath $(if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" }) >> >> # 创建输出目录 >> $outputDir = Split-Path $OutputPath -Parent >> if (-not (Test-Path $outputDir)) { >> New-Item -ItemType Directory -Path $outputDir -Force | Out-Null >> } >> >> # 执行下载命令 >> $commandArgs = @( >> '--location', >> '--progress-bar', >> '--fail', >> '--output', "`"$OutputPath`"", >> "`"$Url`"" >> ) >> >> Write-Verbose "执行命令: $curlExe $($commandArgs -join ' ')" >> & $curlExe @commandArgs 2>&1 >> >> if ($LASTEXITCODE -ne 0) { >> throw "下载失败 (退出代码: $LASTEXITCODE)" >> } >> >> # 验证文件完整性 >> if (-not (Test-Path $OutputPath)) { >> throw "下载文件不存在: $OutputPath" >> } >> >> $fileInfo = Get-Item $OutputPath >> if ($fileInfo.Length -eq 0) { >> Remove-Item $OutputPath -Force >> throw "下载文件为空" >> } >> >> Write-Host "✅ 下载成功 | 保存到: $OutputPath" -ForegroundColor Green >> return $OutputPath >> } catch { >> Write-Error "下载失败: $_" >> return $null >> } >> } >> PS C:\Users\Administrator> # 创建模块目录 >> $moduleDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\CurlTools" >> $privateDir = Join-Path $moduleDir "Private" >> $publicDir = Join-Path $moduleDir "Public" >> >> # 确保目录存在 >> $null = New-Item -Path $moduleDir -ItemType Directory -Force >> $null = New-Item -Path $privateDir -ItemType Directory -Force >> $null = New-Item -Path $publicDir -ItemType Directory -Force >> >> # ===== 保存核心函数 ===== >> $coreFunctions = @{ >> # 私有函数 >> "Private/GetPlatform.ps1" = @' >> function Get-Platform { >> # 实现 >> } >> '@ >> "Private/ValidateCurlPath.ps1" = @' >> function Test-CurlPath { >> # 实现 >> } >> '@ >> "Private/InitializeModule.ps1" = @' >> function Initialize-Module { >> # 修复后的实现 >> } >> '@ >> "Private/InstallCurl.ps1" = @' >> function Install-Curl { >> # 实现 >> } >> '@ >> >> # 公共函数 >> "Public/SecureDownload.ps1" = @' >> function Invoke-SecureDownload { >> # 完整实现 >> } >> '@ >> "Public/GetCurlPath.ps1" = @' >> function Get-CurlPath { >> # 实现 >> } >> '@ >> } >> >> foreach ($path in $coreFunctions.Keys) { >> $fullPath = Join-Path $moduleDir $path >> $dir = Split-Path $fullPath -Parent >> if (-not (Test-Path $dir)) { >> New-Item -ItemType Directory -Path $dir -Force | Out-Null >> } >> Set-Content -Path $fullPath -Value $coreFunctions[$path] -Force >> } >> >> # ===== 创建测试脚本 ===== >> $testScript = @' >> # 重新加载模块 >> Remove-Module CurlTools -ErrorAction SilentlyContinue -Force >> Import-Module "$PSScriptRoot" -Force -Verbose >> >> # 全面测试 >> $testCases = @( >> @{Name = "路径获取"; Script = { Get-CurlPath } } >> @{Name = "版本获取"; Script = { Get-CurlVersion } } >> @{Name = "HTTP下载"; Script = { >> $url = "https://www.example.com" >> $out = Join-Path $env:TEMP "example_$(Get-Date -f 'yyyyMMddHHmmss').html" >> Invoke-SecureDownload -Url $url -OutputPath $out >> }} >> @{Name = "HTTPS下载"; Script = { >> $url = "https://www.google.com" >> $out = Join-Path $env:TEMP "google_$(Get-Date -f 'yyyyMMddHHmmss').html" >> Invoke-SecureDownload -Url $url -OutputPath $out >> }} >> ) >> >> foreach ($test in $testCases) { >> try { >> Write-Host "`n=== 测试: $($test.Name) ===" -ForegroundColor Cyan >> $result = & $test.Script >> if ($result) { >> Write-Host "✅ 测试成功" -ForegroundColor Green >> if ($result -is [string]) { >> Write-Host "结果: $result" -ForegroundColor Gray >> } >> } else { >> Write-Warning "⚠️ 测试返回空结果" >> } >> } catch { >> Write-Host "❌ 测试失败: $_" -ForegroundColor Red >> } >> } >> '@ >> >> Set-Content -Path (Join-Path $moduleDir "Test-Module.ps1") -Value $testScript >> PS C:\Users\Administrator> # 安装后执行测试 >> $testScriptPath = Join-Path $moduleDir "Test-Module.ps1" >> if (Test-Path $testScriptPath) { >> Write-Host "`n执行模块自检..." -ForegroundColor Cyan >> & $testScriptPath >> } else { >> Write-Warning "未找到测试脚本" >> } >> >> # 最终状态报告 >> if ($error.Count -gt 0) { >> Write-Host "`n❌ 模块安装完成,但检测到 $($error.Count) 个错误" -ForegroundColor Red >> $error | ForEach-Object { Write-Host " - $_" -ForegroundColor DarkRed } >> } else { >> Write-Host "`n✅ 模块安装成功并通过所有自检" -ForegroundColor Green >> } >> 执行模块自检... 详细信息: 正在从路径“C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psd1”加载模块。 详细信息: 正在从路径“C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psm1”加载模块。 === 测试: 路径获取 === ? 测试失败: 无法将“Get-CurlPath”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请 确保路径正确,然后再试一次。 === 测试: 版本获取 === ? 测试失败: 无法将“Get-CurlVersion”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 === 测试: HTTP下载 === 警告: 配置的curl路径无效,正在重新查找... Invoke-SecureDownload : 下载失败: 无法将参数绑定到参数“Path”,因为该参数是空值。 所在位置 C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\Test-Module.ps1:12 字符: 9 + Invoke-SecureDownload -Url $url -OutputPath $out + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-SecureDownload 警告: ?? 测试返回空结果 === 测试: HTTPS下载 === 警告: 配置的curl路径无效,正在重新查找... Invoke-SecureDownload : 下载失败: 无法将参数绑定到参数“Path”,因为该参数是空值。 所在位置 C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\Test-Module.ps1:17 字符: 9 + Invoke-SecureDownload -Url $url -OutputPath $out + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Invoke-SecureDownload 警告: ?? 测试返回空结果 ❌ 模块安装完成,但检测到 9 个错误 - 下载失败: 无法将参数绑定到参数“Path”,因为该参数是空值。 - 无法将参数绑定到参数“Path”,因为该参数是空值。 - 无法将“Find-CurlPath”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径 正确,然后再试一次。 - 下载失败: 无法将参数绑定到参数“Path”,因为该参数是空值。 - 无法将参数绑定到参数“Path”,因为该参数是空值。 - 无法将“Find-CurlPath”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径 正确,然后再试一次。 - 无法将“Get-CurlVersion”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路 径正确,然后再试一次。 - 无法将“Get-CurlPath”项识别为 cmdlet、函数、脚本文件或可运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 - 没有删除任何模块。请确认要删除的模块的规范正确,并且运行空间中存在这些模块。 PS C:\Users\Administrator>
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值