Bat 文件无法在没有硬编码目录的情况下启动 powershell 脚本

问题描述 投票:0回答:1

我的计划如下:

  1. 打开.bat文件
  2. 文件然后打开一个 PS 窗口,允许脚本执行并以管理员身份(!)
  3. 目录必须是可变的,才能在该文件夹中的任何 PC 上运行。
  4. 安装 Chocolatey 和 Winget 来安装应用程序。
  5. 必须没有用户输入。

我的 .ps1 文件名为

Start.ps1
,批处理文件名为
Start.bat

在当前的批量配置中,不会以管理员身份执行PS窗口,也不会允许脚本执行。

PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""C:\Users\user\Desktop\Install\StartNew.ps1""' -Verb RunAs}"

当目录为1:1时它确实有效,但在不同的机器上它不会开始安装chocolatey和winget。

powershell batch-file elevated-privileges
1个回答
0
投票
  • Start.bat
    Start.ps1
    文件放在同一目录中。

  • Start.bat
    中使用以下内容:

@echo off & setlocal

:: Determine the full path to the companion .ps1 file (Start.ps1)
:: based on the full path of this batch file (Start.bat)
set "PS1File=%~dpn0.ps1"

:: Now reference %PS1File% as part of the PowerShell command.
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -Verb RunAs PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File \"%PS1File%\"'"

注:

  • 您仍然会收到 UAC 提示,要求授权创建提升的进程(只有停用 UAC 才能避免这种情况,强烈建议不要这样做)。

  • 正如 Compo 所指出的,提升的进程会将

    C:\Windows\System32
    视为其工作目录;如果您的
    .ps1
    脚本需要不同的脚本(并且本身不会更改),则需要在调用脚本之前将嵌套
    -File
    切换到调用
    -Command
    的嵌套
    Set-Location
    调用。

    • 顺便说一句:如果您要调用
      pwsh.exe
      ,即 PowerShell(核心)CLI,则调用者的工作目录将被保留(即使您碰巧从 Windows PowerShell 调用 ;请参阅 this回答)。
  • 要完全停用执行策略,请使用

    -ExecutionPolicy Bypass
    而不是
    -ExecutionPolicy Unrestricted
    ,如上所示。 (这通常在实践中不会产生影响,但后者会提示输入从网络下载的脚本)。

  • 没有理由使用 "& { ... }" 来调用通过

    -Command
    (
    -c
    ) 参数传递到 PowerShell CLI 的代码 - 只需直接使用
    "..."
    ,如上面的代码所示。旧版本的
    CLI 文档
    错误地建议 & { ... } 是必需的,但这已得到纠正。
    
    

© www.soinside.com 2019 - 2024. All rights reserved.