powershell 技巧 版本Get-Host

本文介绍了PowerShell中的一些实用技巧,包括类型转换、快捷键、比较操作符如`-ne`, `-notin`的使用,以及查看PowerShell版本的方法。还展示了如何在字符串操作和显示文件列表中应用这些技巧。" 105102527,7432937,使用CSS创建充电特效,"['CSS', 'HTML', '前端开发']

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

类型转换:
[char]([convert]::ToInt32([int]$char,8))

快捷键
显示调用堆栈    CTRL+SHIFT+D
列出断点    CTRL+SHIFT+L

 

不等于!,not:

  if (!($name.Contains('*'))) {
    $name = "*$name*"
}

 

-notin:

foreach ($program in $CurrentProgramList) {
    if ($program.name -like $name -and $program -notin $programNameList) {
        $programPathList += $LnkTargetPath
        $programNameList += $program.name
    }


    @($cc | Out-GridView -Title 'output')
    5

   if ($name -isnot [array]) {
        exec $name
    }
    else {
        foreach ($i in $name) {
            exec $i
        }
    }


$outputData | ConvertTo-Csv -NoTypeInformation | Out-File "d:\thanks.csv"

字符串:
$txt = New-Object System.Text.StringBuilder 80000
ls D:\thanks-image | foreach {
$img = "<img src='{0}'/>" -f $_.Name
$txt.Append($img) | Out-Null
}
$txt.ToString()

less than
greater than


-eq :等于
-ne :不等于
-gt :大于
-ge :大于等于
-lt :小于
-le :小于等于
-contains :包含
-notcontains :不包含

 

poweshell 版本

$PSVersionTable.PSVersion
Get-Host
    #>

PS C:\Users\Administrator> # 导出公共函数 >> Export-ModuleMember -Function Get-CurlPath, Get-CurlVersion, Invoke-SecureDownload, Uninstall-CurlTools >> >> # 私有函数 >> function Get-Platform { >> if ($IsLinux) { "Linux" } >> elseif ($IsMacOS) { "macOS" } >> else { "Windows" } >> } >> >> # 公共函数 >> function Get-CurlPath { >> if ($IsWindows) { >> $curlPath = Get-Command curl -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source >> if (-not $curlPath) { $curlPath = "C:\Windows\System32\curl.exe" } >> return $curlPath >> } else { >> return (Get-Command curl).Source >> } >> } >> >> function Get-CurlVersion { >> $curlPath = Get-CurlPath >> $versionOutput = & $curlPath --version | Select-Object -First 1 >> if ($versionOutput -match 'curl (\d+\.\d+\.\d+)') { >> return @{ >> Version = $matches[1] >> FullOutput = $versionOutput >> } >> } else { >> throw "无法解析curl版本" >> } >> } >> >> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [ValidatePattern('^https?://')] >> [string]$Url, >> [Parameter(Mandatory=$true)] >> [string]$OutputPath >> ) >> >> $curlPath = Get-CurlPath >> $arguments = @("-L", "-o", "`"$OutputPath`"", "`"$Url`"") >> >> try { >> $process = Start-Process -FilePath $curlPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru >> if ($process.ExitCode -ne 0) { >> throw "下载失败 (退出代码: $($process.ExitCode))" >> } >> >> if (-not (Test-Path $OutputPath)) { >> throw "文件未创建" >> } >> >> return Get-Item $OutputPath >> } catch { >> throw "安全下载失败: $_" >> } >> } >> >> function Uninstall-CurlTools { >> <# >> .SYNOPSIS >> 安全卸载CurlTools模块 >> #> >> $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 >> if (-not $module) { >> Write-Warning "未找到CurlTools模块" >> return >> } >> >> $uninstallPath = Join-Path $module.ModuleBase "Uninstall.ps1" >> if (Test-Path $uninstallPath) { >> Write-Host "运行卸载脚本..." -ForegroundColor Cyan >> & $uninstallPath >> } else { >> Write-Error "找不到卸载脚本" >> } >> } >> Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:2 字符: 1 + Export-ModuleMember -Function Get-CurlPath, Get-CurlVersion, Invoke-S ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Export-ModuleMember], InvalidOperationException + FullyQualifiedErrorId : Modules_CanOnlyExecuteExportModuleMemberInsideAModule,Microsoft.PowerShell.Commands.Expo rtModuleMemberCommand PS C:\Users\Administrator> param( >> [switch]$Force >> ) >> >> # 1. 确定模块目录 >> $moduleDir = if ($PSVersionTable.PSEdition -eq "Core") { >> Join-Path $HOME ".local/share/powershell/Modules/CurlTools" >> } else { >> Join-Path $env:ProgramFiles "WindowsPowerShell/Modules/CurlTools" >> } >> >> # 2. 确保目录结构存在 >> $requiredDirs = @( >> $moduleDir, >> (Join-Path $moduleDir "Public"), >> (Join-Path $moduleDir "Private") >> ) >> >> foreach ($dir in $requiredDirs) { >> if (-not (Test-Path $dir)) { >> try { >> New-Item -ItemType Directory -Path $dir -Force | Out-Null >> Write-Host "✅ 创建目录: $dir" -ForegroundColor Green >> } catch { >> Write-Error "❌ 创建目录失败: $dir - $_" >> Read-Host "按回车键退出" >> exit 1 >> } >> } elseif ($Force) { >> Write-Warning "目录已存在: $dir (使用 -Force 覆盖)" >> } >> } >> >> # 3. 定义模块文件内容 >> $moduleContent = @' >> # 导出公共函数 >> Export-ModuleMember -Function Get-CurlPath, Get-CurlVersion, Invoke-SecureDownload, Uninstall-CurlTools >> >> # 私有函数 >> function Get-Platform { >> if ($IsLinux) { "Linux" } >> elseif ($IsMacOS) { "macOS" } >> else { "Windows" } >> } >> >> # 公共函数 >> function Get-CurlPath { >> if ($IsWindows) { >> $curlPath = Get-Command curl -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source >> if (-not $curlPath) { $curlPath = "C:\Windows\System32\curl.exe" } >> return $curlPath >> } else { >> return (Get-Command curl).Source >> } >> } >> >> function Get-CurlVersion { >> $curlPath = Get-CurlPath >> $versionOutput = & $curlPath --version | Select-Object -First 1 >> if ($versionOutput -match 'curl (\d+\.\d+\.\d+)') { >> return @{ >> Version = $matches[1] >> FullOutput = $versionOutput >> } >> } else { >> throw "无法解析curl版本" >> } >> } >> >> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [ValidatePattern('^https?://')] >> [string]$Url, >> [Parameter(Mandatory=$true)] >> [string]$OutputPath >> ) >> >> $curlPath = Get-CurlPath >> $arguments = @("-L", "-o", "`"$OutputPath`"", "`"$Url`"") >> >> try { >> $process = Start-Process -FilePath $curlPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru >> if ($process.ExitCode -ne 0) { >> throw "下载失败 (退出代码: $($process.ExitCode))" >> } >> >> if (-not (Test-Path $OutputPath)) { >> throw "文件未创建" >> } >> >> return Get-Item $OutputPath >> } catch { >> throw "安全下载失败: $_" >> } >> } >> >> function Uninstall-CurlTools { >> <# >> .SYNOPSIS >> 安全卸载CurlTools模块 >> #> >> $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 >> if (-not $module) { >> Write-Warning "未找到CurlTools模块" >> return >> } >> >> $uninstallPath = Join-Path $module.ModuleBase "Uninstall.ps1" >> if (Test-Path $uninstallPath) { >> Write-Host "运行卸载脚本..." -ForegroundColor Cyan >> & $uninstallPath >> } else { >> Write-Error "找不到卸载脚本" >> } >> } >> '@ >> >> # 4. 卸载脚本内容 (保持不变) >> $uninstallScript = @' >> param([switch]$Force) >> >> $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 >> if (-not $module) { >> Write-Warning "未找到CurlTools模块" >> return >> } >> >> $moduleDir = $module.ModuleBase >> Write-Host "`n正在卸载CurlTools模块..." -ForegroundColor Yellow >> Write-Host "模块位置: $moduleDir" >> >> # 用户确认 >> if (-not $Force) { >> $confirmation = Read-Host "确定要卸载CurlTools模块吗? (y/n)" >> if ($confirmation -ne 'y') { >> Write-Host "卸载已取消" -ForegroundColor Yellow >> return >> } >> } >> >> # 确保卸载前移除模块 >> try { >> Remove-Module CurlTools -Force -ErrorAction Stop >> Write-Host "✅ 模块已从会话中移除" -ForegroundColor Green >> } catch { >> Write-Warning "无法从会话中移除模块: $_" >> } >> >> # 删除模块目录 >> try { >> Write-Host "正在删除模块文件..." >> Remove-Item -Path $moduleDir -Recurse -Force -ErrorAction Stop >> Write-Host "✅ 模块文件已删除" -ForegroundColor Green >> } catch { >> Write-Error "❌ 删除模块文件失败: $_" >> Write-Host "请手动删除目录: $moduleDir" -ForegroundColor Red >> return >> } >> >> # 清理配置文件 >> $configDir = switch (Get-Platform) { >> "Linux" { Join-Path $HOME ".config" "curltools" } >> "macOS" { Join-Path $HOME "Library" "Application Support" "CurlTools" } >> default { Join-Path $env:APPDATA "CurlTools" } >> } >> >> if (Test-Path $configDir) { >> try { >> Remove-Item -Path $configDir -Recurse -Force >> Write-Host "✅ 配置文件已清理" -ForegroundColor Green >> } catch { >> Write-Warning "清理配置文件失败: $_" >> } >> } >> >> Write-Host "`n✅ 模块已成功卸载" -ForegroundColor Green >> Read-Host "按回车键退出" >> '@ >> >> # 5. 保存所有文件 >> $filesToCreate = @{ >> "CurlTools.psm1" = $moduleContent >> "Uninstall.ps1" = $uninstallScript >> } >> >> foreach ($fileName in $filesToCreate.Keys) { >> $filePath = Join-Path $moduleDir $fileName >> try { >> Set-Content -Path $filePath -Value $filesToCreate[$fileName] -Force >> Write-Host "✅ 创建文件: $filePath" -ForegroundColor Green >> >> # 调试:显示文件前5行 >> $contentPreview = Get-Content -Path $filePath -TotalCount 5 >> Write-Host "文件预览:" >> $contentPreview | ForEach-Object { Write-Host " $_" } >> } catch { >> Write-Error "❌ 创建文件失败: $filePath - $_" >> Read-Host "按回车键退出" >> exit 1 >> } >> } >> >> # 6. 测试模块安装(增强版) >> try { >> Write-Host "`n测试模块安装..." -ForegroundColor Cyan >> >> # 1. 导入模块 >> Import-Module $moduleDir -Force -ErrorAction Stop >> Write-Host "✅ 模块导入成功" -ForegroundColor Green >> >> # 2. 验证模块已加载 >> $moduleInfo = Get-Module CurlTools >> if (-not $moduleInfo) { >> throw "模块加载后未在会话中找到" >> } >> Write-Host "✅ 模块信息: $($moduleInfo.Version)" -ForegroundColor Green >> >> # 3. 验证导出函数 >> $commands = Get-Command -Module CurlTools >> if (-not $commands) { >> throw "模块未导出任何命令" >> } >> Write-Host "✅ 导出命令: $($commands.Name -join ', ')" -ForegroundColor Green >> >> # 4. 验证基本功能 >> $curlPath = Get-CurlPath >> if (-not $curlPath) { >> throw "Get-CurlPath 返回空值" >> } >> Write-Host "✅ curl路径: $curlPath" -ForegroundColor Green >> >> # 5. 测试下载功能(可选) >> try { >> $testFile = Join-Path $env:TEMP "test_download_$(Get-Date -Format 'yyyyMMddHHmmss').txt" >> $result = Invoke-SecureDownload -Url "https://example.com" -OutputPath $testFile >> if (Test-Path $testFile) { >> Write-Host "✅ 下载测试成功: $testFile" -ForegroundColor Green >> Remove-Item $testFile -Force >> } >> } catch { >> Write-Warning "⚠️ 下载测试失败: $_ (不影响整体安装)" >> } >> >> # 显示使用说明 >> Write-Host "`n使用说明:" -ForegroundColor Magenta >> Write-Host "1. 导入模块: Import-Module CurlTools" -ForegroundColor Yellow >> Write-Host "2. 查看帮助: Get-Help Invoke-SecureDownload" -ForegroundColor Yellow >> Write-Host "3. 卸载模块: Uninstall-CurlTools" -ForegroundColor Yellow >> >> # 添加用户交互保持窗口打开 >> Read-Host "`n按回车键退出" >> exit 0 >> } catch { >> Write-Error "❌ 模块测试失败: $_" >> >> # 显示详细错误信息 >> Write-Host "`n调试信息:" -ForegroundColor Red >> Write-Host "模块目录: $moduleDir" -ForegroundColor Red >> Write-Host "模块内容:" >> if (Test-Path "$moduleDir\CurlTools.psm1") { >> Get-Content "$moduleDir\CurlTools.psm1" -TotalCount 20 | ForEach-Object { Write-Host " $_" } >> } >> >> Read-Host "`n按回车键退出查看错误详情" >> exit 1 >> } >> ✅ 创建文件: C:\Program Files\WindowsPowerShell\Modules\CurlTools\Uninstall.ps1 文件预览: param([switch]$Force) $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 if (-not $module) { Write-Warning "未找到CurlTools模块" ✅ 创建文件: C:\Program Files\WindowsPowerShell\Modules\CurlTools\CurlTools.psm1 文件预览: # 导出公共函数 Export-ModuleMember -Function Get-CurlPath, Get-CurlVersion, Invoke-SecureDownload, Uninstall-CurlTools # 私有函数 function Get-Platform { 测试模块安装... ✅ 模块导入成功 ✅ 模块信息: 0.0 param( [switch]$Force ) # 1. 确定模块目录 $moduleDir = if ($PSVersionTable.PSEdition -eq "Core") { Join-Path $HOME ".local/share/powershell/Modules/CurlTools" } else { Join-Path $env:ProgramFiles "WindowsPowerShell/Modules/CurlTools" } # 2. 确保目录结构存在 $requiredDirs = @( $moduleDir, (Join-Path $moduleDir "Public"), (Join-Path $moduleDir "Private") ) foreach ($dir in $requiredDirs) { if (-not (Test-Path $dir)) { try { New-Item -ItemType Directory -Path $dir -Force | Out-Null Write-Host "✅ 创建目录: $dir" -ForegroundColor Green } catch { Write-Error "❌ 创建目录失败: $dir - $_" Read-Host "按回车键退出" exit 1 } } elseif ($Force) { Write-Warning "目录已存在: $dir (使用 -Force 覆盖)" } } # 3. 定义模块文件内容 $moduleContent = @' # 导出公共函数 Export-ModuleMember -Function Get-CurlPath, Get-CurlVersion, Invoke-SecureDownload, Uninstall-CurlTools # 私有函数 function Get-Platform { if ($IsLinux) { "Linux" } elseif ($IsMacOS) { "macOS" } else { "Windows" } } # 公共函数 function Get-CurlPath { if ($IsWindows) { $curlPath = Get-Command curl -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source if (-not $curlPath) { $curlPath = "C:\Windows\System32\curl.exe" } return $curlPath } else { return (Get-Command curl).Source } } function Get-CurlVersion { $curlPath = Get-CurlPath $versionOutput = & $curlPath --version | Select-Object -First 1 if ($versionOutput -match 'curl (\d+\.\d+\.\d+)') { return @{ Version = $matches[1] FullOutput = $versionOutput } } else { throw "无法解析curl版本" } } function Invoke-SecureDownload { param( [Parameter(Mandatory=$true)] [ValidatePattern('^https?://')] [string]$Url, [Parameter(Mandatory=$true)] [string]$OutputPath ) $curlPath = Get-CurlPath $arguments = @("-L", "-o", "`"$OutputPath`"", "`"$Url`"") try { $process = Start-Process -FilePath $curlPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru if ($process.ExitCode -ne 0) { throw "下载失败 (退出代码: $($process.ExitCode))" } if (-not (Test-Path $OutputPath)) { throw "文件未创建" } return Get-Item $OutputPath } catch { throw "安全下载失败: $_" } } function Uninstall-CurlTools { <# .SYNOPSIS 安全卸载CurlTools模块 #> $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 if (-not $module) { Write-Warning "未找到CurlTools模块" return } $uninstallPath = Join-Path $module.ModuleBase "Uninstall.ps1" if (Test-Path $uninstallPath) { Write-Host "运行卸载脚本..." -ForegroundColor Cyan & $uninstallPath } else { Write-Error "找不到卸载脚本" } } '@ # 4. 卸载脚本内容 (保持不变) $uninstallScript = @' param([switch]$Force) $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 if (-not $module) { Write-Warning "未找到CurlTools模块" return } $moduleDir = $module.ModuleBase Write-Host "`n正在卸载CurlTools模块..." -ForegroundColor Yellow Write-Host "模块位置: $moduleDir" # 用户确认 if (-not $Force) { $confirmation = Read-Host "确定要卸载CurlTools模块吗? (y/n)" if ($confirmation -ne 'y') { Write-Host "卸载已取消" -ForegroundColor Yellow return } } # 确保卸载前移除模块 try { Remove-Module CurlTools -Force -ErrorAction Stop Write-Host "✅ 模块已从会话中移除" -ForegroundColor Green } catch { Write-Warning "无法从会话中移除模块: $_" } # 删除模块目录 try { Write-Host "正在删除模块文件..." Remove-Item -Path $moduleDir -Recurse -Force -ErrorAction Stop Write-Host "✅ 模块文件已删除" -ForegroundColor Green } catch { Write-Error "❌ 删除模块文件失败: $_" Write-Host "请手动删除目录: $moduleDir" -ForegroundColor Red return } # 清理配置文件 $configDir = switch (Get-Platform) { "Linux" { Join-Path $HOME ".config" "curltools" } "macOS" { Join-Path $HOME "Library" "Application Support" "CurlTools" } default { Join-Path $env:APPDATA "CurlTools" } } if (Test-Path $configDir) { try { Remove-Item -Path $configDir -Recurse -Force Write-Host "✅ 配置文件已清理" -ForegroundColor Green } catch { Write-Warning "清理配置文件失败: $_" } } Write-Host "`n✅ 模块已成功卸载" -ForegroundColor Green Read-Host "按回车键退出" '@ # 5. 保存所有文件 $filesToCreate = @{ "CurlTools.psm1" = $moduleContent "Uninstall.ps1" = $uninstallScript } foreach ($fileName in $filesToCreate.Keys) { $filePath = Join-Path $moduleDir $fileName try { Set-Content -Path $filePath -Value $filesToCreate[$fileName] -Force Write-Host "✅ 创建文件: $filePath" -ForegroundColor Green # 调试:显示文件前5行 $contentPreview = Get-Content -Path $filePath -TotalCount 5 Write-Host "文件预览:" $contentPreview | ForEach-Object { Write-Host " $_" } } catch { Write-Error "❌ 创建文件失败: $filePath - $_" Read-Host "按回车键退出" exit 1 } } # 6. 测试模块安装(增强版) try { Write-Host "`n测试模块安装..." -ForegroundColor Cyan # 1. 导入模块 Import-Module $moduleDir -Force -ErrorAction Stop Write-Host "✅ 模块导入成功" -ForegroundColor Green # 2. 验证模块已加载 $moduleInfo = Get-Module CurlTools if (-not $moduleInfo) { throw "模块加载后未在会话中找到" } Write-Host "✅ 模块信息: $($moduleInfo.Version)" -ForegroundColor Green # 3. 验证导出函数 $commands = Get-Command -Module CurlTools if (-not $commands) { throw "模块未导出任何命令" } Write-Host "✅ 导出命令: $($commands.Name -join ', ')" -ForegroundColor Green # 4. 验证基本功能 $curlPath = Get-CurlPath if (-not $curlPath) { throw "Get-CurlPath 返回空值" } Write-Host "✅ curl路径: $curlPath" -ForegroundColor Green # 5. 测试下载功能(可选) try { $testFile = Join-Path $env:TEMP "test_download_$(Get-Date -Format 'yyyyMMddHHmmss').txt" $result = Invoke-SecureDownload -Url "https://example.com" -OutputPath $testFile if (Test-Path $testFile) { Write-Host "✅ 下载测试成功: $testFile" -ForegroundColor Green Remove-Item $testFile -Force } } catch { Write-Warning "⚠️ 下载测试失败: $_ (不影响整体安装)" } # 显示使用说明 Write-Host "`n使用说明:" -ForegroundColor Magenta Write-Host "1. 导入模块: Import-Module CurlTools" -ForegroundColor Yellow Write-Host "2. 查看帮助: Get-Help Invoke-SecureDownload" -ForegroundColor Yellow Write-Host "3. 卸载模块: Uninstall-CurlTools" -ForegroundColor Yellow # 添加用户交互保持窗口打开 Read-Host "`n按回车键退出" exit 0 } catch { Write-Error "❌ 模块测试失败: $_" # 显示详细错误信息 Write-Host "`n调试信息:" -ForegroundColor Red Write-Host "模块目录: $moduleDir" -ForegroundColor Red Write-Host "模块内容:" if (Test-Path "$moduleDir\CurlTools.psm1") { Get-Content "$moduleDir\CurlTools.psm1" -TotalCount 20 | ForEach-Object { Write-Host " $_" } } Read-Host "`n按回车键退出查看错误详情" exit 1 } : ❌ 模块测试失败: 模块未导出任何命令 + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException 调试信息: 模块目录: C:\Program Files\WindowsPowerShell\Modules\CurlTools 模块内容: # 导出公共函数 Export-ModuleMember -Function Get-CurlPath, Get-CurlVersion, Invoke-SecureDownload, Uninstall-CurlTools # 私有函数 function Get-Platform { if ($IsLinux) { "Linux" } elseif ($IsMacOS) { "macOS" } else { "Windows" } } # 公共函数 function Get-CurlPath { if ($IsWindows) { $curlPath = Get-Command curl -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source if (-not $curlPath) { $curlPath = "C:\Windows\System32\curl.exe" } return $curlPath } else { return (Get-Command curl).Source } } 按回车键退出查看错误详情:
最新发布
08-13
PS C:\Users\Administrator> param( >> [switch]$Force >> ) >> >> # 1. 确定模块目录 >> $moduleDir = if ($PSVersionTable.PSEdition -eq "Core") { >> Join-Path $HOME ".local/share/powershell/Modules/CurlTools" >> } else { >> Join-Path $env:ProgramFiles "WindowsPowerShell/Modules/CurlTools" >> } >> >> # 2. 确保目录结构存在 >> $requiredDirs = @( >> $moduleDir, >> (Join-Path $moduleDir "Public"), >> (Join-Path $moduleDir "Private") >> ) >> >> foreach ($dir in $requiredDirs) { >> if (-not (Test-Path $dir)) { >> try { >> New-Item -ItemType Directory -Path $dir -Force | Out-Null >> Write-Host "✅ 创建目录: $dir" -ForegroundColor Green >> } catch { >> Write-Error "❌ 创建目录失败: $dir - $_" >> Read-Host "按回车键退出" >> exit 1 >> } >> } elseif ($Force) { >> Write-Warning "目录已存在: $dir (使用 -Force 覆盖)" >> } >> } >> >> # 3. 定义模块文件内容 >> # 模块主文件 (CurlTools.psm1) >> $moduleContent = @' >> # 导出公共函数 >> Export-ModuleMember -Function Get-CurlPath, Get-CurlVersion, Invoke-SecureDownload, Uninstall-CurlTools >> >> # 私有函数 >> function Get-Platform { >> if ($IsLinux) { "Linux" } >> elseif ($IsMacOS) { "macOS" } >> else { "Windows" } >> } >> >> # 公共函数 >> function Get-CurlPath { >> if ($IsWindows) { >> $curlPath = Get-Command curl -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source >> if (-not $curlPath) { $curlPath = "C:\Windows\System32\curl.exe" } >> return $curlPath >> } else { >> return (Get-Command curl).Source >> } >> } >> >> function Get-CurlVersion { >> $curlPath = Get-CurlPath >> $versionOutput = & $curlPath --version | Select-Object -First 1 >> if ($versionOutput -match 'curl (\d+\.\d+\.\d+)') { >> return @{ >> Version = $matches[1] >> FullOutput = $versionOutput >> } >> } else { >> throw "无法解析curl版本" >> } >> } >> >> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [ValidatePattern('^https?://')] >> [string]$Url, >> [Parameter(Mandatory=$true)] >> [string]$OutputPath >> ) >> >> $curlPath = Get-CurlPath >> $arguments = @("-L", "-o", "`"$OutputPath`"", "`"$Url`"") >> >> try { >> $process = Start-Process -FilePath $curlPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru >> if ($process.ExitCode -ne 0) { >> throw "下载失败 (退出代码: $($process.ExitCode))" >> } >> >> if (-not (Test-Path $OutputPath)) { >> throw "文件未创建" >> } >> >> return Get-Item $OutputPath >> } catch { >> throw "安全下载失败: $_" >> } >> } >> >> function Uninstall-CurlTools { >> <# >> .SYNOPSIS >> 安全卸载CurlTools模块 >> #> >> $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 >> if (-not $module) { >> Write-Warning "未找到CurlTools模块" >> return >> } >> >> $uninstallPath = Join-Path $module.ModuleBase "Uninstall.ps1" >> if (Test-Path $uninstallPath) { >> Write-Host "运行卸载脚本..." -ForegroundColor Cyan >> & $uninstallPath >> } else { >> Write-Error "找不到卸载脚本" >> } >> } >> '@ >> >> # 卸载脚本 (Uninstall.ps1) >> $uninstallScript = @' >> param([switch]$Force) >> >> $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 >> if (-not $module) { >> Write-Warning "未找到CurlTools模块" >> return >> } >> >> $moduleDir = $module.ModuleBase >> Write-Host "`n正在卸载CurlTools模块..." -ForegroundColor Yellow >> Write-Host "模块位置: $moduleDir" >> >> # 用户确认 >> if (-not $Force) { >> $confirmation = Read-Host "确定要卸载CurlTools模块吗? (y/n)" >> if ($confirmation -ne 'y') { >> Write-Host "卸载已取消" -ForegroundColor Yellow >> return >> } >> } >> >> # 确保卸载前移除模块 >> try { >> Remove-Module CurlTools -Force -ErrorAction Stop >> Write-Host "✅ 模块已从会话中移除" -ForegroundColor Green >> } catch { >> Write-Warning "无法从会话中移除模块: $_" >> } >> >> # 删除模块目录 >> try { >> Write-Host "正在删除模块文件..." >> Remove-Item -Path $moduleDir -Recurse -Force -ErrorAction Stop >> Write-Host "✅ 模块文件已删除" -ForegroundColor Green >> } catch { >> Write-Error "❌ 删除模块文件失败: $_" >> Write-Host "请手动删除目录: $moduleDir" -ForegroundColor Red >> return >> } >> >> # 清理配置文件 >> $configDir = switch (Get-Platform) { >> "Linux" { Join-Path $HOME ".config" "curltools" } >> "macOS" { Join-Path $HOME "Library" "Application Support" "CurlTools" } >> default { Join-Path $env:APPDATA "CurlTools" } >> } >> >> if (Test-Path $configDir) { >> try { >> Remove-Item -Path $configDir -Recurse -Force >> Write-Host "✅ 配置文件已清理" -ForegroundColor Green >> } catch { >> Write-Warning "清理配置文件失败: $_" >> } >> } >> >> Write-Host "`n✅ 模块已成功卸载" -ForegroundColor Green >> Read-Host "按回车键退出" >> '@ >> >> # 4. 保存所有文件 >> $filesToCreate = @{ >> "CurlTools.psm1" = $moduleContent >> "Uninstall.ps1" = $uninstallScript >> } >> >> foreach ($fileName in $filesToCreate.Keys) { >> $filePath = Join-Path $moduleDir $fileName >> try { >> Set-Content -Path $filePath -Value $filesToCreate[$fileName] -Force >> Write-Host "✅ 创建文件: $filePath" -ForegroundColor Green >> } catch { >> Write-Error "❌ 创建文件失败: $filePath - $_" >> Read-Host "按回车键退出" >> exit 1 >> } >> } >> >> # 5. 测试模块安装 >> try { >> Write-Host "`n测试模块安装..." -ForegroundColor Cyan >> Import-Module $moduleDir -Force -ErrorAction Stop >> >> # 验证基本功能 >> $curlPath = Get-CurlPath >> if (-not $curlPath) { >> Write-Error "❌ Get-CurlPath 返回空值" >> throw "Get-CurlPath 返回空值" >> } >> >> Write-Host "✅ 模块安装成功! curl路径: $curlPath" -ForegroundColor Green >> >> # 显示使用说明 >> Write-Host "`n使用说明:" -ForegroundColor Magenta >> Write-Host "1. 导入模块: Import-Module CurlTools" -ForegroundColor Yellow >> Write-Host "2. 查看帮助: Get-Help Invoke-SecureDownload" -ForegroundColor Yellow >> Write-Host "3. 卸载模块: Uninstall-CurlTools" -ForegroundColor Yellow >> >> # 添加用户交互保持窗口打开 >> Read-Host "`n按回车键退出" >> exit 0 >> } catch { >> Write-Error "❌ 模块测试失败: $_" >> Read-Host "`n按回车键退出查看错误详情" >> exit 1 >> } >> ✅ 创建文件: C:\Program Files\WindowsPowerShell\Modules\CurlTools\Uninstall.ps1 ✅ 创建文件: C:\Program Files\WindowsPowerShell\Modules\CurlTools\CurlTools.psm1 测试模块安装... param( [switch]$Force ) # 1. 确定模块目录 $moduleDir = if ($PSVersionTable.PSEdition -eq "Core") { Join-Path $HOME ".local/share/powershell/Modules/CurlTools" } else { Join-Path $env:ProgramFiles "WindowsPowerShell/Modules/CurlTools" } # 2. 确保目录结构存在 $requiredDirs = @( $moduleDir, (Join-Path $moduleDir "Public"), (Join-Path $moduleDir "Private") ) foreach ($dir in $requiredDirs) { if (-not (Test-Path $dir)) { try { New-Item -ItemType Directory -Path $dir -Force | Out-Null Write-Host "✅ 创建目录: $dir" -ForegroundColor Green } catch { Write-Error "❌ 创建目录失败: $dir - $_" Read-Host "按回车键退出" exit 1 } } elseif ($Force) { Write-Warning "目录已存在: $dir (使用 -Force 覆盖)" } } # 3. 定义模块文件内容 # 模块主文件 (CurlTools.psm1) $moduleContent = @' # 导出公共函数 Export-ModuleMember -Function Get-CurlPath, Get-CurlVersion, Invoke-SecureDownload, Uninstall-CurlTools # 私有函数 function Get-Platform { if ($IsLinux) { "Linux" } elseif ($IsMacOS) { "macOS" } else { "Windows" } } # 公共函数 function Get-CurlPath { if ($IsWindows) { $curlPath = Get-Command curl -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source if (-not $curlPath) { $curlPath = "C:\Windows\System32\curl.exe" } return $curlPath } else { return (Get-Command curl).Source } } function Get-CurlVersion { $curlPath = Get-CurlPath $versionOutput = & $curlPath --version | Select-Object -First 1 if ($versionOutput -match 'curl (\d+\.\d+\.\d+)') { return @{ Version = $matches[1] FullOutput = $versionOutput } } else { throw "无法解析curl版本" } } function Invoke-SecureDownload { param( [Parameter(Mandatory=$true)] [ValidatePattern('^https?://')] [string]$Url, [Parameter(Mandatory=$true)] [string]$OutputPath ) $curlPath = Get-CurlPath $arguments = @("-L", "-o", "`"$OutputPath`"", "`"$Url`"") try { $process = Start-Process -FilePath $curlPath -ArgumentList $arguments -Wait -NoNewWindow -PassThru if ($process.ExitCode -ne 0) { throw "下载失败 (退出代码: $($process.ExitCode))" } if (-not (Test-Path $OutputPath)) { throw "文件未创建" } return Get-Item $OutputPath } catch { throw "安全下载失败: $_" } } function Uninstall-CurlTools { <# .SYNOPSIS 安全卸载CurlTools模块 #> $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 if (-not $module) { Write-Warning "未找到CurlTools模块" return } $uninstallPath = Join-Path $module.ModuleBase "Uninstall.ps1" if (Test-Path $uninstallPath) { Write-Host "运行卸载脚本..." -ForegroundColor Cyan & $uninstallPath } else { Write-Error "找不到卸载脚本" } } '@ # 卸载脚本 (Uninstall.ps1) $uninstallScript = @' param([switch]$Force) $module = Get-Module CurlTools -ListAvailable | Select-Object -First 1 if (-not $module) { Write-Warning "未找到CurlTools模块" return } $moduleDir = $module.ModuleBase Write-Host "`n正在卸载CurlTools模块..." -ForegroundColor Yellow Write-Host "模块位置: $moduleDir" # 用户确认 if (-not $Force) { $confirmation = Read-Host "确定要卸载CurlTools模块吗? (y/n)" if ($confirmation -ne 'y') { Write-Host "卸载已取消" -ForegroundColor Yellow return } } # 确保卸载前移除模块 try { Remove-Module CurlTools -Force -ErrorAction Stop Write-Host "✅ 模块已从会话中移除" -ForegroundColor Green } catch { Write-Warning "无法从会话中移除模块: $_" } # 删除模块目录 try { Write-Host "正在删除模块文件..." Remove-Item -Path $moduleDir -Recurse -Force -ErrorAction Stop Write-Host "✅ 模块文件已删除" -ForegroundColor Green } catch { Write-Error "❌ 删除模块文件失败: $_" Write-Host "请手动删除目录: $moduleDir" -ForegroundColor Red return } # 清理配置文件 $configDir = switch (Get-Platform) { "Linux" { Join-Path $HOME ".config" "curltools" } "macOS" { Join-Path $HOME "Library" "Application Support" "CurlTools" } default { Join-Path $env:APPDATA "CurlTools" } } if (Test-Path $configDir) { try { Remove-Item -Path $configDir -Recurse -Force Write-Host "✅ 配置文件已清理" -ForegroundColor Green } catch { Write-Warning "清理配置文件失败: $_" } } Write-Host "`n✅ 模块已成功卸载" -ForegroundColor Green Read-Host "按回车键退出" '@ # 4. 保存所有文件 $filesToCreate = @{ "CurlTools.psm1" = $moduleContent "Uninstall.ps1" = $uninstallScript } foreach ($fileName in $filesToCreate.Keys) { $filePath = Join-Path $moduleDir $fileName try { Set-Content -Path $filePath -Value $filesToCreate[$fileName] -Force Write-Host "✅ 创建文件: $filePath" -ForegroundColor Green } catch { Write-Error "❌ 创建文件失败: $filePath - $_" Read-Host "按回车键退出" exit 1 } } # 5. 测试模块安装 try { Write-Host "`n测试模块安装..." -ForegroundColor Cyan Import-Module $moduleDir -Force -ErrorAction Stop # 验证基本功能 $curlPath = Get-CurlPath if (-not $curlPath) { Write-Error "❌ Get-CurlPath 返回空值" throw "Get-CurlPath 返回空值" } Write-Host "✅ 模块安装成功! curl路径: $curlPath" -ForegroundColor Green # 显示使用说明 Write-Host "`n使用说明:" -ForegroundColor Magenta Write-Host "1. 导入模块: Import-Module CurlTools" -ForegroundColor Yellow Write-Host "2. 查看帮助: Get-Help Invoke-SecureDownload" -ForegroundColor Yellow Write-Host "3. 卸载模块: Uninstall-CurlTools" -ForegroundColor Yellow # 添加用户交互保持窗口打开 Read-Host "`n按回车键退出" exit 0 } catch { Write-Error "❌ 模块测试失败: $_" Read-Host "`n按回车键退出查看错误详情" exit 1 } : ❌ 模块测试失败: 无法将“Get-CurlPath”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括 路径,请确保路径正确,然后再试一次。 + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException 按回车键退出查看错误详情:
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值