从.bat启动与直接运行.ps1不一样



我正在尝试制作一个脚本,人们可以双击运行一组偶尔变化的命令。在linux中,我运行一个.sh,它获取另一个sh(我可以在需要时更改)并运行它。我正在为Windows寻找一个类似的解决方案。

我查看了PowerShell,但发现它需要从。bat运行以允许双击,所以现在我有以下内容:

foo.bat file:

@ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%bar.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";

调用bar.ps1:

Invoke-WebRequest https://dl.dropboxusercontent.com/u/xxx/bar2.ps1 -OutFile bar2.ps1

从PowerShell运行bar.ps1工作良好,下载bar2.ps1,但运行批处理文件没有,或者至少不是两个文件所在的目录(找不到它在任何地方,虽然我猜这可能是一个工作目录问题仍然?)。

您的批处理文件正在以更高的权限运行PowerShell脚本。这样做会将工作目录更改为C:Windowssystem32(出于安全原因),因此您很可能会在那里找到下载的文件。要获得与脚本相同目录下的输出文件,您可以像这样更改PowerShell脚本:

$dir = Split-Path $MyInvocation.MyCommand.Path -Parent
$filename = 'bar2.ps1'
$url = "https://dl.dropboxusercontent.com/u/xxx/$filename"
Invoke-WebRequest $url -OutFile "$dir/$filename"

话虽如此,为什么要运行一个具有更高权限的下载脚本呢?别这样。

最新更新