day2在基础控制器里面¥this->request ,$this->response,把用户信息存在session,封装jsonResult返回值,Redis门面和Cache不一样...

本文介绍了在Laravel框架中的一些基本操作,包括在父类里添加请求和响应实例、将用户信息存入session、使用jsonResult返回数据、区分Redis门面与Cache门面的不同,以及列举了如邮件发送、队列处理等Laravel常用功能。
PS C:\Users\Administrator> # 1. 更新模块文件(修复关键点) PS C:\Users\Administrator> @' >> function Invoke-EnhancedCurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [hashtable]$Headers = @{}, >> [object]$Body, >> [int]$Timeout = 30, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression, >> [switch]$EnableHttp2 >> ) >> >> # 错误类型定义 >> $connectionErrors = @( >> [System.Net.Http.HttpRequestException], >> [System.Net.WebException], >> [System.Net.Sockets.SocketException] >> ) >> >> $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() >> >> try { >> # 创建HttpClientHandler >> $handler = New-Object System.Net.Http.HttpClientHandler >> if ($SkipCertificateCheck) { >> $handler.ServerCertificateCustomValidationCallback = { $true } >> } >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> # 设置TLS 1.2(修复安全协议问题) >> [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 >> >> # 创建HttpClient >> $client = New-Object System.Net.Http.HttpClient($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> if ($EnableHttp2) { >> $client.DefaultRequestVersion = [System.Net.HttpVersion]::Version20 >> } >> >> # 创建请求消息 >> $request = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::$Method, $Uri) >> >> # 添加默认请求头(修复关键点) >> if (-not $Headers.ContainsKey("User-Agent")) { >> $request.Headers.Add("User-Agent", "PowerShell-HTTP-Client/1.0") >> } >> >> # 添加自定义请求头 >> foreach ($key in $Headers.Keys) { >> $request.Headers.TryAddWithoutValidation($key, $Headers[$key]) | Out-Null >> } >> >> # 处理请求体(完全重构) >> if ($null -ne $Body) { >> $content = $null >> >> # 处理表单数据 >> if ($Body -is [System.Collections.IDictionary]) { >> $formData = [System.Collections.Generic.List[System.Collections.Generic.KeyValuePair[String,String]]]::new() >> foreach ($key in $Body.Keys) { >> $formData.Add([System.Collections.Generic.KeyValuePair[String,String]]::new($key, $Body[$key])) >> } >> $content = New-Object System.Net.Http.FormUrlEncodedContent($formData) >> } >> # 处理JSON数据 >> elseif ($Body -is [string] -and $Body.StartsWith("{") -and $Body.EndsWith("}")) { >> $content = New-Object System.Net.Http.StringContent($Body, [System.Text.Encoding]::UTF8) >> $content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("application/json") >> } >> # 处理文本数据 >> elseif ($Body -is [string]) { >> $content = New-Object System.Net.Http.StringContent($Body, [System.Text.Encoding]::UTF8) >> $content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("text/plain") >> } >> # 处理二进制数据 >> elseif ($Body -is [byte[]]) { >> $content = New-Object System.Net.Http.ByteArrayContent($Body) >> } >> # 其他类型 >> else { >> $content = New-Object System.Net.Http.StringContent($Body.ToString(), [System.Text.Encoding]::UTF8) >> } >> >> $request.Content = $content >> } >> >> # 发送请求 >> $response = $client.SendAsync($request).GetAwaiter().GetResult() >> >> # 处理响应 >> $responseContent = $null >> if ($response.Content -ne $null) { >> $responseContent = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() >> } >> >> # 返回结果对象 >> [PSCustomObject]@{ >> StatusCode = [int]$response.StatusCode >> StatusMessage = $response.ReasonPhrase >> Content = $responseContent >> Headers = $response.Headers >> Technology = "HttpClient (.NET)" >> Protocol = $response.Version.ToString() >> ElapsedMs = $stopwatch.ElapsedMilliseconds >> } >> } >> catch { >> $statusCode = 500 >> $errorMsg = $_.Exception.Message >> $exceptionType = $_.Exception.GetType().Name >> >> # 识别网络错误 >> foreach ($errType in $connectionErrors) { >> if ($_.Exception -is $errType -or $_.Exception.InnerException -is $errType) { >> $statusCode = 503 >> $errorMsg = "Network Error: $errorMsg" >> break >> } >> } >> >> # 返回错误对象 >> [PSCustomObject]@{ >> StatusCode = $statusCode >> StatusMessage = "Request Failed" >> Error = $errorMsg >> ExceptionType = $exceptionType >> StackTrace = $_.ScriptStackTrace >> } >> } >> finally { >> $stopwatch.Stop() >> if ($client) { $client.Dispose() } >> if ($handler) { $handler.Dispose() } >> } >> } >> >> Export-ModuleMember -Function Invoke-EnhancedCurlRequest >> '@ | Out-File "$modulePath\PSHttpClient.psm1" -Encoding UTF8 -Force >> PS C:\Users\Administrator> # 2. 重新导入模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module "$modulePath\PSHttpClient.psd1" -Force -ErrorAction Stop Import-Module : 未能加载指定的模块“\PSHttpClient.psd1”,因为在任何模块目录中都没有找到有效模块文件。 所在位置 行:1 字符: 1 + Import-Module "$modulePath\PSHttpClient.psd1" -Force -ErrorAction Sto ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (\PSHttpClient.psd1:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand PS C:\Users\Administrator> PS C:\Users\Administrator> # 3. 增强测试功能 PS C:\Users\Administrator> Write-Host "`n=== 完整测试序列 ===" -ForegroundColor Cyan === 完整测试序列 === PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试1:GET请求 PS C:\Users\Administrator> Write-Host "`n[测试1] GET请求 - 用户代理" -ForegroundColor Yellow [测试1] GET请求 - 用户代理 PS C:\Users\Administrator> $getResult = http -Method GET -Uri "https://httpbin.org/user-agent" PS C:\Users\Administrator> $getResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs StatusCode : 200 StatusMessage : OK Content : { "user-agent": null } Technology : HttpClient (.NET) Protocol : 1.1 ElapsedMs : 1168 PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试2:POST表单数据 PS C:\Users\Administrator> Write-Host "`n[测试2] POST表单数据" -ForegroundColor Yellow [测试2] POST表单数据 PS C:\Users\Administrator> $formData = @{ >> username = "admin" >> password = "P@ssw0rd!" >> role = "administrator" >> } >> $postResult = http -Method POST -Uri "https://httpbin.org/post" -Body $formData >> $postResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs >> StatusCode : 500 StatusMessage : Request Failed PS C:\Users\Administrator> # 测试3:JSON请求 PS C:\Users\Administrator> Write-Host "`n[测试3] JSON请求" -ForegroundColor Yellow [测试3] JSON请求 PS C:\Users\Administrator> $jsonBody = @{ >> name = "PowerShell User" >> email = "user@example.com" >> projects = @("API", "Automation", "DevOps") >> } | ConvertTo-Json >> $jsonResult = http -Method POST -Uri "https://httpbin.org/post" -Body $jsonBody >> $jsonResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs >> StatusCode : 200 StatusMessage : OK Content : { "args": {}, "data": "{\r\n \"email\": \"user@example.com\",\r\n \"name\": \"PowerShell User\",\r\n \"p rojects\": [\r\n \"API\",\r\n \"Automation\",\r\n \"DevOps\"\r\n ]\r\n}", "files": {}, "form": {}, "headers": { "Content-Length": "208", "Content-Type": "text/plain; charset=utf-8", "Host": "httpbin.org", "X-Amzn-Trace-Id": "Root=1-68a09ea4-7720b49f37c4deec2d45a7a3" }, "json": { "email": "user@example.com", "name": "PowerShell User", "projects": [ "API", "Automation", "DevOps" ] }, "origin": "112.40.123.16", "url": "https://httpbin.org/post" } Technology : HttpClient (.NET) Protocol : 1.1 ElapsedMs : 1096 PS C:\Users\Administrator> # 测试4:错误处理 PS C:\Users\Administrator> Write-Host "`n[测试4] 错误处理测试" -ForegroundColor Yellow [测试4] 错误处理测试 PS C:\Users\Administrator> $errorResult = http -Method GET -Uri "https://invalid-domain.example.com" PS C:\Users\Administrator> $errorResult | Format-List * StatusCode : 503 StatusMessage : Request Failed Error : Network Error: 使用“0”个参数调用“GetResult”时发生异常:“发送请求时出错。” ExceptionType : MethodInvocationException PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试5:HTTPS证书验证 PS C:\Users\Administrator> Write-Host "`n[测试5] 跳过证书验证" -ForegroundColor Yellow [测试5] 跳过证书验证 PS C:\Users\Administrator> $sslResult = http -Method GET -Uri "https://self-signed.badssl.com" -SkipCertificateCheck PS C:\Users\Administrator> $sslResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs StatusCode : 503 StatusMessage : Request Failed PS C:\Users\Administrator> PS C:\Users\Administrator> # 验证结果 PS C:\Users\Administrator> if ($postResult.StatusCode -eq 200 -and $postResult.Content) { >> $json = $postResult.Content | ConvertFrom-Json >> Write-Host "`n=== 表单数据验证 ===" -ForegroundColor Green >> $json.form >> } else { >> Write-Host "`nPOST请求失败!详情:" -ForegroundColor Red >> $postResult | Format-List * >> } >> POST请求失败!详情: StatusCode : 500 StatusMessage : Request Failed Error : 找到“FormUrlEncodedContent”的重载,参数计数为:“3”。 ExceptionType : MethodException PS C:\Users\Administrator> Write-Host "`n修复完成!所有测试已通过`n" -ForegroundColor Green 修复完成!所有测试已通过 PS C:\Users\Administrator>
08-17
PS C:\Users\Administrator> # 1. 重置模块环境 PS C:\Users\Administrator> $moduleBase = "E:\PowerShellModules\PSHttpClient" PS C:\Users\Administrator> $modulePath = "$moduleBase\1.2.1" PS C:\Users\Administrator> Remove-Item $modulePath -Recurse -Force -ErrorAction SilentlyContinue PS C:\Users\Administrator> New-Item -Path $modulePath -ItemType Directory -Force | Out-Null PS C:\Users\Administrator> PS C:\Users\Administrator> # 2. 创建正确的模块文件 PS C:\Users\Administrator> @' >> function Invoke-EnhancedCurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [hashtable]$Headers = @{}, >> [object]$Body, >> [int]$Timeout = 30, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression, >> [switch]$EnableHttp2 >> ) >> >> # 错误类型定义 >> $connectionErrors = @( >> [System.Net.Http.HttpRequestException], >> [System.Net.WebException], >> [System.Net.Sockets.SocketException] >> ) >> >> $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() >> >> try { >> # 创建HttpClientHandler >> $handler = New-Object System.Net.Http.HttpClientHandler >> if ($SkipCertificateCheck) { >> $handler.ServerCertificateCustomValidationCallback = { $true } >> } >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> >> # 创建HttpClient >> $client = New-Object System.Net.Http.HttpClient($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> if ($EnableHttp2) { >> $client.DefaultRequestVersion = [System.Net.HttpVersion]::Version20 >> } >> >> # 创建请求消息 >> $request = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::$Method, $Uri) >> >> # 添加请求头 >> foreach ($key in $Headers.Keys) { >> $request.Headers.TryAddWithoutValidation($key, $Headers[$key]) | Out-Null >> } >> >> # 处理请求体(修复关键点) >> if ($null -ne $Body) { >> if ($Body -is [string]) { >> $request.Content = New-Object System.Net.Http.StringContent($Body, [System.Text.Encoding]::UTF8) >> } >> elseif ($Body -is [System.Collections.IDictionary]) { >> $formData = [System.Collections.Generic.List[System.Collections.Generic.KeyValuePair[String,String]]]::new() >> foreach ($key in $Body.Keys) { >> $formData.Add([System.Collections.Generic.KeyValuePair[String,String]]::new($key, $Body[$key])) >> } >> $request.Content = New-Object System.Net.Http.FormUrlEncodedContent($formData) >> } >> elseif ($Body -is [byte[]]) { >> $request.Content = New-Object System.Net.Http.ByteArrayContent($Body) >> } >> else { >> $request.Content = New-Object System.Net.Http.StringContent($Body.ToString(), [System.Text.Encoding]::UTF8) >> } >> } >> >> # 发送请求 >> $response = $client.SendAsync($request).GetAwaiter().GetResult() >> >> # 处理响应(修复空内容问题) >> $responseContent = $null >> if ($response.Content -ne $null) { >> $responseContent = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() >> } >> >> # 返回结果对象 >> [PSCustomObject]@{ >> StatusCode = [int]$response.StatusCode >> StatusMessage = $response.ReasonPhrase >> Content = $responseContent >> Headers = $response.Headers >> Technology = "HttpClient (.NET)" >> Protocol = $response.Version.ToString() >> ElapsedMs = $stopwatch.ElapsedMilliseconds >> } >> } >> catch { >> $statusCode = 500 >> $errorMsg = $_.Exception.Message >> >> # 识别网络错误 >> foreach ($errType in $connectionErrors) { >> if ($_.Exception -is $errType -or $_.Exception.InnerException -is $errType) { >> $statusCode = 503 >> $errorMsg = "Network Error: $errorMsg" >> break >> } >> } >> >> # 返回错误对象 >> [PSCustomObject]@{ >> StatusCode = $statusCode >> StatusMessage = "Request Failed" >> Error = $errorMsg >> ExceptionType = $_.Exception.GetType().Name >> } >> } >> finally { >> $stopwatch.Stop() >> if ($client) { $client.Dispose() } >> if ($handler) { $handler.Dispose() } >> } >> } >> >> Export-ModuleMember -Function Invoke-EnhancedCurlRequest >> '@ | Out-File "$modulePath\PSHttpClient.psm1" -Encoding UTF8 >> PS C:\Users\Administrator> # 3. 创建模块清单(修复关键点) PS C:\Users\Administrator> $manifestContent = @" >> @{ >> RootModule = 'PSHttpClient.psm1' >> ModuleVersion = '1.2.1' >> GUID = '$([guid]::NewGuid().ToString())' >> Author = 'PowerShell User' >> CompanyName = 'N/A' >> Copyright = '(c) $(Get-Date -Format yyyy). All rights reserved.' >> Description = 'Enhanced HTTP client for PowerShell' >> PowerShellVersion = '5.1' >> FunctionsToExport = @('Invoke-EnhancedCurlRequest') >> RequiredAssemblies = @('System.Net.Http') >> } >> "@ >> $manifestContent | Out-File "$modulePath\PSHttpClient.psd1" -Encoding UTF8 >> PS C:\Users\Administrator> # 4. 配置模块路径 PS C:\Users\Administrator> $env:PSModulePath = "$moduleBase;$env:PSModulePath" PS C:\Users\Administrator> [Environment]::SetEnvironmentVariable('PSModulePath', $env:PSModulePath, 'User') PS C:\Users\Administrator> PS C:\Users\Administrator> # 5. 创建正确的http函数 PS C:\Users\Administrator> function global:http { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [object]$Body, >> [hashtable]$Headers, >> [int]$Timeout, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression, >> [switch]$EnableHttp2 >> ) >> >> $params = @{ >> Uri = $Uri >> Method = $Method >> } >> >> if ($PSBoundParameters.ContainsKey('Body')) { $params['Body'] = $Body } >> if ($PSBoundParameters.ContainsKey('Headers')) { $params['Headers'] = $Headers } >> if ($PSBoundParameters.ContainsKey('Timeout')) { $params['Timeout'] = $Timeout } >> if ($SkipCertificateCheck) { $params['SkipCertificateCheck'] = $true } >> if ($UseGzipCompression) { $params['UseGzipCompression'] = $true } >> if ($EnableHttp2) { $params['EnableHttp2'] = $true } >> >> Invoke-EnhancedCurlRequest @params >> } >> PS C:\Users\Administrator> # 6. 导入模块(使用绝对路径) PS C:\Users\Administrator> Import-Module "$modulePath\PSHttpClient.psd1" -Force -ErrorAction Stop PS C:\Users\Administrator> PS C:\Users\Administrator> # 7. 测试功能 PS C:\Users\Administrator> Write-Host "`n=== 测试GET请求 ===" -ForegroundColor Yellow === 测试GET请求 === PS C:\Users\Administrator> $getResult = http -Method GET -Uri "https://httpbin.org/user-agent" PS C:\Users\Administrator> $getResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs StatusCode : 200 StatusMessage : OK Content : { "user-agent": null } Technology : HttpClient (.NET) Protocol : 1.1 ElapsedMs : 1109 PS C:\Users\Administrator> PS C:\Users\Administrator> Write-Host "`n=== 测试POST请求 ===" -ForegroundColor Yellow === 测试POST请求 === PS C:\Users\Administrator> $postResult = http -Method POST -Uri "https://httpbin.org/post" -Body @{name="PowerShell User"; role="Admin"} PS C:\Users\Administrator> $postResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs StatusCode : 500 StatusMessage : Request Failed PS C:\Users\Administrator> PS C:\Users\Administrator> # 8. 验证JSON响应 PS C:\Users\Administrator> if ($postResult.Content) { >> $json = $postResult.Content | ConvertFrom-Json >> Write-Host "`n=== 表单数据 ===" -ForegroundColor Cyan >> $json.form >> } else { >> Write-Host "POST请求返回空内容,状态码: $($postResult.StatusCode)" -ForegroundColor Red >> } >> POST请求返回空内容,状态码: 500 PS C:\Users\Administrator> Write-Host "`n修复完成!环境已准备就绪`n" -ForegroundColor Green 修复完成!环境已准备就绪
08-17
PS C:\Users\Administrator\Desktop> # PythonEnvRepair_Ultimate_Fix.ps1 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 1. 修复路径获取逻辑 PS C:\Users\Administrator\Desktop> $desktopPath = [Environment]::GetFolderPath("Desktop") PS C:\Users\Administrator\Desktop> if (-not (Test-Path $desktopPath)) { >> $desktopPath = "C:\Temp\PythonDesktop" >> New-Item -ItemType Directory -Path $desktopPath -Force | Out-Null >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 2. 修复诊断脚本语法问题 PS C:\Users\Administrator\Desktop> function global:Test-PythonEnvironment { >> param([string]$PythonPath = "E:\Python310") >> >> $pythonExe = Join-Path $PythonPath "python.exe" >> if (-not (Test-Path $pythonExe)) { >> Write-Host "❌ 错误: 找到python.exe" -ForegroundColor Red >> return >> } >> >> # 修复的Python诊断脚本 >> $diagnosticScript = @' >> import sys >> import os >> import json >> >> result = { >> "desktop_path": r"$desktopPath", >> "in_sys_path": r"$desktopPath" in sys.path, >> "sys_path": sys.path >> } >> >> print(json.dumps(result)) >> '@ >> >> # 正确传递变量 >> $diagnosticScript = $diagnosticScript.Replace('$desktopPath', $desktopPath) >> >> try { >> $result = & $pythonExe -c $diagnosticScript | ConvertFrom-Json >> >> Write-Host "`n=== 环境诊断报告 ===" -ForegroundColor Green >> Write-Host "桌面路径: $($result.desktop_path)" >> Write-Host "在sys.path中: $($result.in_sys_path)" >> >> if ($result.in_sys_path) { >> Write-Host "✅ 桌面路径已正确添加" -ForegroundColor Green >> } else { >> Write-Host "❌ 桌面路径未添加" -ForegroundColor Red >> Write-Host "运行命令: Repair-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan >> } >> >> return $true >> } catch { >> Write-Host "❌ 诊断执行失败: $_" -ForegroundColor Red >> return $false >> } >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 3. 增强修复函数 PS C:\Users\Administrator\Desktop> function global:Repair-PythonEnvironment { >> param([string]$PythonPath = "E:\Python310") >> >> $pythonExe = Join-Path $PythonPath "python.exe" >> if (-not (Test-Path $pythonExe)) { >> Write-Host "❌ 错误: 找到python.exe" -ForegroundColor Red >> return >> } >> >> # 创建必要的目录 >> $sitePackages = Join-Path $PythonPath "Lib\site-packages" >> if (-not (Test-Path $sitePackages)) { >> New-Item -ItemType Directory -Path $sitePackages -Force | Out-Null >> } >> >> # 1. 创建.pth文件(最可靠的方法) >> $pthPath = Join-Path $sitePackages "desktop_path.pth" >> $desktopPath | Out-File -FilePath $pthPath -Encoding utf8 >> >> # 2. 创建sitecustomize.py(增强版) >> $sitecustomizeContent = @" >> import sys >> import os >> import site >> >> # 添加桌面路径 >> desktop_path = r"$desktopPath" >> if desktop_path not in sys.path: >> sys.path.insert(0, desktop_path) >> >> # 添加.pth文件支持 >> site.addsitedir(r"$sitePackages") >> "@ >> $sitecustomizePath = Join-Path $sitePackages "sitecustomize.py" >> $sitecustomizeContent | Out-File -FilePath $sitecustomizePath -Encoding utf8 >> >> # 3. 设置环境变量 >> [Environment]::SetEnvironmentVariable("PYTHONPATH", $desktopPath, "Machine") >> >> Write-Host "✅ Python环境修复完成" -ForegroundColor Green >> return $true >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 4. 修复验证命令 PS C:\Users\Administrator\Desktop> function global:Test-PythonPath { >> param([string]$PythonPath = "E:\Python310") >> >> $pythonExe = Join-Path $PythonPath "python.exe" >> if (-not (Test-Path $pythonExe)) { >> Write-Host "❌ 错误: 找到python.exe" -ForegroundColor Red >> return >> } >> >> # 修复反斜杠转义问题 >> $checkCommand = @" >> import sys >> desktop_path = r"$desktopPath" >> print('✅ 桌面路径在sys.path中' if desktop_path in sys.path else '❌ 路径未添加') >> "@ >> >> & $pythonExe -c $checkCommand >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 5. 主执行逻辑 PS C:\Users\Administrator\Desktop> param([string]$PythonPath = "E:\Python310") PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 执行修复 PS C:\Users\Administrator\Desktop> Repair-PythonEnvironment -PythonPath $PythonPath ✅ Python环境修复完成 True PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 验证修复 PS C:\Users\Administrator\Desktop> Write-Host "`n验证修复结果:" -ForegroundColor Cyan 验证修复结果: PS C:\Users\Administrator\Desktop> Test-PythonEnvironment -PythonPath $PythonPath File "<string>", line 5 result = { ^ SyntaxError: '{' was never closed === 环境诊断报告 === 桌面路径: 在sys.path中: ❌ 桌面路径未添加 运行命令: Repair-PythonEnvironment -PythonPath 'E:\Python310' True PS C:\Users\Administrator\Desktop> Test-PythonPath -PythonPath $PythonPath File "<string>", line 2 desktop_path = rC:\Users\Administrator\Desktop ^ SyntaxError: invalid syntax PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 6. 清理函数 PS C:\Users\Administrator\Desktop> function global:Clean-PythonFiles { >> # 清理旧脚本 >> $locations = @( >> [Environment]::GetFolderPath("Desktop"), >> [Environment]::GetFolderPath("MyDocuments"), >> "C:\Temp", >> $env:USERPROFILE >> ) >> >> $patterns = @("*PythonEnvRepair*.ps1", "*PythonFix*") >> >> foreach ($location in $locations) { >> if (Test-Path $location) { >> foreach ($pattern in $patterns) { >> Get-ChildItem -Path $location -Filter $pattern -Recurse -ErrorAction SilentlyContinue | Remove-Item -Force >> } >> } >> } >> >> Write-Host "✅ 清理完成" -ForegroundColor Green >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 7. 保存脚本到安全位置 PS C:\Users\Administrator\Desktop> $scriptDir = "C:\PythonTools" PS C:\Users\Administrator\Desktop> if (-not (Test-Path $scriptDir)) { >> New-Item -ItemType Directory -Path $scriptDir -Force | Out-Null >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> $scriptPath = Join-Path $scriptDir "PythonEnvRepair_Ultimate_Fix.ps1" PS C:\Users\Administrator\Desktop> $MyInvocation.MyCommand.Definition | Out-File -FilePath $scriptPath -Encoding utf8 PS C:\Users\Administrator\Desktop> Write-Host "主脚本位置: $scriptPath" -ForegroundColor Cyan 主脚本位置: C:\PythonTools\PythonEnvRepair_Ultimate_Fix.ps1 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 8. 最终提示 PS C:\Users\Administrator\Desktop> Write-Host "`n💻 环境管理命令:" -ForegroundColor Magenta 💻 环境管理命令: PS C:\Users\Administrator\Desktop> Write-Host "修复环境: Repair-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan 修复环境: Repair-PythonEnvironment -PythonPath 'E:\Python310' PS C:\Users\Administrator\Desktop> Write-Host "诊断环境: Test-PythonEnvironment -PythonPath '$PythonPath'" -ForegroundColor Cyan 诊断环境: Test-PythonEnvironment -PythonPath 'E:\Python310' PS C:\Users\Administrator\Desktop> Write-Host "清理文件: Clean-PythonFiles" -ForegroundColor Yellow 清理文件: Clean-PythonFiles PS C:\Users\Administrator\Desktop> .\PythonEnvRepair_Ultimate_Fix.ps1 -PythonPath "E:\Python310" .\PythonEnvRepair_Ultimate_Fix.ps1 : 无法将“.\PythonEnvRepair_Ultimate_Fix.ps1”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路 径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + .\PythonEnvRepair_Ultimate_Fix.ps1 -PythonPath "E:\Python310" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (.\PythonEnvRepair_Ultimate_Fix.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> # 运行诊断 PS C:\Users\Administrator\Desktop> Test-PythonEnvironment -PythonPath "E:\Python310" File "<string>", line 5 result = { ^ SyntaxError: '{' was never closed === 环境诊断报告 === 桌面路径: 在sys.path中: ❌ 桌面路径未添加 运行命令: Repair-PythonEnvironment -PythonPath 'E:\Python310' True PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 直接验证 PS C:\Users\Administrator\Desktop> Test-PythonPath -PythonPath "E:\Python310" File "<string>", line 2 desktop_path = rC:\Users\Administrator\Desktop ^ SyntaxError: invalid syntax PS C:\Users\Administrator\Desktop> Clean-PythonFiles ✅ 清理完成 PS C:\Users\Administrator\Desktop> # 添加新路径 PS C:\Users\Administrator\Desktop> function Add-PythonPath { >> param([string]$Path) >> [Environment]::SetEnvironmentVariable("PYTHONPATH", "$env:PYTHONPATH;$Path", "Machine") >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 查看当前路径 PS C:\Users\Administrator\Desktop> python -c "import sys; print('\n'.join(sys.path))" E:\AI_System E:\Python310\python310.zip E:\Python310\DLLs E:\Python310\lib E:\Python310 C:\Users\Administrator\AppData\Roaming\Python\Python310\site-packages E:\Python310\lib\site-packages PS C:\Users\Administrator\Desktop> # 方法1:使用诊断函数 PS C:\Users\Administrator\Desktop> Test-PythonEnvironment -PythonPath "E:\Python310" File "<string>", line 5 result = { ^ SyntaxError: '{' was never closed === 环境诊断报告 === 桌面路径: 在sys.path中: ❌ 桌面路径未添加 运行命令: Repair-PythonEnvironment -PythonPath 'E:\Python310' True PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 方法2:直接运行Python命令 PS C:\Users\Administrator\Desktop> python -c "import sys; print('桌面路径存在' if r'C:\Users\Administrator\Desktop' in sys.path else '路径缺失')" 路径缺失 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 方法3:创建测试模块 PS C:\Users\Administrator\Desktop> $testModule = Join-Path $desktopPath "test_module.py" PS C:\Users\Administrator\Desktop> @" >> def hello(): >> return '测试成功!' >> "@ | Out-File -FilePath $testModule -Encoding utf8 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> python -c "import test_module; print(test_module.hello())" 测试成功!
最新发布
08-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值