Build a PowerShell cmdlet

本文介绍如何使用Windows PowerShell开发命令行工具,包括创建命令集(cmdlet)、使用正则表达式、集成自定义PowerShell插件以及利用扩展类型系统(ETS)扩展PowerShell对象。通过实例展示如何获取本地IIS7服务器的网站列表,并实现支持通配符的过滤功能。

Link:http://www.codeproject.com/KB/powershell/PowerShell.aspx?display=Mobile

What is Windows PowerShell?

Windows PowerShell (a.k.a. Monad) is a new CLI (Command Line Interface) provided by Microsoft. PowerShell is based on .NET Framework 2.0, and passes data as .NET objects.

What are we going to do?

In this article, you'll see how to develop a commandlet (cmdlet, PowerShell commands) which support wildcards, and uses ETS (Extended Type System), and how to use CustomPSSnapIn.

The sample uses IIS 7 and the IIS 7 .NET libraries (Microsoft.Web.Administration) to retrieve the list of websites in the local IIS 7 server.

How to begin?

  1. First, download Windows PowerShell, of course.
  2. Download Windows SDK
  3. Download PowerShell template for Visual Studio(optional).

What are Cmdlets actually?

Cmdlets are tiny .NET classes derived from System.Management.Automation.Cmdlet or fromSystem.Management.Automation.PSCmdlet, and override a few methods with your own logic. The cmdlets are installed to PowerShell, and can be used from PowerShell, or from other applications which use PowerShell to invoke cmdlets.

Cmdlet vs. PSCmelet

A cmdlet class can derived from two different classes: Cmdlet andPSCmdlet. The difference is how much you depend on the Windows PowerShell environment. When deriving fromCmdlet, you aren't really depending on PowerShell. You are not impacted by any changes in the PowerShell runtime. In addition, your cmdlet can be invoked directly from any application instead of invoking it through the Windows PowerShell runtime.

In most cases, deriving from Cmdlet is the best choice, except when you need full integration with the PowerShell runtime, access to session state data, call scripts etc. Then, you'll derive fromPSCmdlet.

Cmdlet attribute

Every cmdlet has a name in the same template: verb-noun. The verb (get, set, new, add, etc.) is from a built-in list of verb names. The noun is for your choice.

The first part in the cmdlet class (getWebsites.cs) is:

[Cmdlet(VerbsCommon.Get, "ws" SupportsShouldProcess = true)]

The verb is "Get" (from the enum VerbsCommon), the noun is "ws", and we supportsShouldProcess. It's very important to use the verb from one of the enums.

Note that in the top of the code, I have these using statements:

using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Collections;
using Microsoft.Web.Administration;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reflection;

The ones in bolds are "special" namespaces which are relevant for PowerShell, exceptMicrosoft.Web.Administration which is used to manage IIS 7.

Parameters

Almost any PowerShell cmdlet will use parameters to help users get relevant information. The parameters are, actually, properties which have theParameterAttribute before:

