GetTempPath

本文详细解析了GetTempPath函数的使用方法及参数说明。GetTempPath用于获取系统的临时文件夹路径,通过指定变量长度,函数将返回相应长度的临时路径。文章举例展示了如何正确调用该函数并获取完整路径。

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

GetTempPath有关参数说明如下:
StrLen = GetTempPath(NAME_LEN, OutPath)
其中:
OutPath: 是输出临时文件夹名称的变量,它的初始值为NAME_LEN个空格,函数调用后,就不是空格了,它会把取得的临时文件夹名称存入此变量。
NAME_LEN: 是告诉函数OutPath变量的长度。
StrLen:是取得的临时文件夹名称的长度。
举例如下:
StrLen = GetTempPath(NAME_LEN, OutPath)
调用后OutPath=“C:/DOCUME~1/LJL889~1/LOCALS~1/Temp/ ”
那么,left(OutPath,StrLen )就是准确的临时文件夹名称了。
PS C:\Users\Administrator> # CurlTools.psm1 >> # ============== >> # 终极修复版模块主文件 >> >> # 初始化模块变量 >> $script:Config = $null >> $script:CurlPath = $null >> $script:ConfigDir = $null >> $script:ConfigPath = $null >> >> # 检测操作系统 - 终极兼容版 >> function script:Get-Platform { >> try { >> if ($PSVersionTable.PSEdition -eq "Core") { >> if ($IsWindows) { return "Windows" } >> elseif ($IsLinux) { return "Linux" } >> elseif ($IsMacOS) { return "macOS" } >> } else { >> # PowerShell 5.1 兼容处理 >> if ($env:OS -like "Windows*") { >> return "Windows" >> } elseif (Test-Path "/etc/os-release") { >> return "Linux" >> } else { >> return "macOS" >> } >> } >> } catch { >> return "Windows" # 默认返回Windows >> } >> } >> >> # 配置目录获取 - 无环境变量依赖 >> function script:Get-ConfigDir { >> $platform = Get-Platform >> $tempDir = [System.IO.Path]::GetTempPath() >> >> try { >> switch ($platform) { >> "Linux" { >> $homeDir = [Environment]::GetFolderPath('UserProfile') >> if (-not $homeDir) { $homeDir = "/home/$env:USER" } >> $configDir = "$homeDir/.config/curltools" >> } >> "macOS" { >> $homeDir = [Environment]::GetFolderPath('UserProfile') >> if (-not $homeDir) { $homeDir = "/Users/$env:USER" } >> $configDir = "$homeDir/Library/Application Support/CurlTools" >> } >> default { >> $appData = [Environment]::GetFolderPath('ApplicationData') >> if (-not $appData) { >> $appData = "$env:USERPROFILE\AppData\Roaming" >> } >> $configDir = "$appData\CurlTools" >> } >> } >> } catch { >> $configDir = "$tempDir\CurlTools" >> } >> >> # 确保目录存在 >> if (-not (Test-Path $configDir)) { >> New-Item -ItemType Directory -Path $configDir -Force | Out-Null >> } >> return $configDir >> } >> >> # curl路径检测 - 无依赖终极版 >> function script:Get-DefaultCurlPath { >> $platform = Get-Platform >> $knownPaths = @{ >> Windows = @( >> "C:\Windows\System32", >> "C:\Program Files\curl\bin", >> "C:\curl\bin", >> "$env:USERPROFILE\curl\bin", >> "C:\Program Files\Git\usr\bin", >> "C:\Program Files\Git\mingw64\bin" >> ) >> Linux = @("/usr/bin", "/usr/local/bin", "/bin", "/snap/bin") >> macOS = @("/usr/local/bin", "/opt/homebrew/bin", "/usr/bin", "/bin") >> } >> >> # 尝试所有已知路径 >> foreach ($path in $knownPaths[$platform]) { >> $curlExe = if ($platform -eq "Windows") { "curl.exe" } else { "curl" } >> $fullPath = Join-Path $path $curlExe >> if (Test-Path $fullPath -PathType Leaf) { >> return $path >> } >> } >> >> # 终极后备方案 - 搜索整个磁盘 >> if ($platform -eq "Windows") { >> $drives = Get-PSDrive -PSProvider FileSystem | Select-Object -ExpandProperty Root >> foreach ($drive in $drives) { >> $curlPath = Get-ChildItem -Path $drive -Filter "curl.exe" -Recurse -ErrorAction SilentlyContinue | >> Select-Object -First 1 -ExpandProperty DirectoryName >> if ($curlPath) { return $curlPath } >> } >> } >> >> return $null >> } >> >> # curl自动安装函数 >> function script:Install-Curl { >> $platform = Get-Platform >> $tempDir = [System.IO.Path]::GetTempPath() >> >> try { >> if ($platform -eq "Windows") { >> $curlZip = "$tempDir\curl.zip" >> $curlUrl = "https://curl.se/windows/dl-8.8.0_5/curl-8.8.0_5-win64-mingw.zip" >> >> # 下载并解压 >> Invoke-WebRequest -Uri $curlUrl -OutFile $curlZip -ErrorAction Stop >> Expand-Archive -Path $curlZip -DestinationPath "$tempDir\curl" -Force >> >> # 设置路径 >> $curlPath = "$tempDir\curl\curl-8.8.0_5-win64-mingw\bin" >> return $curlPath >> } else { >> # Linux/macOS 使用包管理器 >> if ($platform -eq "Linux") { >> if (Get-Command apt -ErrorAction SilentlyContinue) { >> Start-Process -Wait -NoNewWindow -FilePath "sudo" -ArgumentList "apt", "update" >> Start-Process -Wait -NoNewWindow -FilePath "sudo" -ArgumentList "apt", "install", "-y", "curl" >> } elseif (Get-Command yum -ErrorAction SilentlyContinue) { >> Start-Process -Wait -NoNewWindow -FilePath "sudo" -ArgumentList "yum", "install", "-y", "curl" >> } >> } else { >> # macOS >> if (Get-Command brew -ErrorAction SilentlyContinue) { >> brew install curl >> } else { >> Start-Process -Wait -NoNewWindow -FilePath "/bin/bash" -ArgumentList "-c", "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" >> brew install curl >> } >> } >> >> # 获取安装路径 >> return (Get-Command curl -ErrorAction SilentlyContinue).Source | Split-Path >> } >> } catch { >> Write-Warning "curl自动安装失败: $_" >> return $null >> } >> } >> >> # 模块初始化 - 无依赖实现 >> function script:Initialize-ModuleConfig { >> try { >> # 获取配置目录 >> $script:ConfigDir = Get-ConfigDir >> $script:ConfigPath = Join-Path -Path $script:ConfigDir -ChildPath "config.json" >> >> # 加载或创建默认配置 >> if (Test-Path $script:ConfigPath) { >> try { >> $script:Config = Get-Content $script:ConfigPath | ConvertFrom-Json >> } catch { >> $script:Config = $null >> } >> } >> >> if (-not $script:Config) { >> $defaultPath = Get-DefaultCurlPath >> >> if (-not $defaultPath) { >> # 终极后备方案 - 下载curl >> $defaultPath = Install-Curl >> } >> >> $script:Config = [PSCustomObject]@{ >> CurlPath = $defaultPath >> LastUpdate = (Get-Date).ToString("o") >> AutoUpdate = $true >> } >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> } >> >> # 设置模块路径 >> $script:CurlPath = $script:Config.CurlPath >> return $true >> } catch { >> return $false >> } >> } >> >> # ========== 公共函数定义 ========== >> function Get-CurlPath { >> # 延迟初始化 >> if (-not $script:Config) { >> Initialize-ModuleConfig | Out-Null >> } >> return $script:CurlPath >> } >> >> function Set-CurlPath { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Path >> ) >> # 延迟初始化 >> if (-not $script:Config) { >> Initialize-ModuleConfig | Out-Null >> } >> >> $script:CurlPath = $Path >> $env:Path = "$Path;$env:Path" >> Write-Host "手动设置curl路径: $Path" -ForegroundColor Green >> >> # 更新配置 >> if ($script:Config) { >> $script:Config.CurlPath = $Path >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> } >> } >> >> function Get-CurlVersion { >> # 延迟初始化 >> if (-not $script:Config) { >> Initialize-ModuleConfig | Out-Null >> } >> >> $curlExe = if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" } >> $fullPath = Join-Path $script:CurlPath $curlExe >> & $fullPath --version | Select-Object -First 1 >> } >> >> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Url, >> >> [Parameter(Mandatory=$true)] >> [string]$OutputPath, >> >> [string]$ExpectedHash, >> [string]$HashAlgorithm = "SHA256" >> ) >> >> try { >> # 下载文件 >> Write-Verbose "下载文件: $Url" >> $ProgressPreference = 'SilentlyContinue' >> Invoke-WebRequest -Uri $Url -OutFile $OutputPath -UseBasicParsing >> >> # 验证哈希 >> if (-not [string]::IsNullOrWhiteSpace($ExpectedHash)) { >> $actualHash = (Get-FileHash -Path $OutputPath -Algorithm $HashAlgorithm).Hash >> if ($actualHash -ne $ExpectedHash) { >> Remove-Item -Path $OutputPath -Force >> throw "文件哈希不匹配! 期望: $ExpectedHash, 实际: $actualHash" >> } >> } >> >> return $OutputPath >> } catch { >> Write-Error "下载失败: $_" >> return $null >> } >> } >> >> # ========== 模块初始化 ========== >> # 使用脚本作用域函数进行初始化 >> try { >> $initSuccess = Initialize-ModuleConfig >> if (-not $initSuccess) { >> # 终极后备方案 - 使用临时curl >> $tempCurl = Install-Curl >> if ($tempCurl) { >> $script:CurlPath = $tempCurl >> Write-Warning "使用临时curl路径: $script:CurlPath" >> } else { >> Write-Warning "模块初始化失败且无法安装curl" >> } >> } >> } catch { >> Write-Warning "模块初始化错误: $_" >> } >> >> # ========== 模块导出区域 ========== >> # 必须在所有函数定义后,模块末尾执行 >> $exportFunctions = @( >> 'Get-CurlPath' >> 'Set-CurlPath' >> 'Get-CurlVersion' >> 'Invoke-SecureDownload' >> ) >> >> Export-ModuleMember -Function $exportFunctions >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:294 字符: 1 + Export-ModuleMember -Function $exportFunctions + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator>
08-13
PS C:\Users\Administrator> # CurlTools.psm1 >> # ============== >> # 完整修复的模块代码 >> >> # 模块初始化块 >> $script:Config = $null >> $script:CurlPath = $null >> $script:ConfigDir = $null >> $script:ConfigPath = $null >> $script:ModuleInitialized = $false >> >> # 检测操作系统 >> function Get-Platform { >> if ($PSVersionTable.PSEdition -eq "Core") { >> if ($IsWindows) { "Windows" } >> elseif ($IsLinux) { "Linux" } >> elseif ($IsMacOS) { "macOS" } >> } else { >> if ($env:OS -like "Windows*") { "Windows" } >> elseif (Test-Path "/etc/os-release") { "Linux" } >> else { "macOS" } >> } >> } >> >> # 获取配置目录 >> function Get-ConfigDir { >> $platform = Get-Platform >> switch ($platform) { >> "Linux" { "$HOME/.config/curltools" } >> "macOS" { "$HOME/Library/Application Support/CurlTools" } >> default { "$env:APPDATA\CurlTools" } >> } >> } >> >> # 核心初始化函数 >> function Initialize-Module { >> try { >> # 设置配置目录 >> $script:ConfigDir = Get-ConfigDir >> if (-not (Test-Path $script:ConfigDir)) { >> New-Item -ItemType Directory -Path $script:Config极乐净土Dir -Force | Out-Null >> } >> $script:ConfigPath = Join-Path $script:ConfigDir "config.json" >> >> # 加载或创建配置 >> if (Test-Path $script:ConfigPath) { >> $script:Config = Get-Content $script:ConfigPath | ConvertFrom-Json >> } >> >> if (-not $script:Config) { >> $script:Config = [PSCustomObject]@{ >> CurlPath = $null >> LastUpdate = (Get-Date).ToString("o") >> AutoUpdate = $true >> } >> } >> >> # 查找或安装curl >> if (-not $script:Config.CurlPath -or -not (Test-Path $script:Config.CurlPath)) { >> $script:Config.CurlPath = Find-CurlPath >> } >> >> # 保存配置 >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> $script:CurlPath = $script:Config.CurlPath >> $script:ModuleInitialized = $true >> >> return $true >> } catch { >> Write-Warning "模块初始化失败: $_" >> return $false >> } >> } >> >> # 查找curl路径 >> function Find-CurlPath { >> $platform = Get-Platform >> $exeName = if ($platform -eq "Windows") { "curl.exe" } else { "curl" } >> >> # 检查系统PATH >> $pathCurl = Get-Command $exeName -ErrorAction SilentlyContinue >> if ($pathCurl) { >> return $pathCurl.Source | Split-Path >> } >> >> # 平台特定路径 >> $searchPaths = switch ($platform) { >> "Windows" { >> @( >> "C:\Windows\System32", >> "C:\Program Files\curl\bin", >> "${env:ProgramFiles}\Git\usr\bin" >> ) >> } >> "Linux" { @("/极乐净土usr/bin", "/usr/local/bin") } >> "macOS" { @("/usr/local/bin", "/opt/homebrew/bin") } >> } >> >> foreach ($path in $searchPaths) { >> $fullPath = Join-Path $path $exeName >> if (Test-Path $fullPath) { >> return $path >> } >> } >> >> # 终极方案:自动安装 >> return Install-Curl >> } >> >> # curl安装函数 >> function Install-Curl { >> $platform = Get-Platform >> try { >> if ($platform -eq "Windows") { >> $tempDir = [System.IO.Path]::GetTempPath() >> $curlZip = Join-Path $tempDir "curl.zip" >> $curlUrl = "https://curl.se/windows/dl-8.8.0_5/curl-8.8.0_5-win64-mingw.zip" >> >> # 使用安全下载函数 >> Invoke-SecureDownload -Url $curlUrl -OutputPath $curlZip >> >> Expand-Archive $curlZip -DestinationPath $tempDir -Force >> >> # 验证安装目录是否存在 >> $installDir = Join-Path $tempDir "curl-8.8.0_5-win64-mingw\bin" >> if (-not (Test-Path $installDir)) { >> throw "安装目录不存在: $installDir" >> } >> >> return $installDir >> } >> else { >> if ($platform -eq "Linux") { >> if (Get-Command apt -ErrorAction SilentlyContinue) { >> Start-Process -Wait -FilePath "sudo" -ArgumentList "apt", "update" >> Start-Process -Wait -FilePath "sudo" -ArgumentList "apt", "install", "-y", "curl" >> } elseif (Get-Command yum -ErrorAction SilentlyContinue) { >> Start-Process -Wait -FilePath "sudo" -ArgumentList "yum", "install", "-y", "curl" >> } >> return "/usr/bin" >> } >> else { >> if (-not (Get-Command brew -ErrorAction SilentlyContinue)) { >> # 使用安全下载安装Homebrew >> $installScript = Join-Path $env:TEMP "brew_install.sh" >> Invoke-SecureDownload -Url "https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh" -OutputPath $installScript >> & "/bin/bash" $installScript >> } >> Start-Process -Wait -FilePath "brew" -ArgumentList "install", "curl" >> return "/usr/local/bin" >> } >> } >> } catch { >> throw "无法自动安装curl: $_" >> } >> } >> >> # ========== 公共函数 ========== >> function Get-CurlPath { >> Ensure-ModuleInitialized >> return $script:CurlPath >> } >> >> function Set-CurlPath { >> param( >> [Parameter(Mandatory=$true)] >> [ValidateScript({ >> # 允许设置不存在的路径(创建前) >> if (-not (Test-Path $_)) { >> Write-Warning "路径不存在,将在设置后创建: $_" >> $true >> } else { >> $true >> } >> })] >> [string]$Path >> ) >> >> Ensure-ModuleInitialized >> >> # 确保路径存在 >> if (-not (Test-Path $Path)) { >> New-Item -ItemType Directory -Path $Path -Force | Out-Null >> } >> >> $script:CurlPath = $Path >> $script:Config.CurlPath = $Path >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> Write-Host "已设置curl路径: $Path" -ForegroundColor Green >> >> # 验证路径下是否有curl可执行文件 >> $exeName = if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" } >> $curlExe = Join-Path $Path $exeName >> if (-not (Test-Path $curlExe)) { >> try { >> Write-Warning "路径 $Path 下找不到 $exeName,尝试自动安装..." >> $script:Config.CurlPath = Install-Curl >> $script:CurlPath = $script:Config.CurlPath >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> Write-Host "已自动安装curl到: $script:CurlPath" -ForegroundColor Green >> >> # 再次验证安装结果 >> $curlExe = Join-Path $script:CurlPath $exeName >> if (-not (Test-Path $curlExe)) { >> throw "自动安装后仍未找到curl可执行文件" >> } >> } catch { >> throw "自动安装失败: $_" >> } >> } >> } >> >> function Get-CurlVersion { >> Ensure-ModuleInitialized >> $exe = if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" } >> $curlExe = Join-Path $script:CurlPath $exe >> >> # 检查可执行文件是否存在 >> if (-not (Test-Path $curlExe)) { >> throw "在路径 $script:CurlPath 下找不到 $exe,请使用Set-CurlPath设置正确的路径或重新初始化模块" >> } >> >> & $curlExe --version | Select-Object -First 1 >> } >> >> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Url, >> >> [Parameter(Mandatory=$true)] >> [string]$OutputPath, >> >> [string]$ExpectedHash, >> [string]$HashAlgorithm = "SHA256" >> ) >> >> # 添加重试机制 >> $maxRetries = 3 >> $retryCount = 0 >> $success = $false >> >> do { >> try { >> Write-Verbose "下载文件: $Url (尝试 #$($retryCount + 1))" >> $ProgressPreference = 'SilentlyContinue' >> >> # 创建输出目录(如果不存在) >> $outputDir = [System.IO.Path]::GetDirectoryName($OutputPath) >> if (-not [string]::IsNullOrWhiteSpace($outputDir) -and -not (Test-Path $outputDir)) { >> New-Item -ItemType Directory -Path $outputDir -Force | Out-Null >> } >> >> # 下载文件 >> Invoke-WebRequest -Uri $Url -OutFile $OutputPath -UseBasicParsing -ErrorAction Stop >> >> # 验证文件是否成功下载 >> if (-not (Test-Path $OutputPath)) { >> throw "文件下载后未找到: $OutputPath" >> } >> >> # 验证哈希(如果提供) >> if (-not [string]::IsNullOrWhiteSpace($ExpectedHash)) { >> $actualHash = (Get-FileHash -Path $OutputPath -Algorithm $HashAlgorithm).Hash >> if ($actualHash -ne $ExpectedHash) { >> Remove-Item -Path $OutputPath -Force >> throw "文件哈希不匹配! 期望: $ExpectedHash, 实际: $actualHash" >> } >> } >> >> $success = $true >> return $OutputPath >> } >> catch { >> $retryCount++ >> if ($retryCount -ge $maxRetries) { >> # 清理部分下载的文件 >> if (Test-Path $OutputPath) { >> Remove-Item -Path $OutputPath -Force -ErrorAction SilentlyContinue >> } >> throw "下载失败: $($_.Exception.Message)" >> } >> >> # 随机延迟后重试 >> $retryDelay = Get-Random -Minimum 1 -Maximum 5 >> Write-Warning "下载失败,$retryDelay 秒后重试: $($_.Exception.Message)" >> Start-Sleep -Seconds $retryDelay >> } >> } while (-not $success) >> } >> >> # ========== 辅助函数 ========== >> function Ensure-ModuleInitialized { >> if (-not $script:ModuleInitialized) { >> if (-not (Initialize-Module)) { >> throw "模块未正确初始化" >> } >> } >> } >> >> # ========== 模块初始化 ========== >> # 尝试初始化但不强制 >> try { >> Initialize-Module | Out-Null >> Write-Verbose "CurlTools 模块初始化成功" >> } catch { >> Write-Warning "模块初始化错误: $_" >> } >> >> # ========== 函数导出 ========== >> # 导出公共函数 >> Export-ModuleMember -Function Get-CurlPath, Set-CurlPath, Get-CurlVersion, Invoke-SecureDownload >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:312 字符: 1 + Export-ModuleMember -Function Get-CurlPath, Set-CurlPath, Get-CurlVer ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> # Install-CurlTools.ps1 >> >> # 创建模块目录 >> $moduleDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\CurlTools" >> New-Item -ItemType Directory -Path $moduleDir -Force | Out-Null >> >> # 保存模块代码 >> $moduleCode = @' >> # 将上面的完整模块代码粘贴在这里(移除所有乱码) >> '@ >> >> Set-Content -Path "$moduleDir\CurlTools.psm1" -Value $moduleCode -Force >> >> # 创建模块清单 >> $manifest = @" >> @{ >> ModuleVersion = '1.9.0' >> RootModule = 'CurlTools.psm1' >> FunctionsToExport = @( >> 'Get-CurlPath', >> 'Set-CurlPath', >> 'Get-CurlVersion', >> 'Invoke-S极乐净土ecureDownload' >> ) >> CompatiblePSEditions = @('Desktop', 'Core') >> GUID = 'c0d1b1e1-1a2b-4c3d-8e4f-9a0b1c2d3e4f' >> Author = 'Your Name' >> Description = 'Powerful curl tools for PowerShell' >> } >> "@ >> >> Set-Content -Path "$moduleDir\CurlTools.psd1" -Value $manifest -Force >> >> # 重新加载模块 >> Remove-Module CurlTools -ErrorAction SilentlyContinue >> Import-Module $moduleDir -Force -Verbose >> >> # 测试模块 >> if (Get-Module CurlTools) { >> Write-Host "CurlTools 模块安装成功!" -ForegroundColor Green >> >> # 测试基本功能 >> try { >> $curlPath = Get-CurlPath >> Write-Host "Curl路径: $curlPath" >> >> # 测试设置新路径 >> $newPath = Join-Path $env:TEMP "CurlTestPath" >> Set-CurlPath -Path $newPath >> >> $curlPath = Get-CurlPath >> Write-Host "新Curl路径: $curlPath" >> >> $version = Get-CurlVersion >> Write-Host "Curl版本: $version" >> >> # 测试下载功能 >> $testUrl = "https://raw.githubusercontent.com/PowerShell/PowerShell/master/README.md" >> $outputPath = Join-Path $env:TEMP "PowerShell_README.md" >> Invoke-SecureDownload -Url $testUrl -OutputPath $outputPath >> Write-Host "测试下载成功: $outputPath" -ForegroundColor Green >> } catch { >> Write-Warning "基本功能测试失败: $_" >> } >> } else { >> Write-Error "模块安装失败,请检查。" >> } >> 详细信息: 正在从路径“C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psd1”加载模块。 详细信息: 正在从路径“C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psm1”加载模块。 CurlTools 模块安装成功! Curl路径: E:\ai_temp\CurlTestPath 已设置curl路径: E:\ai_temp\CurlTestPath 警告: 路径 E:\ai_temp\CurlTestPath 下找不到 curl.exe,尝试自动安装... 警告: 下载失败,4 秒后重试: 远程服务器返回错误: (404) 未找到。 警告: 下载失败,2 秒后重试: 远程服务器返回错误: (404) 未找到。 警告: 基本功能测试失败: 自动安装失败: 无法自动安装curl: 下载失败: 远程服务器返回错误: (404) 未找到。 PS C:\Users\Administrator> # 模块目录结构 >> # CurlTools/ >> # ├── Public/ >> # │ ├── Get-CurlPath.ps1 >> # │ ├── Set-CurlPath.ps1 >> # │ ├── Get-CurlVersion.ps1 >> # │ └── Invoke-SecureDownload.ps1 >> # ├── Private/ >> # │ ├── Get-Platform.ps1 >> # │ ├── Get-ConfigDir.ps1 >> # │ ├── Initialize-Module.ps1 >> # │ ├── Find-CurlPath.ps1 >> # │ └── Install-Curl.ps1 >> # └── CurlTools.psm1 >> >> # CurlTools.psm1 内容 >> $publicFunctions = Get-ChildItem -Path "$PSScriptRoot\Public\*.ps1" -ErrorAction SilentlyContinue >> $privateFunctions = Get-ChildItem -Path "$PSScriptRoot\Private\*.ps1" -ErrorAction SilentlyContinue >> >> # 导入所有函数 >> foreach ($file in @($publicFunctions + $privateFunctions)) { >> try { >> . $file.FullName >> } catch { >> Write-Error "导入函数 $($file.FullName) 失败: $_" >> } >> } >> >> # 导出公共函数 >> $functionsToExport = $publicFunctions | ForEach-Object { $_.BaseName } >> Export-ModuleMember -Function $functionsToExport >> >> # 初始化模块 >> Initialize-Module >> # 模块目录结构 # CurlTools/ # ├── Public/ # │ ├── Get-CurlPath.ps1 # │ ├── Set-CurlPath.ps1 # │ ├── Get-CurlVersion.ps1 # │ └── Invoke-SecureDownload.ps1 # ├── Private/ # │ ├── Get-Platform.ps1 # │ ├── Get-ConfigDir.ps1 # │ ├── Initialize-Module.ps1 # │ ├── Find-CurlPath.ps1 # │ └── Install-Curl.ps1 # └── CurlTools.psm1 # CurlTools.psm1 内容 $publicFunctions = Get-ChildItem -Path "$PSScriptRoot\Public\*.ps1" -ErrorAction SilentlyContinue $privateFunctions = Get-ChildItem -Path "$PSScriptRoot\Private\*.ps1" -ErrorAction SilentlyContinue # 导入所有函数 foreach ($file in @($publicFunctions + $privateFunctions)) { try { . $file.FullName } catch { Write-Error "导入函数 $($file.FullName) 失败: $_" } } # 导出公共函数 $functionsToExport = $publicFunctions | ForEach-Object { $_.BaseName } Export-ModuleMember -Function $functionsToExport # 初始化模块 Initialize-Module : 导入函数 失败: 管道元素中的“.”后面的表达式生成无效的对象。该表达式必须生成命令名称、脚本块或 CommandInfo 对象。 + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:31 字符: 1 + Export-ModuleMember -Function $functionsToExport + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand True PS C:\Users\Administrator> # Test-CurlTools.ps1 >> >> # 加载模块 >> Import-Module CurlTools -Force >> >> # 测试1:获取Curl路径 >> try { >> $path = Get-CurlPath >> Write-Host "测试1: 当前Curl路径: $path" -ForegroundColor Cyan >> } catch { >> Write-Warning "测试1失败: $_" >> } >> >> # 测试2:设置新的Curl路径 >> try { >> $newPath = Join-Path $env:TEMP "CurlTestPath" >> Set-CurlPath -Path $newPath >> } catch { >> Write-Warning "测试2失败: $_" >> } >> >> # 测试3:再次获取Curl路径 >> try { >> $newPathActual = Get-CurlPath >> Write-Host "测试3: 设置后的Curl路径: $newPathActual" -ForegroundColor Cyan >> } catch { >> Write-Warning "测试3失败: $_" >> } >> >> # 测试4:获取Curl版本 >> try { >> $version = Get-CurlVersion >> Write-Host "测试4: Curl版本: $version" -ForegroundColor Cyan >> } catch { >> Write-Warning "测试4失败: $_" >> } >> >> # 测试5:安全下载 >> try { >> $testUrl = "https://raw.githubusercontent.com/PowerShell/PowerShell/master/README.md" >> $outputFile = Join-Path $env:TEMP "PowerShell_README.md" >> Invoke-SecureDownload -Url $testUrl -OutputPath $outputFile >> if (Test-Path $outputFile) { >> Write-Host "测试5: 文件下载成功: $outputFile" -ForegroundColor Green >> } else { >> Write-Host "测试5: 文件下载失败" -ForegroundColor Red >> } >> } catch { >> Write-Warning "测试5失败: $_" >> } >> >> # 测试6:带哈希验证的下载 >> try { >> $expectedHash = (Get-FileHash -Path $outputFile -Algorithm SHA256).Hash >> $outputFile2 = Join-Path $env:TEMP "PowerShell_README_Verified.md" >> Invoke-SecureDownload -Url $testUrl -OutputPath $outputFile2 -ExpectedHash $expectedHash -HashAlgorithm SHA256 >> if (Test-Path $outputFile2) { >> Write-Host "测试6: 带哈希验证的文件下载成功" -ForegroundColor Green >> } else { >> Write-Host "测试6: 带哈希验证的文件下载失败" -ForegroundColor Red >> } >> } catch { >> Write-Warning "测试6失败: $_" >> } >> 测试1: 当前Curl路径: E:\ai_temp\CurlTestPath 已设置curl路径: E:\ai_temp\CurlTestPath 警告: 路径 E:\ai_temp\CurlTestPath 下找不到 curl.exe,尝试自动安装... 警告: 下载失败,4 秒后重试: 远程服务器返回错误: (404) 未找到。 警告: 下载失败,4 秒后重试: 远程服务器返回错误: (404) 未找到。 警告: 测试2失败: 自动安装失败: 无法自动安装curl: 下载失败: 远程服务器返回错误: (404) 未找到。 测试3: 设置后的Curl路径: E:\ai_temp\CurlTestPath 警告: 测试4失败: 在路径 E:\ai_temp\CurlTestPath 下找不到 curl.exe,请使用Set-CurlPath设置正确的路径或重新初始化模块
最新发布
08-13
PS C:\Users\Administrator> # CurlTools.psm1 >> # ============== >> # 完整修复的模块代码 >> >> # 模块初始化块 >> $script:Config = $null >> $script:CurlPath = $null >> $script:ConfigDir = $null >> $script:ConfigPath = $null >> $script:ModuleInitialized = $false >> >> # 检测操作系统 >> function Get-Platform { >> if ($PSVersionTable.PSEdition -eq "Core") { >> if ($IsWindows) { "Windows" } >> elseif ($IsLinux) { "Linux" } >> elseif ($IsMacOS) { "macOS" } >> } else { >> if ($env:OS -like "Windows*") { "Windows" } >> elseif (Test-Path "/etc/os-release") { "Linux" } >> else { "macOS" } >> } >> } >> >> # 获取配置目录 >> function Get-ConfigDir { >> $platform = Get-Platform >> switch ($platform) { >> "Linux" { "$HOME/.config/curltools" } >> "macOS" { "$HOME/Library/Application Support/CurlTools" } >> default { "$env:APPDATA\CurlTools" } >> } >> } >> >> # 核心初始化函数 >> function Initialize-Module { >> try { >> # 设置配置目录 >> $script:ConfigDir = Get-ConfigDir >> if (-not (Test-Path $script:ConfigDir)) { >> New-Item -ItemType Directory -Path $script:ConfigDir -Force | Out-Null >> } >> $script:ConfigPath = Join-Path $script:ConfigDir "config.json" >> >> # 加载或创建配置 >> if (Test-Path $script:ConfigPath) { >> $script:Config = Get-Content $script:ConfigPath | ConvertFrom-Json >> } >> >> if (-not $script:Config) { >> $script:Config = [PSCustomObject]@{ >> CurlPath = $null >> LastUpdate = (Get-Date).ToString("o") >> AutoUpdate = $true >> } >> } >> >> # 查找或安装curl >> if (-not $script:Config.CurlPath -or -not (Test-Path $script:Config.CurlPath)) { >> $script:Config.CurlPath = Find-CurlPath >> } >> >> # 保存配置 >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> $script:CurlPath = $script:Config.CurlPath >> $script:ModuleInitialized = $true >> >> return $true >> } catch { >> Write-Warning "模块初始化失败: $_" >> return $false >> } >> } >> >> # 查找curl路径 >> function Find-CurlPath { >> $platform = Get-Platform >> $exeName = if ($platform -eq "Windows") { "curl.exe" } else { "curl" } >> >> # 检查系统PATH >> $pathCurl = Get-Command $exeName -ErrorAction SilentlyContinue >> if ($pathCurl) { >> return $pathCurl.Source | Split-Path >> } >> >> # 平台特定路径 >> $searchPaths = switch ($platform) { >> "Windows" { >> @( >> "C:\Windows\System32", >> "C:\Program Files\curl\bin", >> "${env:ProgramFiles}\Git\usr\bin" >> ) >> } >> "Linux" { @("/usr/bin", "/usr/local/bin") } >> "macOS" { @("/usr/local/bin", "/opt/homebrew/bin") } >> } >> >> foreach ($path in $searchPaths) { >> $fullPath = Join-Path $path $exeName >> if (Test-Path $fullPath) { >> return $path >> } >> } >> >> # 终极方案:自动安装 >> return Install-Curl >> } >> >> # curl安装函数 >> function Install-Curl { >> $platform = Get-Platform >> try { >> if ($platform -eq "Windows") { >> $tempDir = [System.IO.Path]::GetTempPath() >> $curlZip = Join-PPath $tempDir "curl.zip" >> $curlUrl = "https://curl.se/windows/dl-8.8.0_5/curl-8.8.0_5-win64-mingw.zip" >> >> # 使用安全下载函数 >> Invoke-SecureDownload -Url $curlUrl -OutputPath $curlZip >> >> Expand-Archive $curlZip -DestinationPath $tempDir -Force >> return Join-Path $tempDir "curl-8.8.0_5-win64-mingw\bin" >> } >> else { >> if ($platform -eq "Linux") { >> if (Get-Command apt -ErrorAction SilentlyContinue) { >> Start-Process -Wait -FilePath "sudo" -ArgumentList "apt", "update" >> Start-Process -Wait -FilePath "sudo" -ArgumentList "apt", "install", "-y", "curl" >> } elseif (Get-Command yum -ErrorAction SilentlyContinue) { >> Start-Process -Wait -FilePath "sudo" -ArgumentList "yum", "install", "-y", "curl" >> } >> return "/usr/bin" >> } >> else { >> if (-not (Get-Command brew -ErrorAction SilentlyContinue)) { >> # 使用安全下载安装Homebrew >> $installScript = Join-Path $env:TEMP "brew_install.sh" >> Invoke-SecureDownload -Url "https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh" -OutputPath $installScript >> & "/bin/bash" $installScript >> } >> Start-Process -Wait -FilePath "brew" -ArgumentList "install", "curl" >> return "/usr/local/bin" >> } >> } >> } catch { >> throw "无法自动安装curl: $_" >> } >> } >> >> # ========== 公共函数 ========== >> function Get-CurlPath { >> Ensure-ModuleInitialized >> return $script:CurlPath >> } >> >> function Set-CurlPath { >> param( >> [Parameter(Mandatory=$true)] >> [ValidateScript({ >> # 允许设置不存在的路径(创建前) >> if (-not (Test-Path $_)) { >> Write-Warning "路径不存在,将在设置后创建: $_" >> $true >> } else { >> $true >> } >> })] >> [string]$Path >> ) >> >> Ensure-ModuleInitialized >> >> # 确保路径存在 >> if (-not (Test-Path $Path)) { >> New-Item -ItemType Directory -Path $Path -Force | Out-Null >> } >> >> $script:CurlPath = $Path >> $script:Config.CurlPath = $Path >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> Write-Host "已设置curl路径: $Path" -ForegroundColor Green >> >> # 验证路径下是否有curl可执行文件 >> $exeName = if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" } >> $curlExe = Join-Path $Path $exeName >> if (-not (Test-Path $curlExe)) { >> Write-Warning "路径 $Path 下找不到 $exeName,尝试自动安装..." >> $script:Config.CurlPath = Install-Curl >> $script:CurlPath = $script:Config.CurlPath >> $script:Config | ConvertTo-Json | Set-Content $script:ConfigPath -Force >> Write-Host "已自动安装curl到: $script:CurlPath" -ForegroundColor Green >> } >> } >> >> function Get-CurlVersion { >> Ensure-ModuleInitialized >> $exe = if ((Get-Platform) -eq "Windows") { "curl.exe" } else { "curl" } >> $curlExe = Join-Path $script:CurlPath $exe >> >> # 检查可执行文件是否存在 >> if (-not (Test-Path $curlExe)) { >> throw "在路径 $script:CurlPath 下找不到 $exe,请使用Set-CurlPath设置正确的路径或重新初始化模块" >> } >> >> & $curlExe --version | Select-Object -First 1 >> } >> >> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Url, >> >> [Parameter(Mandatory=$true)] >> [string]$OutputPath, >> >> [string]$ExpectedHash, >> [string]$HashAlgorithm = "SHA256" >> ) >> >> # 添加重试机制 >> $maxRetries = 3 >> $retryCount = 0 >> $success = $false >> >> do { >> try { >> Write-Verbose "下载文件: $Url (尝试 #$($retryCount + 1))" >> $ProgressPreference = 'SilentlyContinue' >> >> # 创建输出目录(如果不存在) >> $outputDir = [System.IO.Path]::GetDirectoryName($OutputPath) >> if (-not [string]::IsNullOrWhiteSpace($outputDir) -and -not (Test-Path $outputDir)) { >> New-Item -ItemType Directory -Path $outputDir -Force | Out-Null >> } >> >> # 下载文件 >> Invoke-WebRequest -Uri $Url -OutFile $OutputPath -UseBasicParsing -ErrorAction Stop >> >> # 验证文件是否成功下载 >> if (-not (Test-Path $OutputPath)) { >> throw "文件下载后未找到: $OutputPath" >> } >> >> # 验证哈希(如果提供) >> if (-not [string]::IsNullOrWhiteSpace($ExpectedHash)) { >> $actualHash = (Get-FileHash -Path $OutputPath -Algorithm $HashAlgorithm).Hash >> if ($actualHash -ne $ExpectedHash) { >> Remove-Item -Path $OutputPath -Force >> throw "文件哈希不匹配! 期望: $ExpectedHash, 实际: $actualHash" >> } >> } >> >> $success = $true >> return $OutputPath >> } >> catch { >> $retryCount++ >> if ($retryCount -ge $maxRetries) { >> # 清理部分下载的文件 >> if (Test-Path $OutputPath) { >> Remove-Item -Path $OutputPath -Force -ErrorAction SilentlyContinue >> } >> throw "下载失败: $($_.Exception.Message)" >> } >> >> # 随机延迟后重试 >> $retryDelay = Get-Random -Minimum 1 -Maximum 5 >> Write-Warning "下载失败,$retryDelay 秒后重试: $($_.Exception.Message)" >> Start-Sleep -Seconds $retryDelay >> } >> } while (-not $success) >> } >> >> # ========== 辅助函数 ========== >> function Ensure-ModuleInitialized { >> if (-not $script:ModuleInitialized) { >> if (-not (Initialize-Module)) { >> throw "模块未正确初始化" >> } >> } >> } >> >> # ========== 模块初始化 ========== >> # 尝试初始化但不强制 >> try { >> Initialize-Module | Out-Null >> Write-Verbose "CurlTools 模块初始化成功" >> } catch { >> Write-Warning "模块初始化错误: $_" >> } >> >> # ========== 函数导出 ========== >> # 导出公共函数 >> Export-ModuleMember -Function Get-CurlPath, Set-CurlPath, Get-CurlVersion, Invoke-SecureDownload >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:295 字符: 1 + Export-ModuleMember -Function Get-CurlPath, Set-CurlPath, Get-CurlVer ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> # Install-CurlTools.ps1 >> >> # 创建模块目录 >> $moduleDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\CurlTools" >> New-Item -ItemType Directory -Path $moduleDir -Force | Out-Null >> >> # 保存模块代码 >> $moduleCode = @' >> # 将上面的完整模块代码粘贴在这里 >> '@ >> >> Set-Content -Path "$moduleDir\CurlTools.psm1" -Value $moduleCode -Force >> >> # 创建模块清单 >> $manifest = @" >> @{ >> ModuleVersion = '1.6.0' >> RootModule = 'CurlTools.psm1' >> FunctionsToExport = @( >> 'Get-CurlPath', >> 'Set-CurlPath', >> 'Get-CurlVersion', >> 'Invoke-SecureDownload' >> ) >> CompatiblePSEditions = @('Desktop', 'Core') >> GUID = 'c0d1b1e1-1a2b-4c3d-8e4f-9a0b1c2d3e4f' >> Author = 'Your Name' >> Description = 'Powerful curl tools for PowerShell' >> } >> "@ >> >> Set-Content -Path "$moduleDir\CurlTools.psd1" -Value $manifest -Force >> >> # 重新加载模块 >> Remove-Module CurlTools -ErrorAction SilentlyContinue >> Import-Module CurlTools -Force -Verbose >> >> # 测试模块 >> if (Get-Module CurlTools) { >> Write-Host "CurlTools 模块安装成功!" -ForegroundColor Green >> >> # 测试基本功能 >> try { >> $curlPath = Get-CurlPath >> Write-Host "Curl路径: $curlPath" >> $version = Get-CurlVersion >> Write-Host "Curl版本: $version" >> >> # 测试下载功能 >> $testUrl = "https://raw.githubusercontent.com/PowerShell/PowerShell/master/README.md" >> $outputPath = "$env:TEMP\PowerShell_README.md" >> Invoke-SecureDownload -Url $testUrl -OutputPath $outputPath >> Write-Host "测试下载成功: $outputPath" -ForegroundColor Green >> } catch { >> Write-Warning "基本功能测试失败: $_" >> } >> } else { >> Write-Error "模块安装失败,请检查。" >> } >> 详细信息: 正在从路径“C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psd1”加载模块。 详细信息: 正在从路径“C:\Users\Administrator\Documents\WindowsPowerShell\Modules\CurlTools\CurlTools.psm1”加载模块。 CurlTools 模块安装成功! Curl路径: C:\Custom\Curl\Path 警告: 基本功能测试失败: 在路径 C:\Custom\Curl\Path 下找不到 curl.exe,请使用Set-CurlPath设置正确的路径或重新初始化模块 PS C:\Users\Administrator> # 使用模块化结构组织代码 >> $publicFunctions = @( >> 'Get-CurlPath' >> 'Set-CurlPath' >> 'Get-CurlVersion' >> 'Invoke-SecureDownload' >> ) >> >> $privateFunctions = @( >> 'Get-Platform' >> 'Get-ConfigDir' >> 'Initialize-Module' >> 'Find-CurlPath' >> 'Install-Curl' >> 'Ensure-ModuleInitialized' >> ) >> >> # 导出公共函数 >> Export-ModuleMember -Function $publicFunctions >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:19 字符: 1 + Export-ModuleMember -Function $publicFunctions + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> # 添加详细的日志记录 >> function Write-ModuleLog { >> param( >> [string]$Message, >> [ValidateSet('Info', 'Warning', 'Error')] >> [string]$Level = 'Info' >> ) >> >> $logEntry = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] [$Level] $Message" >> $logPath = Join-Path $script:ConfigDir "curltools.log" >> >> Add-Content -Path $logPath -Value $logEntry >> >> switch ($Level) { >> 'Info' { Write-Verbose $Message } >> 'Warning' { Write-Warning $Message } >> 'Error' { Write-Error $Message } >> } >> } >> PS C:\Users\Administrator> # 使用 .NET 方法替代 PowerShell cmdlet 提高性能 >> function Invoke-FastDownload { >> param( >> [string]$Url, >> [string]$OutputPath >> ) >> >> $httpClient = [System.Net.Http.HttpClient]::new() >> $response = $httpClient.GetAsync($Url).Result >> $fileStream = [System.IO.File]::OpenWrite($OutputPath) >> $response.Content.CopyToAsync($fileStream).Wait() >> $fileStream.Close() >> } >> PS C:\Users\Administrator> function Update-CurlTools { >> param([switch]$Force) >> >> try { >> $updateUrl = "https://api.github.com/repos/yourname/curltools/releases/latest" >> $response = Invoke-RestMethod $updateUrl >> $latestVersion = [Version]$response.tag_name >> $currentVersion = [Version](Get-Module CurlTools).Version >> >> if ($latestVersion -gt $currentVersion -or $Force) { >> Write-Host "正在更新模块到版本 $latestVersion" >> >> # 下载更新包 >> $updatePackage = Join-Path $env:TEMP "curltools-update.zip" >> $downloadUrl = $response.assets | >> Where-Object { $_.name -like "*.zip" } | >> Select-Object -First 1 -ExpandProperty browser_download_url >> >> Invoke-SecureDownload -Url $downloadUrl -OutputPath $updatePackage >> >> # 解压更新包 >> $extractPath = Join-Path $env:TEMP "curltools-update" >> Expand-Archive -Path $updatePackage -DestinationPath $extractPath -Force >> >> # 替换模块文件 >> $moduleDir = (Get-Module CurlTools).ModuleBase >> Copy-Item -Path "$extractPath\*" -Destination $moduleDir -Recurse -Force >> >> # 重新加载模块 >> Remove-Module CurlTools -ErrorAction SilentlyContinue >> Import-Module CurlTools -Force >> >> Write-Host "模块已成功更新到版本 $latestVersion" -ForegroundColor Green >> } >> else { >> Write-Host "当前已是最新版本 ($currentVersion)" -ForegroundColor Cyan >> } >> } >> catch { >> Write-Error "更新失败: $_" >> } >> } >> PS C:\Users\Administrator> # 重新加载模块 >> Remove-Module CurlTools -ErrorAction SilentlyContinue >> Import-Module CurlTools -Force >> >> # 测试1:获取Curl路径 >> $path = Get-CurlPath >> Write-Host "测试1: 当前Curl路径: $path" -ForegroundColor Cyan >> >> # 测试2:设置新的Curl路径 >> $newPath = Join-Path $env:TEMP "CurlTestPath" >> Set-CurlPath -Path $newPath >> >> # 测试3:再次获取Curl路径 >> $newPathActual = Get-CurlPath >> Write-Host "测试3: 设置后的Curl路径: $newPathActual" -ForegroundColor Cyan >> >> # 测试4:获取Curl版本 >> $version = Get-CurlVersion >> Write-Host "测试4: Curl版本: $version" -ForegroundColor Cyan >> >> # 测试5:安全下载 >> $testUrl = "https://raw.githubusercontent.com/PowerShell/PowerShell/master/README.md" >> $outputFile = Join-Path $env:TEMP "PowerShell_README.md" >> Invoke-SecureDownload -Url $testUrl -OutputPath $outputFile >> if (Test-Path $outputFile) { >> Write-Host "测试5: 文件下载成功: $outputFile" -ForegroundColor Green >> } else { >> Write-Host "测试5: 文件下载失败" -ForegroundColor Red >> } >> >> # 测试6:带哈希验证的下载 >> $expectedHash = (Get-FileHash -Path $outputFile -Algorithm SHA256).Hash >> $outputFile2 = Join-Path $env:TEMP "PowerShell_README_Verified.md" >> Invoke-SecureDownload -Url $testUrl -OutputPath $outputFile2 -ExpectedHash $expectedHash -HashAlgorithm SHA256 >> if (Test-Path $outputFile2) { >> Write-Host "测试6: 带哈希验证的文件下载成功" -ForegroundColor Green >> } else { >> Write-Host "测试6: 带哈希验证的文件下载失败" -ForegroundColor Red >> } >> 测试1: 当前Curl路径: C:\Custom\Curl\Path 警告: 路径不存在,将在设置后创建: E:\ai_temp\CurlTestPath 已设置curl路径: E:\ai_temp\CurlTestPath 警告: 路径 E:\ai_temp\CurlTestPath 下找不到 curl.exe,尝试自动安装... 无法自动安装curl: 无法将“Join-PPath”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径 ,请确保路径正确,然后再试一次。 所在位置 行:147 字符: 9 + throw "无法自动安装curl: $_" + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (无法自动安装curl: 无法将...请确保路径正确,然后再试一次。:String) [], RuntimeException + FullyQualifiedErrorId : 无法自动安装curl: 无法将“Join-PPath”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。 请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 PS C:\Users\Administrator>
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值