Windows批处理:在不缩短的情况下获取路径 [英] Windows Batch: getting Path without Shortening
问题描述
我现在搜索了几个小时,却没有找到适合我的解决方案.
I searched now for several Hours and didnt find any fitting solution for me.
当我尝试获取批处理文件的当前路径时,通常使用%〜dp0. 这将导致以下路径:D:\ VM \ TUTORI〜2 \ STARTS〜1.BAT
When I try to get the current Path of the Batch File, I use normaly %~dp0. This will leads in Paths like: D:\VM\TUTORI~2\STARTS~1.BAT
但是,如果仅执行文件管理,这不是问题,但是我想使用脚本来调用Vagrant命令. 碰巧流浪者系统不喜欢这种缩短的路径. 一旦路径足够短或当我直接从CMD调用它时,它就可以正常工作.
However this is not an issue, if only doing File Management, but I want to use the Script to call Vagrant commands. It happens that the Vagrant System doesnt like this shortened Paths. As soon as the Path is short enough or when I call it from the CMD directly, it works just fine.
我现在正在寻找一种方法,以获取到我的工作目录的所有未缩短的路径. 但是到目前为止我所做的一切都没有奏效,谷歌只为我提供了人们如何缩短他们的道路的方法. 这个问题有切实可行的解决方案吗?
I'm now searching for a way to get any unshortened Path to my working Directory. But whatever I tried so far didnt work and google only delivers me how people Shorten their Paths. Is there a practical Solution to this Problem?
我想在脚本中设置一个变量,如下所示: D:\ VM \ tutorialtest
I want to set a Variable in my Script looking like this: D:\VM\tutorialtest
根据接受的答案,对我来说,有效的代码段是2. For循环中没有"-2"的代码段.无论文件夹位于何处,这都将为我提供路径.
According to the Accepted Answer the working snippet for me is the Snippet without the "-2" on the 2. For Loop. This will give me the Path no matter where the folder is.
setlocal EnableDelayedExpansion
set myPath=%~DP0
set myPath=%myPath:*\=%
set fullPath=
pushd \
for %%a in ("%myPath:\=" "%") do (
set thisDir=%%~a
for /D %%d in ("!thisDir:~0!*") do (
set fullPath=!fullPath!\%%d
cd %%d
)
)
popd
echo Full path: %~D0%fullPath%
结果:
D:\VM\tutorialtest
推荐答案
尝试一下:
@echo off
setlocal EnableDelayedExpansion
set "myPath=%~DP0"
set "myPath=%myPath:*\=%"
set "fullPath="
pushd \
for %%a in ("%myPath:\=" "%") do (
set "thisDir=%%~a"
for /D %%d in ("!thisDir:~0,-2!*") do (
set "fullPath=!fullPath!\%%d"
cd "%%d"
)
)
popd
echo Full path: %~D0%fullPath%
请发布结果.
编辑:错误修复
问题在于,少于2个字符的名称会被剪切掉! (我的错误).
The problem is that names that have less than 2 characters are cutted! (my mistake).
我做了一些测试,看来for /D %%d in ("TUTORI~2*") ...
也返回了文件夹的全名,所以thisDir变量不是必需的.您可以这样修改for %%a
循环并获得相同的结果:
I did some testing and it seems that for /D %%d in ("TUTORI~2*") ...
also returns the full name of the folder, so thisDir variable is not required. You may modify the for %%a
loop this way and get the same result:
for %%a in ("%myPath:\=" "%") do (
for /D %%d in ("%%~a*") do (
set fullPath=!fullPath!\%%d
cd %%d
)
)
这篇关于Windows批处理:在不缩短的情况下获取路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!