[Parameter(Position = 0,
Mandatory = true,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Enter filter by site name (support wildcard)")]
[Alias("SiteName")]

public string Name
{
    set { names = value; }
}

Parameters can be accessed using position or property name. This means that if we set the parameter at position 0, you can call the cmdlet like this:get-websites *. The "*" is the parameter, or using property name:get-websites -Name *. Here, we also define the alias:get-websites -SiteName *.

A mandatory parameter means the user must enter a value for the parameter.

The main logic

In our cmdlet, we can override a few methods. We must override at least one from this list:

BeginProcessing

The code here, in most cases, is used to prepare the cmdlet. This code runs only once, when the cmdlet calls.

ProcessRecord

This is the most commonly overridden method. This method includes the main logic. The code can run more than once, as required.

EndProcessing

This overridden method is used to finalize the cmdlet operation.

We can also override the StopProcessing method, which includes code that will run on an unexpected stop of a cmdlet (for example, the user uses Ctrl+c).

I override only the ProcessRecord method. First, I create an instance of the genericSystem.Collections.ObjectModel.Collection<> collection. This is the collection type PowerShell uses. The type isPSObject, which is the main object PowerShell uses.

Because we want to support wildcards, I use the built-in wildcard classes that comes with PowerShell:

WildcardOptions options = WildcardOptions.IgnoreCase |WildcardOptions.Compiled;
WildcardPattern wildcard = new WildcardPattern(names, options); 

Then, we create an instance of Microsoft.Web.Administration.ServerManager, the object used to manage IIS 7 websites.

In the foreach loop, we check for every site to see if its name matches the wildcard. If it does, we convert it toPSObject.

Extended Type System

Extended Type System is one of the main and most interesting PowerShell concepts. We can extend any type we want, and add members in addition to the built-in ones. ThePSObject object is the main object in PowerShell, because it includes the original object and the extended members in the same object, and gives the user who invokes this cmdlet the option to use any member - the original members and the extended ones.

ps.Properties.Add(new PSNoteProperty("MaxBandwidthMB", site.Limits.MaxBandwidth / 1024));

Here, we add a new property called MaxBandwidthMB, and its value is the the original bandwidth value / 1024.

Types can be extended from code, or from XML files, in a specific format. Here, we will see an example to extend a type with a new property - but we can add properties and methods from a lot of types: aliases, scripts, code methods, etc.

Finally, we add the PSObject instance which includes the original (early bound object) and the extended members to the collection, and use theWriteHost method to write it to the host (can be PowerShell command line host, or another application that invoke our cmdlet).

After you'll finish the cmdlet, you can get a list of the members of the object returned from the cmdlet. Here you can see our extended property (marked):

Screenshot - Capture.jpg

In case of an exception...

We use a try...catch statement, and if an exception occurs, we use theWriteError method to write information about the error to the host.

Formats

If we use this cmdlet now from the console, we will get a strange output, which includes the object types and a few values. We have to specify the default output view we want. We do this in theformat.ps1xml file. Note that we use theMaxBandwidthMB property, which is an extended one.

This is the output without the format file:

Screenshot - Capture1.jpg

Snap In

The snap-in includes the details PowerShell needs to install the cmdlet. We can derive it fromPSSnapIn which is the "default" - install everything you can, or fromCustomPSSnapIn, then we set exactly what to do.

Here, we add the cmdlet and the format file.

First, we define a collection for cmdlets, formats, types, and providers. In the constructor, we add the cmdlet and the format file. We also override a few properties to include information about our snap-in. And, we override the properties to return our collection of cmdlets and formats.

Installation

From PowerShell, we install the snap-in with installutil.exe, part of the .NET Framework SDK. I wrote a little function you can add to your profile:

function installutil
{
    param([string]$dllPath=$(throw "Please Enter the DLL path to Install!"))
    set-alias installutil $env:windir\Microsoft.NET\Framework\v2.0.50727\installutil
    if(test-path $dllPath)
    {
        installutil /u $dllpath
        installutil $dllpath
        write-host "snap-in installed. now, you can add it to your shell instance"
    }
    else{
        write-error "The file does not exist"
    }
}

Now, you just have to enter:

installutil dllPath

Instead of dllPath, enter the full path to the DLL which includes the DLL of the project.

Now, you have to add the snap-in:

add-pssnapin cpdemo

Note that you may have to change the path of the format file in the snapin.cs class file.

And that's all! The cmdlet is ready to use and returns a collection ofPSObjects which includesMicrosoft.Web.Administration.Site and an extended property.

In PowerShell, you can use the object that the cmdlet returns for more things. This command, for example, will save the output to a CSV file:

get-ws d* | Where{$_.MaxBandwidthMB -gt 4000000} | 
           Select-Object Name,MaxBandwidthMB | out-csv c:\csv.csv

This command will save a new CSV file which includes the list of names and theMaxBandwidthMB property for all sites for which the name begins with "d" and where the value of the propertyMaxBandwidthMB > 4000000.



1.E:\Program Files\NVIDIA\CUNND\v9.12里面有bin cudnn samples include lib LICENSE,里面还有子文件12.9和13.0,mdll都在bin,h再include,E:\Program Files\NVIDIA\CUNND\v9.12\lib\13.0\x64里面是lib,12.9同样 2.Set-PythonEnv: C:\Users\Administrator\Documents\PowerShell\Microsoft.PowerShell_profile.ps1:5 Line | 5 | Set-PythonEnv -EnvName global | ~~~~~~~~~~~~~ | The term 'Set-PythonEnv' 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. Set-PythonEnv: C:\Users\Administrator\Documents\PowerShell\Microsoft.PowerShell_profile.ps1:5 Line | 5 | Set-PythonEnv -EnvName global | ~~~~~~~~~~~~~ | The term 'Set-PythonEnv' 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. PS C:\Users\Administrator\Desktop> cd E:\PyTorch_Build\pytorch PS E:\PyTorch_Build\pytorch> python -m venv rtx5070_env Error: [Errno 13] Permission denied: 'E:\\PyTorch_Build\\pytorch\\rtx5070_env\\Scripts\\python.exe' PS E:\PyTorch_Build\pytorch> .\rtx5070_env\Scripts\activate (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 路径验证脚本 (validate_paths.ps1) (rtx5070_env) PS E:\PyTorch_Build\pytorch> $tools = @{ >> "Python" = "E:\Python310\python.exe" >> "Git" = "E:\Program Files\Git\bin\git.exe" >> "CUDA" = "E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\" >> "cuDNN" = "E:\Program Files\NVIDIA\cuDNN\v9.12\" >> "OpenBLAS_Prebuilt" = "E:\Libs\OpenBLAS_Prebuilt\lib\openblas.lib" >> "CMake" = "E:\Program Files\CMake\bin\cmake.exe" >> "Ninja" = "E:\PyTorch_Build\pytorch\rtx5070_env\Scripts\ninja.exe" >> } (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> foreach ($tool in $tools.GetEnumerator()) { >> $exists = Test-Path $tool.Value -ErrorAction SilentlyContinue >> $status = if ($exists) { "✅ 验证通过" } else { "❌ 路径不存在" } >> Write-Host ("{0,-20} {1,-60} {2}" -f $tool.Key, $tool.Value, $status) >> } cuDNN E:\Program Files\NVIDIA\cuDNN\v9.12\ ❌ 路径不存在 OpenBLAS_Prebuilt E:\Libs\OpenBLAS_Prebuilt\lib\openblas.lib ✅ 验证通过 Git E:\Program Files\Git\bin\git.exe ✅ 验证通过 CUDA E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\ ✅ 验证通过 Ninja E:\PyTorch_Build\pytorch\rtx5070_env\Scripts\ninja.exe ✅ 验证通过 CMake E:\Program Files\CMake\bin\cmake.exe ✅ 验证通过 Python E:\Python310\python.exe ✅ 验证通过 (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 特殊验证:OpenBLAS库文件 (rtx5070_env) PS E:\PyTorch_Build\pytorch> if (Test-Path $tools["OpenBLAS_Prebuilt"]) { >> Write-Host "OpenBLAS库验证通过: $($tools['OpenBLAS_Prebuilt'])" -ForegroundColor Green >> } else { >> Write-Host "错误:OpenBLAS库文件未找到" -ForegroundColor Red >> # 自动搜索备用路径 >> $found = Get-ChildItem "E:\Libs\" -Recurse -Filter "openblas.lib" | Select-Object -First 1 >> if ($found) { >> Write-Host "发现备用路径: $($found.FullName)" -ForegroundColor Yellow >> $env:OpenBLAS_HOME = $found.Directory.Parent.FullName >> } >> } OpenBLAS库验证通过: E:\Libs\OpenBLAS_Prebuilt\lib\openblas.lib (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 修复PowerShell配置文件 (fix_profile.ps1) (rtx5070_env) PS E:\PyTorch_Build\pytorch> $profilePath = "C:\Users\Administrator\Documents\PowerShell\Microsoft.PowerShell_profile.ps1" (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 备份原始配置文件 (rtx5070_env) PS E:\PyTorch_Build\pytorch> $backupPath = "$profilePath.backup_$(Get-Date -Format 'yyyyMMdd')" (rtx5070_env) PS E:\PyTorch_Build\pytorch> Copy-Item $profilePath $backupPath -Force (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 修正配置文件内容 (rtx5070_env) PS E:\PyTorch_Build\pytorch> (Get-Content $profilePath) | ForEach-Object { >> # 修复Set-PythonEnv调用问题 >> if ($_ -match "Set-PythonEnv -EnvName global") { >> '# ' + $_ + " # 已禁用此问题命令" >> } >> # 添加模块自动加载 >> elseif ($_ -match "Export-ModuleMember") { >> $_ + "`nImport-Module $PSScriptRoot\EnvManager -Force" >> } >> else { >> $_ >> } >> } | Set-Content $profilePath (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 创建模块加载器 (rtx5070_env) PS E:\PyTorch_Build\pytorch> $modulePath = "C:\Users\Administrator\Documents\PowerShell\Modules\EnvManager" (rtx5070_env) PS E:\PyTorch_Build\pytorch> New-Item -ItemType Directory -Path $modulePath -Force | Out-Null (rtx5070_env) PS E:\PyTorch_Build\pytorch> @" >> # EnvManager.psm1 >> function Set-PythonEnv { >> # 修正后的实现代码... >> } >> >> Export-ModuleMember -Function Set-PythonEnv >> "@ | Set-Content "$modulePath\EnvManager.psm1" (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> Write-Host "PowerShell配置文件已修复,问题命令已注释" -ForegroundColor Green PowerShell配置文件已修复,问题命令已注释 (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 禁用WSL更新提示 (disable_wsl_prompt.ps1) (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 方法1:注册表禁用 (rtx5070_env) PS E:\PyTorch_Build\pytorch> New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModel\StateChange" ` >> -Name "DisableWSLUpdateNotification" ` >> -Value 1 ` >> -PropertyType DWORD ` >> -Force DisableWSLUpdateNotification : 1 PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curren tVersion\AppModel\StateChange PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curren tVersion\AppModel PSChildName : StateChange PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 方法2:修改VS Code设置 (rtx5070_env) PS E:\PyTorch_Build\pytorch> $vscodeSettings = @{ >> "wsl.deprecated" = @{ >> "showDeprecatedNotification" = $false >> }; >> "extensions.ignoreRecommendations" = $true; >> } (rtx5070_env) PS E:\PyTorch_Build\pytorch> $json = $vscodeSettings | ConvertTo-Json -Depth 3 (rtx5070_env) PS E:\PyTorch_Build\pytorch> Set-Content -Path "$env:APPDATA\Code\User\settings.json" -Value $json (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> # 方法3:禁用WSL服务(如果不使用) (rtx5070_env) PS E:\PyTorch_Build\pytorch> Stop-Service "LxssManager" -Force Stop-Service: Cannot find any service with service name 'LxssManager'. (rtx5070_env) PS E:\PyTorch_Build\pytorch> Set-Service "LxssManager" -StartupType Disabled Set-Service: Service 'LxssManager' was not found on computer '.'. (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> Write-Host "WSL更新提示已禁用" -ForegroundColor Green WSL更新提示已禁用 (rtx5070_env) PS E:\PyTorch_Build\pytorch> sequenceDiagram sequenceDiagram: The term 'sequenceDiagram' 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> participant 用户 participant: The term 'participant' 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> participant PowerShell participant: The term 'participant' 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> participant VS Code participant: The term 'participant' 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> (rtx5070_env) PS E:\PyTorch_Build\pytorch> 用户->>PowerShell: 运行 validate_paths.ps1 用户->>PowerShell:: The term '用户->>PowerShell:' 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> PowerShell->>系统: 验证所有工具路径 PowerShell->>系统:: The term 'PowerShell->>系统:' 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> PowerShell-->>用户: 显示验证结果 PowerShell-->>用户:: The term 'PowerShell-->>用户:' 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> (rtx5070_env) PS E:\PyTorch_Build\pytorch> 用户->>PowerShell: 运行 fix_profile.ps1 用户->>PowerShell:: The term '用户->>PowerShell:' 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> PowerShell->>系统: 修复配置文件 PowerShell->>系统:: The term 'PowerShell->>系统:' 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> PowerShell-->>用户: 确认修复完成 PowerShell-->>用户:: The term 'PowerShell-->>用户:' 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> (rtx5070_env) PS E:\PyTorch_Build\pytorch> 用户->>PowerShell: 运行 disable_wsl_prompt.ps1 用户->>PowerShell:: The term '用户->>PowerShell:' 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> PowerShell->>系统: 禁用WSL提示 PowerShell->>系统:: The term 'PowerShell->>系统:' 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> PowerShell-->>用户: 确认禁用成功 PowerShell-->>用户:: The term 'PowerShell-->>用户:' 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> (rtx5070_env) PS E:\PyTorch_Build\pytorch> 用户->>VS Code: 启动 用户->>VS: The term '用户->>VS' 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> VS Code-->>用户: 无WSL提示 VS: The term 'VS' 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> # 最终验证脚本 (final_check.ps1) (rtx5070_env) PS E:\PyTorch_Build\pytorch> Write-Host "=== 环境路径验证 ===" -ForegroundColor Cyan === 环境路径验证 === (rtx5070_env) PS E:\PyTorch_Build\pytorch> .\validate_paths.ps1 .\validate_paths.ps1: The term '.\validate_paths.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> (rtx5070_env) PS E:\PyTorch_Build\pytorch> Write-Host "`n=== PowerShell问题验证 ===" -ForegroundColor Cyan === PowerShell问题验证 === (rtx5070_env) PS E:\PyTorch_Build\pytorch> if (Get-Command Set-PythonEnv -ErrorAction SilentlyContinue) { >> Write-Host "环境切换功能正常" -ForegroundColor Green >> } else { >> Write-Host "环境切换功能修复失败" -ForegroundColor Red >> } 环境切换功能正常 (rtx5070_env) PS E:\PyTorch_Build\pytorch> (rtx5070_env) PS E:\PyTorch_Build\pytorch> Write-Host "`n=== 核心问题验证 ===" -ForegroundColor Cyan === 核心问题验证 === (rtx5070_env) PS E:\PyTorch_Build\pytorch> Write-Host "1. 环境隔离:" 1. 环境隔离: (rtx5070_env) PS E:\PyTorch_Build\pytorch> Switch-Environment Global Switch-Environment: The term 'Switch-Environment' 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> Switch-Environment PyTorch Switch-Environment: The term 'Switch-Environment' 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> (rtx5070_env) PS E:\PyTorch_Build\pytorch> Write-Host "`n2. 依赖锁定:" 2. 依赖锁定: (rtx5070_env) PS E:\PyTorch_Build\pytorch> Lock-Dependencies Lock-Dependencies: The term 'Lock-Dependencies' 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> Write-Host "依赖锁定状态: $(if (Test-Dependencies) {'✅ 正常'} else {'❌ 异常'})" Test-Dependencies: The term 'Test-Dependencies' 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> (rtx5070_env) PS E:\PyTorch_Build\pytorch> Write-Host "`n3. 路径污染:" 3. 路径污染: (rtx5070_env) PS E:\PyTorch_Build\pytorch> Clean-Path Clean-Path: The term 'Clean-Path' 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> Write-Host "当前PATH: $($env:PATH -replace ';', "`n")" 当前PATH: E:\PyTorch_Build\pytorch\rtx5070_env\Scripts C:\Program Files\PowerShell\7 E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\bin E:\Program Files\NVIDIA\CUNND\v9.12\bin\13.0 E:\Program Files\NVIDIA\CUNND\v9.12\lib\13.0\x64 E:\Program Files\CMake\bin C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\bin\Hostx64\x64 E:\Python310\Scripts E:\PyTorch_Build\pytorch\rtx5070_env\Scripts C:\Program Files\PowerShell\7 C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\bin C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\libnvvp C:\Miniconda3\condabin C:\Miniconda3\Scripts E:\PyTorch_Build\pytorch\pytorch_env\Scripts C:\Program Files\PowerShell\7 E:\PyTorch_Build\pytorch\pytorch_env\Scripts C:\Program Files\PowerShell\7 E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\bin\x64 E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\bin E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\bin\x64 E:\PyTorch_Build\pytorch\build\lib.win-amd64-cpython-310\torch\lib E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\bin E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\bin C:\Users\Administrator\AppData\Local\Microsoft\dotnet C:\Users\Administrator\AppData\Local\Microsoft\dotnet C:\Users\Administrator\AppData\Local\Microsoft\dotnet\ C:\Program Files\dotnet C:\WINDOWS\system32 C:\WINDOWS C:\WINDOWS\System32\Wbem C:\WINDOWS\System32\WindowsPowerShell\v1.0\ C:\WINDOWS\System32\OpenSSH\ E:\Python310 C:\Program Files\dotnet\ C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps C:\Users\Administrator\.dotnet\tools C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps C:\Users\Administrator\.dotnet\tools E:\Python310\Scripts E:\Python310\Scripts C:\Program Files\PowerShell\7\ E:\Program Files\Microsoft VS Code\bin E:\Program Files\Git\cmd C:\Program Files\NVIDIA Corporation\Nsight Compute 2025.3.0\ E:\Program Files\CMake\bin C:\Program Files\Microsoft SQL Server\150\Tools\Binn\ C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\ C:\Program Files (x86)\Incredibuild E:\PyTorch_Build\pytorch\build\lib.win-amd64-cpython-310\torch\lib E:\Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\ C:\ProgramData\chocolatey\bin E:\Program Files\Rust\.cargo\bin C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps C:\Users\Administrator\.dotnet\tools C:\Users\Administrator\miniconda3\Scripts E:\Program Files\Rust\.cargo\bin C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps C:\Users\Administrator\.dotnet\tools C:\Users\Administrator\miniconda3\Scripts E:\Program Files\Rust\.cargo\bin C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps C:\Users\Administrator\.dotnet\tools C:\ProgramData\mingw64\mingw64\bin E:\Program Files\7-Zip C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.16.27023\bin\HostX64\x64 E:\Program Files\7-Zip E:\Program Files\Rust\.cargo\bin C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps C:\Users\Administrator\.dotnet\tools C:\ProgramData\mingw64\mingw64\bin (rtx5070_env) PS E:\PyTorch_Build\pytorch>
最新发布
09-04
(.venv) PS E:\PyTorch_Build\pytorch\build> # 使用可靠的路径获取方法 (.venv) PS E:\PyTorch_Build\pytorch\build> $venvPath = "E:\PyTorch_Build\pytorch\build\.venv" (.venv) PS E:\PyTorch_Build\pytorch\build> $torchDir = "$venvPath\Lib\site-packages\torch" (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 检查目录是否存在 (.venv) PS E:\PyTorch_Build\pytorch\build> if (-not (Test-Path $torchDir)) { >> Write-Host "创建缺失的torch目录: $torchDir" >> New-Item -ItemType Directory -Path $torchDir -Force >> } 创建缺失的torch目录: E:\PyTorch_Build\pytorch\build\.venv\Lib\site-packages\torch Directory: E:\PyTorch_Build\pytorch\build\.venv\Lib\site-packages Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 2025/9/1 4:08 torch (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 验证路径 (.venv) PS E:\PyTorch_Build\pytorch\build> Write-Host "Torch目录: $torchDir" Torch目录: E:\PyTorch_Build\pytorch\build\.venv\Lib\site-packages\torch (.venv) PS E:\PyTorch_Build\pytorch\build> $buildDir = "E:\PyTorch_Build\pytorch\build\lib.win-amd64-cpython-310\torch" (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 复制所有必要的构建文件 (.venv) PS E:\PyTorch_Build\pytorch\build> $filesToCopy = @( >> "$buildDir\*.pyd", >> "$buildDir\*.dll", >> "$buildDir\lib\*.dll", >> "$buildDir\lib\*.lib", >> "$buildDir\lib\*.pyd" >> ) (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> foreach ($pattern in $filesToCopy) { >> if (Test-Path $pattern) { >> Get-ChildItem -Path $pattern | ForEach-Object { >> Copy-Item -Path $_.FullName -Destination $torchDir -Force >> Write-Host "已复制: $($_.Name)" >> } >> } else { >> Write-Host "未找到匹配文件: $pattern" >> } >> } 未找到匹配文件: E:\PyTorch_Build\pytorch\build\lib.win-amd64-cpython-310\torch\*.pyd 未找到匹配文件: E:\PyTorch_Build\pytorch\build\lib.win-amd64-cpython-310\torch\*.dll 未找到匹配文件: E:\PyTorch_Build\pytorch\build\lib.win-amd64-cpython-310\torch\lib\*.dll 未找到匹配文件: E:\PyTorch_Build\pytorch\build\lib.win-amd64-cpython-310\torch\lib\*.lib 未找到匹配文件: E:\PyTorch_Build\pytorch\build\lib.win-amd64-cpython-310\torch\lib\*.pyd (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 特别检查核心文件 (.venv) PS E:\PyTorch_Build\pytorch\build> $criticalFiles = @("_C.pyd", "_C_flatbuffer.pyd", "torch_python.dll") (.venv) PS E:\PyTorch_Build\pytorch\build> foreach ($file in $criticalFiles) { >> $filePath = Join-Path $torchDir $file >> if (-not (Test-Path $filePath)) { >> Write-Host "[警告] 核心文件缺失: $file" >> } >> } [警告] 核心文件缺失: _C.pyd [警告] 核心文件缺失: _C_flatbuffer.pyd [警告] 核心文件缺失: torch_python.dll (.venv) PS E:\PyTorch_Build\pytorch\build> $cudaBin = "E:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\bin" (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 获取所有 CUDA DLL (.venv) PS E:\PyTorch_Build\pytorch\build> $cudaDlls = Get-ChildItem -Path $cudaBin -Filter "*.dll" (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 复制到 torch 目录 (.venv) PS E:\PyTorch_Build\pytorch\build> foreach ($dll in $cudaDlls) { >> $destPath = Join-Path $torchDir $dll.Name >> Copy-Item -Path $dll.FullName -Destination $destPath -Force >> Write-Host "已复制CUDA DLL: $($dll.Name)" >> } (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 添加 CUDA 路径到系统 PATH (.venv) PS E:\PyTorch_Build\pytorch\build> $env:PATH = "$cudaBin;$env:PATH" (.venv) PS E:\PyTorch_Build\pytorch\build> # 保存为 torch_diagnose.py (.venv) PS E:\PyTorch_Build\pytorch\build> import os import: The term 'import' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> import sys import: The term 'import' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> import ctypes import: The term 'import' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> import traceback import: The term 'import' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> import platform import: The term 'import' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> def check_file_exists(path): path: The term 'path' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> exists = os.path.exists(path) path: The term 'path' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"[{'✓' if exists else '✗'}] 文件存在: {path}") f[{'✓' if exists else '✗'}] 文件存在: {path}: The term 'f[{'✓' if exists else '✗'}] 文件存在: {path}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> return exists exists: The term 'exists' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> def check_dll_loaded(dll_name): dll_name: The term 'dll_name' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> try: try:: The term 'try:' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> ctypes.CDLL(dll_name) dll_name: The term 'dll_name' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"[✓] DLL已加载: {dll_name}") f[✓] DLL已加载: {dll_name}: The term 'f[✓] DLL已加载: {dll_name}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> return True True: The term 'True' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> except OSError as e: except: The term 'except' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"[✗] DLL加载失败: {dll_name} - {e}") f[✗] DLL加载失败: {dll_name} - {e}: The term 'f[✗] DLL加载失败: {dll_name} - {e}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> return False False: The term 'False' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> def check_module(module_name): module_name: The term 'module_name' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> try: try:: The term 'try:' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> __import__(module_name) module_name: The term 'module_name' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"[✓] 模块已导入: {module_name}") f[✓] 模块已导入: {module_name}: The term 'f[✓] 模块已导入: {module_name}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> return True True: The term 'True' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> except ImportError as e: except: The term 'except' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"[✗] 模块导入失败: {module_name} - {e}") f[✗] 模块导入失败: {module_name} - {e}: The term 'f[✗] 模块导入失败: {module_name} - {e}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> return False False: The term 'False' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> def main(): ParserError: Line | 1 | def main(): | ~ | An expression was expected after '('. (.venv) PS E:\PyTorch_Build\pytorch\build> print("="*50) 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> print("PyTorch 环境诊断工具") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> print("="*50) 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 系统信息 (.venv) PS E:\PyTorch_Build\pytorch\build> print("\n[系统信息]") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"操作系统: {platform.platform()}") f操作系统: {platform.platform()}: The term 'f操作系统: {platform.platform()}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"Python版本: {sys.version}") fPython版本: {sys.version}: The term 'fPython版本: {sys.version}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"Python路径: {sys.executable}") fPython路径: {sys.executable}: The term 'fPython路径: {sys.executable}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"工作目录: {os.getcwd()}") f工作目录: {os.getcwd()}: The term 'f工作目录: {os.getcwd()}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 环境变量 (.venv) PS E:\PyTorch_Build\pytorch\build> print("\n[环境变量]") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"PATH: {os.getenv('PATH')}") fPATH: {os.getenv('PATH')}: The term 'fPATH: {os.getenv('PATH')}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"PYTHONPATH: {os.getenv('PYTHONPATH')}") fPYTHONPATH: {os.getenv('PYTHONPATH')}: The term 'fPYTHONPATH: {os.getenv('PYTHONPATH')}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 确定torch目录 (.venv) PS E:\PyTorch_Build\pytorch\build> torch_dir = None torch_dir: The term 'torch_dir' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> try: try:: The term 'try:' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> import torch import: The term 'import' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> torch_dir = os.path.dirname(torch.__file__) torch.__file__: The term 'torch.__file__' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> except: except:: The term 'except:' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> # 回退方法 (.venv) PS E:\PyTorch_Build\pytorch\build> site_packages = next(p for p in sys.path if 'site-packages' in p) p: The term 'p' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> torch_dir = os.path.join(site_packages, 'torch') ParserError: Line | 1 | torch_dir = os.path.join(site_packages, 'torch') | ~ | Missing argument in parameter list. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"\nTorch目录: {torch_dir}") f\nTorch目录: {torch_dir}: The module 'f' could not be loaded. For more information, run 'Import-Module f'. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 检查核心文件 (.venv) PS E:\PyTorch_Build\pytorch\build> print("\n[核心文件检查]") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> core_files = [ core_files: The term 'core_files' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> "_C.pyd", >> "_C_flatbuffer.pyd", >> "torch_python.dll", >> "c10.dll", >> "c10_cuda.dll" _C.pyd _C_flatbuffer.pyd torch_python.dll c10.dll c10_cuda.dll (.venv) PS E:\PyTorch_Build\pytorch\build> ] ]: The term ']' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> for file in core_files: ParserError: Line | 1 | for file in core_files: | ~ | Missing opening '(' after keyword 'for'. (.venv) PS E:\PyTorch_Build\pytorch\build> file_path = os.path.join(torch_dir, file) ParserError: Line | 1 | file_path = os.path.join(torch_dir, file) | ~ | Missing argument in parameter list. (.venv) PS E:\PyTorch_Build\pytorch\build> check_file_exists(file_path) file_path: The term 'file_path' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 检查依赖项 (.venv) PS E:\PyTorch_Build\pytorch\build> print("\n[DLL依赖检查]") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> for dll in core_files: ParserError: Line | 1 | for dll in core_files: | ~ | Missing opening '(' after keyword 'for'. (.venv) PS E:\PyTorch_Build\pytorch\build> check_dll_loaded(dll) dll: The term 'dll' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 尝试导入torch (.venv) PS E:\PyTorch_Build\pytorch\build> print("\n[模块导入测试]") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> check_module("torch") check_module: The term 'check_module' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 如果torch能导入,检查CUDA (.venv) PS E:\PyTorch_Build\pytorch\build> try: try:: The term 'try:' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> import torch import: The term 'import' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print("\n[PyTorch信息]") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"版本: {torch.__version__}") f版本: {torch.__version__}: The term 'f版本: {torch.__version__}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"CUDA可用: {torch.cuda.is_available()}") fCUDA可用: {torch.cuda.is_available()}: The term 'fCUDA可用: {torch.cuda.is_available()}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> if torch.cuda.is_available(): ParserError: Line | 1 | if torch.cuda.is_available(): | ~ | Missing '(' after 'if' in if statement. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"设备数量: {torch.cuda.device_count()}") f设备数量: {torch.cuda.device_count()}: The term 'f设备数量: {torch.cuda.device_count()}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"设备0名称: {torch.cuda.get_device_name(0)}") f设备0名称: {torch.cuda.get_device_name(0)}: The term 'f设备0名称: {torch.cuda.get_device_name(0)}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 执行简单计算 (.venv) PS E:\PyTorch_Build\pytorch\build> a = torch.ones(1000, device='cuda') ParserError: Line | 1 | a = torch.ones(1000, device='cuda') | ~ | Missing expression after ','. (.venv) PS E:\PyTorch_Build\pytorch\build> b = torch.ones(1000, device='cuda') ParserError: Line | 1 | b = torch.ones(1000, device='cuda') | ~ | Missing expression after ','. (.venv) PS E:\PyTorch_Build\pytorch\build> c = a + b c: The term 'c' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"计算验证: {c.sum().item()} (应为2000)") f计算验证: {c.sum().item()} (应为2000): The term 'f计算验证: {c.sum().item()} (应为2000)' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> except Exception as e: except: The term 'except' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f"\n[错误详情]") f\n[错误详情]: The module 'f' could not be loaded. For more information, run 'Import-Module f'. (.venv) PS E:\PyTorch_Build\pytorch\build> traceback.print_exc() ParserError: Line | 1 | traceback.print_exc() | ~ | An expression was expected after '('. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 打印调试信息 (.venv) PS E:\PyTorch_Build\pytorch\build> print("\n[调试信息]") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> lib_paths = [p for p in sys.path if any(x in p.lower() for x in ['lib', 'site-packages'])] ParserError: Line | 1 | lib_paths = [p for p in sys.path if any(x in p.lower() for x … | ~ | An expression was expected after '('. (.venv) PS E:\PyTorch_Build\pytorch\build> print("Python库路径:") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> for path in lib_paths: ParserError: Line | 1 | for path in lib_paths: | ~ | Missing opening '(' after keyword 'for'. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f" - {path}") f - {path}: The term 'f - {path}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> print("\nPATH中的关键目录:") 无法初始化设备 PRN (.venv) PS E:\PyTorch_Build\pytorch\build> for path in os.getenv('PATH').split(';'): ParserError: Line | 1 | for path in os.getenv('PATH').split(';'): | ~ | Missing opening '(' after keyword 'for'. (.venv) PS E:\PyTorch_Build\pytorch\build> if any(kw in path.lower() for kw in ['cuda', 'bin', 'lib', 'torch']): ParserError: Line | 1 | if any(kw in path.lower() for kw in ['cuda', 'bin', 'lib' … | ~ | Missing '(' after 'if' in if statement. (.venv) PS E:\PyTorch_Build\pytorch\build> print(f" - {path}") f - {path}: The term 'f - {path}' 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. (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> if __name__ == "__main__": ParserError: Line | 1 | if __name__ == "__main__": | ~ | Missing '(' after 'if' in if statement. (.venv) PS E:\PyTorch_Build\pytorch\build> main() ParserError: Line | 1 | main() | ~ | An expression was expected after '('. (.venv) PS E:\PyTorch_Build\pytorch\build> # 运行诊断工具 (.venv) PS E:\PyTorch_Build\pytorch\build> python torch_diagnose.py E:\Python310\python.exe: can't open file 'E:\\PyTorch_Build\\pytorch\\build\\torch_diagnose.py': [Errno 2] No such file or directory (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 如果仍然失败,使用依赖分析工具 (.venv) PS E:\PyTorch_Build\pytorch\build> $dependsUrl = "https://github.com/lucasg/Dependencies/releases/download/v1.11.1/Dependencies_x64_Release.zip" (.venv) PS E:\PyTorch_Build\pytorch\build> $dependsZip = "Dependencies.zip" (.venv) PS E:\PyTorch_Build\pytorch\build> $dependsDir = "Dependencies" (.venv) PS E:\PyTorch_Build\pytorch\build> (.venv) PS E:\PyTorch_Build\pytorch\build> # 下载并运行依赖分析器 (.venv) PS E:\PyTorch_Build\pytorch\build> Invoke-WebRequest -Uri $dependsUrl -OutFile $dependsZip (.venv) PS E:\PyTorch_Build\pytorch\build> Expand-Archive -Path $dependsZip -DestinationPath $dependsDir -Force (.venv) PS E:\PyTorch_Build\pytorch\build> $dependsExe = Join-Path (Resolve-Path $dependsDir) "Dependencies.exe" (.venv) PS E:\PyTorch_Build\pytorch\build> $cModule = Join-Path $torchDir "_C.pyd" (.venv) PS E:\PyTorch_Build\pytorch\build> Start-Process $dependsExe -ArgumentList $cModule (.venv) PS E:\PyTorch_Build\pytorch\build>
09-02
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值