首页 > 解决方案 > 使用 PowerShell 使用 .bat 文件在 Windows 上安装 Chrome

问题描述

我四处寻找,发现了一些提示,但缺少一些细节。这是我所拥有的:

安装-chrome.bat

PowerShell -NoProfile -Command "&{Start-Process PowerShell -ArgumentList '-NoProfile -File install-chrome.ps1' -Verb RunAs}"

安装-chrome.ps1

$client = New-Object System.Net.WebClient;
$client.DownloadFile("https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe", ".\ChromeStandaloneSetup64.exe");

.\ChromeStandaloneSetup64.exe /silent /install ;

有两件事没有按预期工作:

  1. 即使我发现的帖子表明上面应该以管理员模式启动 PowerShell,我仍然会收到 UAC 弹出窗口。
  2. 我期待.\将下载到脚本所在.exe的目录。.ps1.bat

关于如何解决这个问题的任何提示?

编辑:感谢@TheIncorrigible1 的回复,我设法解决了第二部分。当我直接在 PowerShell 中执行它们时,这两个选项或多或少都有效(它会下载它,但安装会在本地引发错误):

< V3

$PSScriptRoot = Split-Path -Parent -Path $script:MyInvocation.MyCommand.Path
$uri = "https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe"
$path = "$PSScriptRoot\ChromeStandaloneSetup64.exe" 

$client = New-Object System.Net.WebClient
$client.DownloadFile($uri, $path)
& $path /install

V3+

$uri = "https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe"
$path = "$PSScriptRoot\ChromeStandaloneSetup64.exe" 
Invoke-WebRequest -Uri $uri -OutFile $path
& $path /install

但是批处理仍然抛出错误:

At line:1 char:62
+ ... tart-Process PowerShell -Verb RunAs -ArgumentList -NoProfile, -File,  ...
+                                                                 ~
Missing argument in parameter list.
At line:1 char:69
+ ... ocess PowerShell -Verb RunAs -ArgumentList -NoProfile, -File, 'C:\Pro ...
+                                                                 ~
Missing argument in parameter list.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingArgument

标签: powershellbatch-file

解决方案


两件事情-

您不需要将批处理命令包装到脚本块中的 powershell 并-ArgumentList需要一个字符串参数数组:

powershell.exe -NoProfile -Command "Start-Process -FilePath powershell.exe -ArgumentList @('-NoProfile', '-File', '%~dp0install-chrome.ps1') -Verb RunAs"

有一个自动变量 ,$PSScriptRoot来确定你的根目录在哪里:

$uri = 'https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe'
if (-not $PSScriptRoot) {
    $PSScriptRoot = Split-Path -Parent -Path $script:MyInvocation.MyCommand.Definition
}
$outFile = "$PSScriptRoot\ChromeStandaloneSetup64.exe"

if ($PSVersionTable.PSVersion.Major -lt 3) {
    (New-Object -TypeName System.Net.WebClient).DownloadFile($uri, $outFile)
}
else {
    Invoke-WebRequest -Uri $uri -OutFile $outFile
}

& $outFile /silent /install

推荐阅读