$Using variable with Invoke-Command cmdlet

本文介绍了在PowerShell3.0中利用远程变量$Using简化远程命令传递的方法,通过实例展示了如何更高效地进行变量匹配与传递。

以前在PowerShell中我们使用远程命令Invoke-Command传递本地变量的时候往往都要在语句块里使用如下,Param() 添加本地变量参数传递。

Invoke-Command -ScriptBlock{
Param($ComputerName)
Get-Process -ComputerName $ComputerName -Name 'Notepad'
}

 

但是在PowerShell 3.0中,我们就不需要这样了,它新增了一个新的远程变量就是$Using,它与Param不同的是,它会自动做变量匹配,而用Param方式则不会做自动匹配,它所做的是一个变量传递的过程。

 

它的使用语句如下:

$Using:<VariableName>  

 

让我们看看如何使用,你只需要像以往一样在使用参数时,在固定参数位置以$Using:ComputerName 替换即可。

Invoke-Command -ScriptBlock{
#Param($ComputerName)
Get-Process -ComputerName $Using:ComputerName -Name 'Notepad'
}


 

PS C:\Users\Administrator> # 使用E盘作为模块安装路径 PS C:\Users\Administrator> $customModulePath = "E:\PowerShellModules\PSHttpClient" PS C:\Users\Administrator> $moduleName = "PSHttpClient" PS C:\Users\Administrator> $moduleVersion = "1.2.1" PS C:\Users\Administrator> $moduleDir = Join-Path $customModulePath $moduleVersion PS C:\Users\Administrator> PS C:\Users\Administrator> # 确保E盘存在 PS C:\Users\Administrator> if (-not (Test-Path "E:\")) { >> Write-Host "错误:E盘不存在!" -ForegroundColor Red >> exit 1 >> } >> PS C:\Users\Administrator> # 清理旧模块(如果存在) PS C:\Users\Administrator> if (Test-Path $moduleDir) { >> Remove-Item $moduleDir -Recurse -Force >> } >> PS C:\Users\Administrator> # 创建模块目录 PS C:\Users\Administrator> New-Item -Path $moduleDir -ItemType Directory -Force | Out-Null PS C:\Users\Administrator> PS C:\Users\Administrator> # 生成有效的GUID PS C:\Users\Administrator> $validGuid = [guid]::NewGuid().ToString() PS C:\Users\Administrator> PS C:\Users\Administrator> # 创建模块文件(完整代码,无占位符) PS C:\Users\Administrator> $moduleContent = @' >> function Invoke-EnhancedCurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [hashtable]$Headers = @{}, >> [object]$Body, >> [int]$Timeout = 30, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression, >> [switch]$EnableHttp2 >> ) >> >> # 使用System.Net.Http.HttpClient实现 >> try { >> # 创建HttpClientHandler >> $handler = New-Object System.Net.Http.HttpClientHandler >> if ($SkipCertificateCheck) { >> $handler.ServerCertificateCustomValidationCallback = { $true } >> } >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> >> # 创建HttpClient >> $client = New-Object System.Net.Http.HttpClient($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> >> # 设置HTTP版本 >> if ($EnableHttp2) { >> $client.DefaultRequestVersion = [System.Net.HttpVersion]::Version20 >> } >> >> # 创建请求消息 >> $request = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::$Method, $Uri) >> >> # 添加请求头 >> foreach ($key in $Headers.Keys) { >> $request.Headers.Add($key, $Headers[$key]) >> } >> >> # 添加请求体(如果存在) >> if ($Body) { >> if ($Body -is [string]) { >> $request.Content = New-Object System.Net.Http.StringContent($Body, [System.Text.Encoding]::UTF8) >> } >> elseif ($Body -is [System.Collections.IDictionary]) { >> $formData = [System.Collections.Generic.List[System.Collections.Generic.KeyValuePair[String,String]]]::new() >> foreach ($key in $Body.Keys) { >> $formData.Add([System.Collections.Generic.KeyValuePair[String,String]]::new($key, $Body[$key])) >> } >> $request.Content = New-Object System.Net.Http.FormUrlEncodedContent($formData) >> } >> } >> >> # 发送请求 >> $response = $client.SendAsync($request).Result >> >> # 读取响应内容 >> $responseContent = $response.Content.ReadAsStringAsync().Result >> >> # 返回结果对象 >> return [PSCustomObject]@{ >> StatusCode = [int]$response.StatusCode >> StatusMessage = $response.ReasonPhrase >> Content = $responseContent >> Headers = $response.Headers >> Technology = "HttpClient (.NET)" >> Protocol = $response.Version.ToString() >> ElapsedMs = $stopwatch.ElapsedMilliseconds >> } >> } >> catch { >> return [PSCustomObject]@{ >> StatusCode = 500 >> StatusMessage = "Internal Error" >> Error = $_.Exception.Message >> } >> } >> } >> >> Export-ModuleMember -Function Invoke-EnhancedCurlRequest >> '@ >> PS C:\Users\Administrator> # 保存模块文件到E盘 PS C:\Users\Administrator> $moduleContent | Out-File "$moduleDir\PSHttpClient.psm1" -Encoding UTF8 -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 创建模块清单文件 PS C:\Users\Administrator> $manifestContent = @" >> @{ >> RootModule = 'PSHttpClient.psm1' >> ModuleVersion = '$moduleVersion' >> GUID = '$validGuid' >> Author = 'PowerShell User' >> CompanyName = 'N/A' >> Copyright = '(c) 2023. All rights reserved.' >> Description = 'Enhanced HTTP client for PowerShell' >> PowerShellVersion = '5.1' >> FunctionsToExport = @('Invoke-EnhancedCurlRequest') >> RequiredAssemblies = @('System.Net.Http', 'System.Web') >> } >> "@ >> PS C:\Users\Administrator> $manifestContent | Out-File "$moduleDir\PSHttpClient.psd1" -Encoding UTF8 -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 更新PSModulePath环境变量(仅当前会话) PS C:\Users\Administrator> if (-not $env:PSModulePath.Contains($customModulePath)) { >> $env:PSModulePath = "$customModulePath;$env:PSModulePath" >> } >> PS C:\Users\Administrator> # 安装完成 PS C:\Users\Administrator> Write-Host "`n=== 模块安装成功 ===" -ForegroundColor Green === 模块安装成功 === PS C:\Users\Administrator> Write-Host "模块路径: $moduleDir" -ForegroundColor Cyan 模块路径: E:\PowerShellModules\PSHttpClient\1.2.1 PS C:\Users\Administrator> Write-Host "版本: $moduleVersion" -ForegroundColor Cyan 版本: 1.2.1 PS C:\Users\Administrator> PS C:\Users\Administrator> # 导入模块 PS C:\Users\Administrator> Remove-Module $moduleName -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module $moduleName -Force -Verbose 详细信息: 正在从路径“C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\1.2.1\PSHttpClient.psd1”加载模块。 详细信息: 正在从路径“C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\1.2.1\System.Net.Http”加载“Assembly”。 详细信息: 正在从路径“C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\1.2.1\System.Net.Http”加载“Assembly”。 详细信息: 正在从路径“C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\1.2.1\PSHttpClient.psm1”加载模块。 < : 无法将“<”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\1.2.1\PSHttpClient.psm1:2 字符: 1 + <这里插入完整的模块代码> + ~ + CategoryInfo : ObjectNotFound: (<:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator> PS C:\Users\Administrator> # 验证安装 PS C:\Users\Administrator> if (Get-Command Invoke-EnhancedCurlRequest -ErrorAction SilentlyContinue) { >> Write-Host "`n=== 功能验证 ===" -ForegroundColor Green >> try { >> $result = Invoke-EnhancedCurlRequest -Uri "https://httpbin.org/get" >> Write-Host "状态码: $($result.StatusCode) $($result.StatusMessage)" >> Write-Host "技术: $($result.Technology)" >> Write-Host "协议: $($result.Protocol)" >> >> Write-Host "`n=== 模块已成功安装到E盘 ===" -ForegroundColor Green >> } >> catch { >> Write-Host "功能验证失败: $_" -ForegroundColor Red >> } >> } else { >> Write-Host "`n!!! 安装失败 !!!" -ForegroundColor Red >> Write-Host "错误: $($Error[0].Exception.Message)" -ForegroundColor Red >> } >> === 功能验证 === 状态码: 200 OK 技术: HttpClient (.NET) 协议: 1.1 === 模块已成功安装到E盘 === PS C:\Users\Administrator> PS C:\Users\Administrator> PS C:\Users\Administrator> # 定义模块函数(不保存到磁盘) PS C:\Users\Administrator> $moduleCode = { >> function Invoke-MemoryCurl { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri >> ) >> >> try { >> $response = Invoke-WebRequest -Uri $Uri -UseBasicParsing >> return [PSCustomObject]@{ >> StatusCode = $response.StatusCode >> Content = $response.Content >> } >> } >> catch { >> return [PSCustomObject]@{ >> StatusCode = 500 >> Error = $_.Exception.Message >> } >> } >> } >> } >> PS C:\Users\Administrator> # 创建内存模块 PS C:\Users\Administrator> $memoryModule = New-Module -Name "MemoryHttp" -ScriptBlock $moduleCode -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 使用模块功能 PS C:\Users\Administrator> $memoryModule::Invoke-MemoryCurl -Uri "https://example.com" 所在位置 行:1 字符: 22 + $memoryModule::Invoke-MemoryCurl -Uri "https://example.com" + ~~~~~~~~~~~ 表达式或语句中包含意外的标记“-MemoryCurl”。 所在位置 行:1 字符: 34 + $memoryModule::Invoke-MemoryCurl -Uri "https://example.com" + ~~~~ 表达式或语句中包含意外的标记“-Uri”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken PS C:\Users\Administrator> PS C:\Users\Administrator> # 验证模块 PS C:\Users\Administrator> Get-Command -Module MemoryHttp CommandType Name Version Source ----------- ---- ------- ------ Function Invoke-MemoryCurl 0.0 MemoryHttp PS C:\Users\Administrator> PS C:\Users\Administrator> # 在临时目录创建模块(系统自动清理) PS C:\Users\Administrator> $tempDir = Join-Path $env:TEMP "PSModules-$(Get-Random)" PS C:\Users\Administrator> New-Item -ItemType Directory -Path $tempDir | Out-Null PS C:\Users\Administrator> PS C:\Users\Administrator> # 创建模块文件 PS C:\Users\Administrator> @' >> function Invoke-TempCurl { >> param([string]$Uri) >> (Invoke-WebRequest -Uri $Uri -UseBasicParsing).Content >> } >> '@ | Out-File "$tempDir\TempModule.psm1" -Encoding UTF8 >> PS C:\Users\Administrator> # 临时导入模块 PS C:\Users\Administrator> Import-Module "$tempDir\TempModule.psm1" -Force PS C:\Users\Administrator> PS C:\Users\Administrator> # 使用功能 PS C:\Users\Administrator> Invoke-TempCurl -Uri "https://example.com" <!doctype html> <html> <head> <title>Example Domain</title> <meta charset="utf-8" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style type="text/css"> body { background-color: #f0f0f2; margin: 0; padding: 0; font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; } div { width: 600px; margin: 5em auto; padding: 2em; background-color: #fdfdff; border-radius: 0.5em; box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02); } a:link, a:visited { color: #38488f; text-decoration: none; } @media (max-width: 700px) { div { margin: 0 auto; width: auto; } } </style> </head> <body> <div> <h1>Example Domain</h1> <p>This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.</p> <p><a href="https://www.iana.org/domains/example">More information...</a></p> </div> </body> </html> PS C:\Users\Administrator> PS C:\Users\Administrator> # 完成后自动清理(可选) PS C:\Users\Administrator> Start-Job -ScriptBlock { >> Start-Sleep -Seconds 60 >> Remove-Item $using:tempDir -Recurse -Force >> } >> Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Running True localhost ... PS C:\Users\Administrator>
08-17
PS C:\Users\Administrator\Desktop> # ===== 1. 修复网络连接问题 ===== PS C:\Users\Administrator\Desktop> function Repair-NetworkConnection { >> param( >> [string]$TargetIP = "192.168.1.100" >> ) >> >> # 手动设置DNS服务器 >> Write-Host "🔧 手动设置DNS服务器..." -ForegroundColor Cyan >> $adapters = Get-DnsClientServerAddress -AddressFamily IPv4 | >> Where-Object { $_.ServerAddresses -ne $null } >> $adapters | Set-DnsClientServerAddress -ServerAddresses ("8.8.8.8", "114.114.114.114") >> >> # 重启网络适配器(跳过物理适配器) >> Write-Host "🔄 重启虚拟网络适配器..." -ForegroundColor Cyan >> Get-NetAdapter | Where-Object { $_.InterfaceType -ne 6 } | Restart-NetAdapter -Confirm:$false >> >> # 清除网络缓存 >> Write-Host "🧹 清除网络缓存..." -ForegroundColor Cyan >> arp -d * >> ipconfig /flushdns >> nbtstat -R >> >> # 重置Winsock(不要求重启) >> Write-Host "⚙️ 重置Winsock..." -ForegroundColor Cyan >> netsh winsock reset catalog >> >> # 测试连接 >> if (Test-Connection $TargetIP -Count 1 -Quiet) { >> Write-Host "✅ 网络连接已恢复" -ForegroundColor Green >> return $true >> } >> >> Write-Host "⚠️ 网络连接部分恢复,可能需要系统重启" -ForegroundColor Yellow >> return $false >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # ===== 2. 修复Python环境(使用备用源)===== PS C:\Users\Administrator\Desktop> function Repair-PythonEnvironment { >> param( >> [string]$PythonPath = "E:\Python310" >> ) >> >> # 验证Python安装 >> if (-not (Test-Path $PythonPath)) { >> Write-Host "❌ Python路径不存在: $PythonPath" -ForegroundColor Red >> return $false >> } >> >> # 修复无效的包分布警告 >> $invalidDistPath = Join-Path $PythonPath "Lib\site-packages\-odelscope" >> if (Test-Path $invalidDistPath) { >> Remove-Item $invalidDistPath -Recurse -Force -ErrorAction SilentlyContinue >> Write-Host "✅ 已删除无效包分布: $invalidDistPath" -ForegroundColor Green >> } >> >> # 修复pip安装 >> try { >> Write-Host "🔧 修复pip安装..." -ForegroundColor Cyan >> >> # 使用国内镜像源 >> $getPipPath = Join-Path $env:TEMP "get-pip.py" >> $pipSources = @( >> "https://repo.huaweicloud.com/python/get-pip.py", >> "https://mirrors.aliyun.com/pypi/get-pip.py" >> ) >> >> foreach ($source in $pipSources) { >> try { >> Invoke-WebRequest -Uri $source -OutFile $getPipPath -ErrorAction Stop >> break >> } >> catch { >> Write-Host "⚠️ 下载失败: $source" -ForegroundColor Yellow >> } >> } >> >> if (-not (Test-Path $getPipPath)) { >> throw "所有镜像源均不可用" >> } >> >> # 重新安装pip >> python $getPipPath --no-warn-script-location >> >> # 配置国内镜像源 >> $pipConfig = @" >> [global] >> index-url = https://pypi.tuna.tsinghua.edu.cn/simple >> trusted-host = pypi.tuna.tsinghua.edu.cn >> "@ >> $pipConfig | Out-File "$env:APPDATA\pip\pip.ini" -Encoding ascii >> >> # 升级核心组件 >> python -m pip install --upgrade pip setuptools wheel >> >> Write-Host "✅ pip已修复" -ForegroundColor Green >> return $true >> } >> catch { >> Write-Host "❌ pip修复失败: $_" -ForegroundColor Red >> return $false >> } >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # ===== 3. 安装.NET SDK(兼容版本)===== PS C:\Users\Administrator\Desktop> function Install-DotNetSDK { >> # 获取最新LTS版本 >> $version = (Invoke-RestMethod "https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/releases-index.json"). >> 'releases-index' | >> Where-Object { $_.'channel-version' -match '^\d+\.\d+$' } | >> Sort-Object { [version]$_.'channel-version' } -Descending | >> Select-Object -First 1 | >> ForEach-Object { >> (Invoke-RestMethod $_.'releases.json'). >> 'releases' | >> Where-Object { $_.'release-version' -match '^\d+\.\d+\.\d+$' } | >> Sort-Object { [version]$_.'release-version' } -Descending | >> Select-Object -First 1 >> } | >> ForEach-Object { $_.'release-version' } >> >> if (-not $version) { >> $version = "6.0.400" # 回退版本 >> } >> >> # 安装最新LTS版本 >> $installScriptPath = "$env:TEMP\dotnet-install.ps1" >> Invoke-WebRequest "https://dot.net/v1/dotnet-install.ps1" -OutFile $installScriptPath >> & $installScriptPath -Channel LTS -Runtime dotnet >> >> # 验证安装 >> $dotnetVersion = dotnet --version >> if ($dotnetVersion) { >> Write-Host "✅ .NET SDK $dotnetVersion 安装成功" -ForegroundColor Green >> return $true >> } >> >> Write-Host "❌ .NET SDK 安装失败" -ForegroundColor Red >> return $false >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # ===== 4. 定义缺失的关键函数 ===== PS C:\Users\Administrator\Desktop> function Install-FromRepository { >> param( >> [Parameter(Mandatory=$true)] >> [string]$PackageName, >> [string]$Version = "latest", >> [string]$RepositoryPath = "E:\ai_pip_repository" >> ) >> >> $downloadedDir = Join-Path $RepositoryPath "downloaded_packages" >> >> # 搜索本地仓库 >> $localPackages = Get-ChildItem -Path $downloadedDir -Recurse -ErrorAction SilentlyContinue | >> Where-Object { $_.Name -like "*$PackageName*" -and $_.Extension -in @('.whl', '.gz', '.zip') } >> >> if ($localPackages) { >> # 版本选择逻辑 >> if ($Version -eq "latest") { >> $selectedPackage = $localPackages | >> Sort-Object { [regex]::Match($_.Name, '(\d+\.)+\d+').Value } -Descending | >> Select-Object -First 1 >> } else { >> $selectedPackage = $localPackages | >> Where-Object { $_.Name -match "$PackageName-$Version" } | >> Select-Object -First 1 >> } >> >> if (-not $selectedPackage) { >> Write-Host "⚠️ 仓库中未找到指定版本: $PackageName==$Version" -ForegroundColor Yellow >> return >> } >> >> Write-Host "🚀 使用仓库中的版本: $($selectedPackage.Name)" -ForegroundColor Yellow >> >> # 安装主包 >> python -m pip install $selectedPackage.FullName --no-deps --no-index >> >> # 安装依赖 >> $depReport = Test-RepositoryDependency -PackageName $PackageName -RepositoryPath $RepositoryPath >> if ($depReport.MissingDependencies.Count -gt 0) { >> Write-Host "🔍 安装依赖包..." -ForegroundColor Cyan >> $depReport.MissingDependencies | ForEach-Object { >> Install-FromRepository $_ -RepositoryPath $RepositoryPath >> } >> } >> return >> } >> >> # 本地仓库不存在则下载并保存 >> Write-Host "🌐 从镜像下载: $PackageName" -ForegroundColor Magenta >> >> # 创建临时下载目录 >> $tempDir = Join-Path $env:TEMP ([System.Guid]::NewGuid().ToString()) >> New-Item -ItemType Directory -Path $tempDir -Force | Out-Null >> >> try { >> # 下载包 >> if ($Version -eq "latest") { >> python -m pip download $PackageName -d $tempDir >> } else { >> python -m pip download "${PackageName}==${Version}" -d $tempDir >> } >> >> # 获取下载的文件 >> $downloadedFiles = Get-ChildItem $tempDir -File -ErrorAction SilentlyContinue | >> Where-Object { $_.Extension -in @('.whl', '.gz', '.zip') } >> >> if (-not $downloadedFiles) { >> throw "未找到下载的包文件" >> } >> >> # 安装并保存每个包 >> foreach ($file in $downloadedFiles) { >> # 安装主包 >> python -m pip install $file.FullName >> >> # 保存到仓库 >> $savePath = Join-Path $downloadedDir $file.Name >> Copy-Item -Path $file.FullName -Destination $savePath -Force >> Write-Host "💾 已保存到仓库: $($file.Name)" -ForegroundColor Green >> } >> } >> catch { >> Write-Host "❌ 安装失败: $_" -ForegroundColor Red >> } >> finally { >> # 清理临时目录 >> Remove-Item $tempDir -Recurse -Force -ErrorAction SilentlyContinue >> } >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> function Update-RepositoryIndex { >> param( >> [string]$RepositoryPath = "E:\ai_pip_repository" >> ) >> >> $downloadedDir = Join-Path $RepositoryPath "downloaded_packages" >> >> # 创建简单的索引文件 >> $indexFile = Join-Path $RepositoryPath "index.txt" >> Get-ChildItem $downloadedDir -File | >> Select-Object Name, Length, LastWriteTime | >> Format-Table -AutoSize | >> Out-File $indexFile -Encoding UTF8 >> >> Write-Host "✅ 仓库索引已更新: $indexFile" -ForegroundColor Green >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # ===== 执行步骤 ===== PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 1. 修复网络连接 PS C:\Users\Administrator\Desktop> Repair-NetworkConnection -TargetIP "192.168.1.100" 🔧 手动设置DNS服务器... 🔄 重启虚拟网络适配器... 🧹 清除网络缓存... Windows IP 配置 已成功刷新 DNS 解析缓存。 NBT 远程缓存名称表的成功清除和预加载。 ⚙️ 重置Winsock... 成功地重置 Winsock 目录。 你必须重新启动计算机才能完成重置。 ⚠️ 网络连接部分恢复,可能需要系统重启 False PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 2. 修复Python环境 PS C:\Users\Administrator\Desktop> Repair-PythonEnvironment 🔧 修复pip安装... ⚠️ 下载失败: https://repo.huaweicloud.com/python/get-pip.py E:\Python310\lib\site-packages\_distutils_hack\__init__.py:15: UserWarning: Distutils was imported before Setuptools, but importing Setuptools also replaces the `distutils` module in `sys.modules`. This may lead to undesirable behaviors or errors. To avoid these issues, avoid using distutils directly, ensure that setuptools is installed in the traditional way (e.g. not an editable install), and/or make sure that setuptools is always imported before distutils. warnings.warn( E:\Python310\lib\site-packages\_distutils_hack\__init__.py:30: UserWarning: Setuptools is replacing distutils. Support for replacing an already imported distutils is deprecated. In the future, this condition will fail. Register concerns at https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml warnings.warn( Traceback (most recent call last): File "C:\Users\ADMINI~1\AppData\Local\Temp\get-pip.py", line 23974, in <module> main() File "C:\Users\ADMINI~1\AppData\Local\Temp\get-pip.py", line 199, in main bootstrap(tmpdir=tmpdir) File "C:\Users\ADMINI~1\AppData\Local\Temp\get-pip.py", line 121, in bootstrap import setuptools # noqa File "E:\Python310\lib\site-packages\setuptools\__init__.py", line 21, in <module> import _distutils_hack.override # noqa: F401 File "E:\Python310\lib\site-packages\_distutils_hack\override.py", line 1, in <module> __import__('_distutils_hack').do_override() File "E:\Python310\lib\site-packages\_distutils_hack\__init__.py", line 89, in do_override ensure_local_distutils() File "E:\Python310\lib\site-packages\_distutils_hack\__init__.py", line 76, in ensure_local_distutils assert '_distutils' in core.__file__, core.__file__ AssertionError: E:\Python310\lib\distutils\core.py ❌ pip修复失败: 未能找到路径“C:\Users\Administrator\AppData\Roaming\pip\pip.ini”的一部分。 False PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 3. 安装.NET SDK PS C:\Users\Administrator\Desktop> Install-DotNetSDK dotnet-install: Remote file https://builds.dotnet.microsoft.com/dotnet/Runtime/8.0.19/dotnet-runtime-8.0.19-win-x64.zip size is 33298518 bytes. dotnet-install: Downloaded file https://builds.dotnet.microsoft.com/dotnet/Runtime/8.0.19/dotnet-runtime-8.0.19-win-x64.zip size is 33298518 bytes. dotnet-install: The remote and local file sizes are equal. dotnet-install: Extracting the archive. dotnet-install: Adding to current process PATH: "C:\Users\Administrator\AppData\Local\Microsoft\dotnet\". Note: This change will not be visible if PowerShell was run as a child process. dotnet-install: Note that the script does not ensure your Windows version is supported during the installation. dotnet-install: To check the list of supported versions, go to https://learn.microsoft.com/dotnet/core/install/windows#supported-versions dotnet-install: Installed version is 8.0.19 dotnet-install: Installation finished The command could not be loaded, possibly because: * You intended to execute a .NET application: The application '--version' does not exist. * You intended to execute a .NET SDK command: No .NET SDKs were found. Download a .NET SDK: https://aka.ms/dotnet/download Learn about SDK resolution: https://aka.ms/dotnet/sdk-not-found ❌ .NET SDK 安装失败 False PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 4. 初始化仓库 PS C:\Users\Administrator\Desktop> Initialize-PipRepository -RepositoryPath "E:\ai_pip_repository" Initialize-PipRepository : 无法将“Initialize-PipRepository”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查 名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + Initialize-PipRepository -RepositoryPath "E:\ai_pip_repository" + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Initialize-PipRepository:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 5. 安装包 PS C:\Users\Administrator\Desktop> Install-FromRepository "torch" -Version "2.0.0" -RepositoryPath "E:\ai_pip_repository" 🌐 从镜像下载: torch E:\Python310\python.exe: No module named pip ❌ 安装失败: 未找到下载的包文件 PS C:\Users\Administrator\Desktop> Install-FromRepository "torchvision" -Version "0.15.1" -RepositoryPath "E:\ai_pip_repository" 🌐 从镜像下载: torchvision E:\Python310\python.exe: No module named pip ❌ 安装失败: 未找到下载的包文件 PS C:\Users\Administrator\Desktop> Install-FromRepository "torchaudio" -Version "2.0.1" -RepositoryPath "E:\ai_pip_repository" 🌐 从镜像下载: torchaudio E:\Python310\python.exe: No module named pip ❌ 安装失败: 未找到下载的包文件 PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 6. 更新仓库索引 PS C:\Users\Administrator\Desktop> Update-RepositoryIndex -RepositoryPath "E:\ai_pip_repository" ✅ 仓库索引已更新: E:\ai_pip_repository\index.txt PS C:\Users\Administrator\Desktop>
08-23
PowerShell 7 环境已加载 (版本: 7.5.2) PowerShell 7 环境已加载 (版本: 7.5.2) PS C:\Users\Administrator\Desktop> cd E:\PyTorch_Build\pytorch PS E:\PyTorch_Build\pytorch> python -m venv rtx5070_env PS E:\PyTorch_Build\pytorch> .\rtx5070_env\Scripts\activate (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 1. 运行修复脚本 (rtx5070_env) PS E:\PyTorch_Build\pytorch> .\complete_install_fix.ps1 尝试从备用源下载: https://pilotfiber.dl.sourceforge.net/project/openblas/v0.3.27/OpenBLAS-0.3.27-x64.zip ❌ 下载失败: The variable '$localZip' cannot be retrieved because it has not been set. 尝试从备用源下载: https://cfhcable.dl.sourceforge.net/project/openblas/v0.3.27/OpenBLAS-0.3.27-x64.zip ❌ 下载失败: The variable '$localZip' cannot be retrieved because it has not been set. 尝试从备用源下载: https://superb-sea2.dl.sourceforge.net/project/openblas/v0.3.27/OpenBLAS-0.3.27-x64.zip ❌ 下载失败: The variable '$localZip' cannot be retrieved because it has not been set. 尝试从GitHub直接下载... InvalidOperation: E:\PyTorch_Build\pytorch\complete_install_fix.ps1:25 Line | 25 | Invoke-WebRequest -Uri $githubRaw -OutFile $localZip | ~~~~~~~~~ | The variable '$localZip' cannot be retrieved because it has not been set. InvalidOperation: E:\PyTorch_Build\pytorch\complete_install_fix.ps1:35 Line | 35 | [System.IO.Compression.ZipFile]::ExtractToDirectory($localZip, $newIn … | ~~~~~~~~~ | The variable '$localZip' cannot be retrieved because it has not been set. Find-BLASBinary: E:\PyTorch_Build\pytorch\complete_install_fix.ps1:38 Line | 38 | $blasFile = Find-BLASBinary -SearchPath $newInstallPath | ~~~~~~~~~~~~~~~ | The term 'Find-BLASBinary' is not recognized as a name of a cmdlet, function, script file, or executable | program. Check the spelling of the name, or if a path was included, verify that the path is correct and try | again. ⚠️ 二进制分发版无效,尝试从源码编译... Chocolatey v2.5.0 3 validations performed. 2 success(es), 1 warning(s), and 0 error(s). Validation Warnings: - A pending system reboot request has been detected, however, this is being ignored due to the current Chocolatey configuration. If you want to halt when this occurs, then either set the global feature using: choco feature enable --name="exitOnRebootDetected" or pass the option --exit-when-reboot-detected. Installing the following packages: cmake By installing, you accept licenses for the packages. Downloading package from source 'https://community.chocolatey.org/api/v2/' Progress: Downloading cmake.install 4.1.1... 100% cmake.install v4.1.1 [Approved] cmake.install package files install completed. Performing other installation steps. Installing 64-bit cmake.install... cmake.install has been installed. The install of cmake.install was successful. Software installed as 'msi', install location is likely default. Downloading package from source 'https://community.chocolatey.org/api/v2/' Progress: Downloading cmake 4.1.1... 100% cmake v4.1.1 [Approved] cmake package files install completed. Performing other installation steps. The install of cmake was successful. Deployed to 'C:\ProgramData\chocolatey\lib\cmake' Chocolatey installed 2/2 packages. See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log). Chocolatey v2.5.0 3 validations performed. 2 success(es), 1 warning(s), and 0 error(s). Validation Warnings: - A pending system reboot request has been detected, however, this is being ignored due to the current Chocolatey configuration. If you want to halt when this occurs, then either set the global feature using: choco feature enable --name="exitOnRebootDetected" or pass the option --exit-when-reboot-detected. Installing the following packages: mingw By installing, you accept licenses for the packages. Downloading package from source 'https://community.chocolatey.org/api/v2/' Progress: Downloading mingw 13.2.0... 100% mingw v13.2.0 [Approved] mingw package files install completed. Performing other installation steps. Downloading mingw 64 bit from 'https://github.com/niXman/mingw-builds-binaries/releases/download/13.2.0-rt_v11-rev0/x86_64-13.2.0-release-posix-seh-ucrt-rt_v11-rev0.7z' Progress: 100% - Completed download of C:\Users\Administrator\AppData\Local\Temp\chocolatey\mingw\13.2.0\x86_64-13.2.0-release-posix-seh-ucrt-rt_v11-rev0.7z (69.57 MB). Download of x86_64-13.2.0-release-posix-seh-ucrt-rt_v11-rev0.7z (69.57 MB) completed. Hashes match. Extracting C:\Users\Administrator\AppData\Local\Temp\chocolatey\mingw\13.2.0\x86_64-13.2.0-release-posix-seh-ucrt-rt_v11-rev0.7z to C:\ProgramData\chocolatey\lib\mingw\tools\install... C:\ProgramData\chocolatey\lib\mingw\tools\install Testing path: C:\ProgramData\mingw64\mingw32\bin Testing path: C:\ProgramData\mingw64\mingw64\bin PATH environment variable does not have C:\ProgramData\mingw64\mingw64\bin in it. Adding... Environment Vars (like PATH) have changed. Close/reopen your shell to see the changes (or in powershell/cmd.exe just type `refreshenv`). The install of mingw was successful. Deployed to 'C:\ProgramData\chocolatey\lib\mingw\tools\install' Chocolatey installed 1/1 packages. See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log). Cloning into 'OpenBLAS'... remote: Enumerating objects: 81610, done. remote: Counting objects: 100% (42/42), done. remote: Compressing objects: 100% (26/26), done. remote: Total 81610 (delta 15), reused 21 (delta 6), pack-reused 81568 (from 2) Receiving objects: 100% (81610/81610), 59.50 MiB | 6.03 MiB/s, done. Resolving deltas: 100% (65602/65602), done. Updating files: 100% (12531/12531), done. Directory: E:\PyTorch_Build\pytorch\OpenBLAS Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 2025/9/2 0:29 build CMake Error: CMake was unable to find a build program corresponding to "MinGW Makefiles". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool. CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage CMake Error: CMAKE_ASM_COMPILER not set, after EnableLanguage -- Configuring incomplete, errors occurred! mingw32-make: E:\PyTorch_Build\pytorch\build_openblas_from_source.ps1:14 Line | 14 | mingw32-make -j8 | ~~~~~~~~~~~~ | The term 'mingw32-make' is not recognized as a name of a cmdlet, function, script file, or executable program. | Check the spelling of the name, or if a path was included, verify that the path is correct and try again. mingw32-make: E:\PyTorch_Build\pytorch\build_openblas_from_source.ps1:15 Line | 15 | mingw32-make install | ~~~~~~~~~~~~ | The term 'mingw32-make' is not recognized as a name of a cmdlet, function, script file, or executable program. | Check the spelling of the name, or if a path was included, verify that the path is correct and try again. (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # 2. 验证环境 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> Write-Host "当前OpenBLAS_HOME: $env:OpenBLAS_HOME" 当前OpenBLAS_HOME: E:\Libs\OpenBLAS_Build (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # 3. 检查文件 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> dir "$env:OpenBLAS_HOME" -Recurse | Where-Object { $_.Name -like "*blas*" } (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # 4. 测试PyTorch配置 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> python -c "import os; print('USE_OPENBLAS:', os.environ.get('USE_OPENBLAS')); print('路径验证:', os.path.exists(os.path.join(os.environ['OpenBLAS_HOME'], 'bin', 'openblas.dll')))" USE_OPENBLAS: None 路径验证: False (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # 1. 保存修复后的脚本 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # 将上述两个脚本保存为: (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # - fixed_complete_install_fix.ps1 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # - fixed_build_openblas_from_source.ps1 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # 2. 启动自动安装流程 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> .\fixed_complete_install_fix.ps1 .\fixed_complete_install_fix.ps1: The term '.\fixed_complete_install_fix.ps1' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # 3. 设置电源选项(防止休眠) (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> powercfg -change -standby-timeout-ac 0 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> powercfg -change -hibernate-timeout-ac 0 (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> # 4. 启用远程监控(可选) (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> $webhook = "https://webhook.site/your-unique-url" (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> $status = "开始编译OpenBLAS" (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build> Invoke-RestMethod -Uri $webhook -Method Post -Body $status Invoke-RestMethod: Error: Token "your-unique-url" not found - Webhook.site Webhook.site Error Token "your-unique-url" not found The URL was deleted, or expired automatically. To avoid URLs expiring automatically, you can upgrade to a Webhook.site subscription. Upgrade Now Home   Control Panel   Create Account   Contact Support   Login (rtx5070_env) PS E:\PyTorch_Build\pytorch\OpenBLAS\build>
09-03
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值