Jac*_*ift 6 powershell batch-file
我正在尝试使用 PowerShell 从 Python 网站将 Python 3 安装程序下载到特定目录中,然后在同一目录中静默运行/安装 .exe,然后将适当的目录添加到我系统的 PATH 变量中。
到目前为止,我想出了:
start cmd /k powershell -Command "(New-Object Net.WebClient).DownloadFile('https://www.python.org/ftp/python/3.6.2/python-3.6.2.exe', 'C:/Tools/python-3.6.2.exe')" &&
c:\Tools\python-3.6.2.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0 TargetDir=c:\Tools\Python362 &&
setx path "%PATH%;C:\Tools\Python362\" /M
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用。命令窗口将打开,然后立即退出。我分别运行了这些命令中的每一个,当我这样做时,它们可以工作,但是当我尝试在同一文件中按顺序运行它们时,它不起作用。任何帮助将不胜感激。
注意:我相信问题源于使用&&
,因为如果我使用&
CMD 提示将持续存在,并执行。但是,这对我没有帮助,因为我需要在第一个命令完成后执行第二个命令,否则第二个命令没有 .exe 可以运行。我希望这只是一个语法错误,因为我对创建批处理文件和使用 Windows 命令行非常陌生。
我个人会在 Powershell 中完成所有操作。
我很想把它放在一个脚本中,像这样:
[CmdletBinding()] Param(
$pythonVersion = "3.6.2"
$pythonUrl = "https://www.python.org/ftp/python/$pythonVersion/python-$pythonVersion.exe"
$pythonDownloadPath = 'C:\Tools\python-$pythonVersion.exe'
$pythonInstallDir = "C:\Tools\Python$pythonVersion"
)
(New-Object Net.WebClient).DownloadFile($pythonUrl, $pythonDownloadPath)
& $pythonDownloadPath /quiet InstallAllUsers=1 PrependPath=1 Include_test=0 TargetDir=$pythonInstallDir
if ($LASTEXITCODE -ne 0) {
throw "The python installer at '$pythonDownloadPath' exited with error code '$LASTEXITCODE'"
}
# Set the PATH environment variable for the entire machine (that is, for all users) to include the Python install dir
[Environment]::SetEnvironmentVariable("PATH", "${env:path};${pythonInstallDir}", "Machine")
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样从 cmd.exe 调用脚本:
Powershell.exe -File X:\Path\to\Install-Python.ps1
Run Code Online (Sandbox Code Playgroud)
该Param()
块定义了 Python 版本的默认值、下载它的 URL、保存它的位置以及安装它的位置,但是如果这些选项变得有用,您可以覆盖这些选项。你可以像这样传递这些参数:
Powershell.exe -File X:\Path\to\Install-Python.ps1 -version 3.4.0 -pythonInstallDir X:\Somewhere\Else\Python3.4.0
Run Code Online (Sandbox Code Playgroud)
也就是说,你也绝对可以在纯 Powershell 中做一个单行。根据您的描述,我认为您不需要添加start cmd /k
前缀 - 您应该可以直接调用 Powershell.exe,如下所示:
powershell -command "(New-Object Net.WebClient).DownloadFile('https://www.python.org/ftp/python/3.6.2/python-3.6.2.exe', 'C:/Tools/python-3.6.2.exe'); & c:\Tools\python-3.6.2.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0 TargetDir=c:\Tools\Python362; [Environment]::SetEnvironmentVariable('PATH', ${env:path} + ';C:\Tools\Python362', 'Machine')"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10358 次 |
最近记录: |