首页 > 解决方案 > 为什么“移动”命令在我的批处理文件中不起作用?

问题描述

所以我正在尝试制作一个批处理文件来移动我选择的文件。但是“移动”命令不起作用,这就是我编码它的方式:

@echo off
title file mover
cls
goto filemover

:filemover
cls
echo Please type what you want to put in the .txt file
set /p input=Type: 
echo %input% >> inputfile.txt
::And here i want it to move the file to the Desktop
move "inputfile.txt" Desktop
::but when i do that it just removes the txt file (inputfile.txt) and replaces it with "Desktop.File"

标签: batch-filecmd

解决方案


事实证明,问题的原因是Desktop用作命令MOVE的目标,该命令应引用用户的桌面目录,但在批处理文件执行时被解释为当前目录Desktop中子目录的名称,并且该目录确实存在于当前目录中或如果当前目录中没有子目录,则作为目标文件名。所以这个问题描述了一个XY 问题Desktop

真正的问题是:

如何在用户的桌面目录中创建或移动文件?

这是一个代码,它直接在用户的桌面目录中创建文件,独立于用户Desktopshell 文件夹的 Windows 默认设置:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "DesktopFolder="
for /F "skip=1 tokens=1,2*" %%I in ('%SystemRoot%\System32\reg.exe QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop 2^>nul') do if /I "%%I" == "Desktop" if not "%%~K" == "" if "%%J" == "REG_SZ" (set "DesktopFolder=%%~K") else if "%%J" == "REG_EXPAND_SZ" call set "DesktopFolder=%%~K"
if not defined DesktopFolder for /F "skip=1 tokens=1,2*" %%I in ('%SystemRoot%\System32\reg.exe QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v Desktop 2^>nul') do if /I "%%I" == "Desktop" if not "%%~K" == "" if "%%J" == "REG_SZ" (set "DesktopFolder=%%~K") else if "%%J" == "REG_EXPAND_SZ" call set "DesktopFolder=%%~K"
if not defined DesktopFolder set "DesktopFolder=\"
if "%DesktopFolder:~-1%" == "\" set "DesktopFolder=%DesktopFolder:~0,-1%"
if not defined DesktopFolder set "DesktopFolder=%UserProfile%\Desktop"

echo Please type what you want to put in the .txt file.
echo/
set UserInput=
set /P "UserInput=Type: "
setlocal EnableDelayedExpansion
echo(!UserInput!>"%Desktopfolder\inputfile.txt"
endlocal
endlocal

该文件inputfile.txt不是首先在当前目录中创建,然后在执行批处理文件时移动,因为当前目录可以为当前用户写保护。

请参阅如何在用户的桌面目录中创建目录的答案?为什么批处理代码完全使用这些命令行来确定哪个目录是用户的桌面目录,以便在 Windows XP 和所有较新的 Windows 上工作,即使在非常罕见的例外情况下也是如此。

要了解使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并仔细阅读每个命令显示的所有帮助页面。

  • call /?
  • echo /?
  • endlocal /?
  • for /?
  • if /?
  • reg /?
  • reg query /?
  • set /?
  • setlocal /?

也可以看看:


推荐阅读