相关疑难解决方法(0)

如何使用正确的工作目录从 BAT 文件启动 PowerShell 脚本?

我正在尝试创建 bat 脚本,该脚本可以在正确的工作目录中启动与 bat 文件名称相同的 PowerShell 脚本。

这是我得到的:

@ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -WorkingDirectory '%~dp0' -Verb RunAs}"
PAUSE
Run Code Online (Sandbox Code Playgroud)

以这种方式传递工作目录不起作用。

如何制作将传递正确工作目录和命令行参数的脚本?

windows powershell cmd batch-file

6
推荐指数
2
解决办法
1万
查看次数

如何在保留当前工作目录并维护传递给脚本的所有参数的同时提升 Powershell?

function Test-IsAdministrator
{
    $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
    $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Test-IsUacEnabled
{
    (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}

if (!(Test-IsAdministrator))
{
    if (Test-IsUacEnabled)
    {
        [string[]]$argList = @('-NoProfile', '-NoExit', '-File', $MyInvocation.MyCommand.Path)
        $argList += $MyInvocation.BoundParameters.GetEnumerator() | ForEach-Object {"-$($_.Key)", "$($_.Value)"}
        $argList += $MyInvocation.UnboundArguments
        Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList 
        return
    }
    else
    {
        throw "You must be an administrator to run this script."
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我运行上面的脚本,它会成功生成另一个具有提升权限的 PowerShell 实例,但当前工作目录会丢失并自动设置为C:\Windows\System32. 绑定参数也会丢失或错误解析。

在阅读类似的问题后,我了解到,当将 Start-Process 与 -Verb RunAs 一起使用时,仅当目标可执行文件是 …

powershell admin elevation

3
推荐指数
1
解决办法
4355
查看次数

标签 统计

powershell ×2

admin ×1

batch-file ×1

cmd ×1

elevation ×1

windows ×1