首页 > 解决方案 > 从路径中删除当前工作目录

问题描述

我在 Windows 中工作,想知道是否有办法从路径中删除当前工作目录?我知道这是 PowerShell 中的默认行为,但我需要它在批处理或 Windows 命令行中工作。

在 UNIX 中,我只需要确保我的$PATH变量不包含.. 有没有办法批量完成这个?这是当前的行为:

H:\tmp>dir
 Volume in drive H has no label.
 Volume Serial Number is E29C-7B61

 Directory of H:\tmp

04/27/2018  10:39 AM    <DIR>          .
04/27/2018  10:39 AM    <DIR>          ..
04/27/2018  10:40 AM                37 dwk.bat
               1 File(s)             37 bytes
               2 Dir(s)  987,995,770,880 bytes free

H:\tmp>dwk.bat
dwk.bat has been run.

H:\tmp>

这是期望的行为:

H:\tmp>dwk.bat
'dwk.bat' is not recognized as an internal or external command,
operable program or batch file.

H:\tmp>.\dwk.bat
dwk.bat has been run.

H:\tmp>

谢谢。

标签: batch-filepathworking-directory

解决方案


我建议首先阅读有关 Stack Overflow 问题的答案:

非常感谢 eryksun ,因为如果没有对上述参考答案的评论,这个答案就不会存在。

接下来我推荐阅读微软开发者网络(MSDN)的文章:

这个问题可以这样回答:是的,桌面应用程序和批处理文件可以在

  • Windows Vista 和所有更高版本的 Windows 客户端和
  • Windows Server 2003 和所有更高版本的 Windows Server。

NoDefaultCurrentDirectoryInExePath必须使用任何值定义具有名称的环境变量,以防止执行存储在当前目录中的脚本(.bat、.cmd、.vbs、...)或应用程序(.com、.exe),而无需.\根据需要显式使用在 Unix/Linux 上。

可以将环境变量NoDefaultCurrentDirectoryInExePath定义为系统变量,以关闭在当前目录中搜索此机器上所有帐户的脚本或应用程序。但这肯定不是一个好主意,因为它肯定会导致包括安装程序和卸载程序在内的许多应用程序无法正常工作。

环境变量NoDefaultCurrentDirectoryInExePath可以定义为用户变量,以关闭在当前目录中搜索脚本或应用程序以查找使用此帐户的进程。但这肯定也不是什么好主意。

但是在某些用例中将环境变量设置NoDefaultCurrentDirectoryInExePath局部变量以关闭在当前目录中搜索脚本或应用程序而不显式使用具有内核函数的.\Windows 版本在搜索脚本文件或应用程序之前调用不包含文件名字符串中的反斜杠(或正斜杠)。NeedCurrentDirectoryForExePathcmd.exe\/

例子:

@echo off
pushd "%TEMP%"
set "NoDefaultCurrentDirectoryInExePath=0"

echo @echo %%0 executed successfully.>Test1.bat

echo Calling Test1.bat ...
call Test1.bat

echo Calling .\Test1.bat ...
call .\Test1.bat

echo Starting Test1.bat ...
start /wait Test1.bat ^& timeout 5

set "NoDefaultCurrentDirectoryInExePath="

echo Calling again Test1.bat ...
call Test1.bat

del Test1.bat
popd
pause

从命令提示符窗口中执行的此批处理文件会导致当前控制台窗口的输出:

Calling Test1.bat ...
'Test1.bat' is not recognized as an internal or external command,
operable program or batch file.
Calling .\Test1.bat ...
.\Test1.bat executed successfully.
Starting Test1.bat ...
Calling again Test1.bat ...
Test1.bat executed successfully.
Press any key to continue . . . 

在执行此批处理文件期间,将打开第二个控制台窗口并输出:

"%TEMP%\Test1.bat" executed successfully.

第二个控制台窗口在 5 秒后自动关闭。

在将临时文件的目录设置为当前目录并在堆栈上推送当前目录路径后,NoDefaultCurrentDirectoryInExePath使用值定义环境变量。0变量值无关紧要,因为评估的只是环境变量的存在而不是它的值。

接下来,Test1.bat在临时文件的目录中创建另一个具有名称的批处理文件,该文件通常对当前用户没有写保护,因为这会导致很多麻烦。

由于环境变量是在本地环境中定义的,所以第一种Test1.bat没有任何路径的调用方法会失败。NoDefaultCurrentDirectoryInExePath

尽管存在环境变量,但第二次调用Test1.batwith relative path是成功的。.\

该批处理文件证明了命令START忽略。NoDefaultCurrentDirectoryInExePath

然后删除环境变量NoDefaultCurrentDirectoryInExePath以恢复原始 Windows 行为。

第二种Test1.bat不带任何路径的调用方法现在成功了。

最后Test1.bat删除创建的并将初始当前目录恢复为当前目录。

当然不可能阻止不是脚本文件或可执行文件的命令DIR的执行。它是cmd.exeWindows 命令处理器的内部命令,分别是powershell.exeWindows PowerShell 的内部命令。


推荐阅读