Xcopy ошибка интерпретации параметров

Issuing:

xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y

works as expected. However:

xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:"Y:...exclude.txt"

returns error:

Invalid number of parameters

Which also occurs when path names (containing spaces) are not enclosed by quotation marks. This however, is not the case. Paths (edited for readability) all correspond correctly. Syntax (as per Product Documentation — Xcopy) is also correct. Concerning OS is Windows XP Professional x32 SP3.

Why is second cmd returning error and how is it to be solved? I am not looking for alternatives to xcopy (robocopy etc.).

Ross Ridge's user avatar

Ross Ridge

37.7k7 gold badges79 silver badges111 bronze badges

asked Jun 4, 2015 at 18:47

user4157124's user avatar

user4157124user4157124

2,72013 gold badges26 silver badges42 bronze badges

XCOPY is an old command harking back to the days of DOS. It looks like the /EXCLUDE option was never updated to support long file names. Ugh :-(

If you remove the quotes, then the text after the space is interpreted as an additional parameter, and you get the «Invalid number of parameters» error. If you keep the quotes, then it treats the quotes as part of the path, and reports it cannot find the file.

I believe you have three possible solutions:

1) Use the short 8.3 folder names in your path.

Of course this cannot work if your volume has short names disabled.

2) Use the SUBST command to create a drive alias for your troublesome path.

subst Q: "Y:path with spaces"
xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:Q:exclude.txt
subst Q: /d

This could be a problem if you don’t know a drive letter that is free.

3) (my favorite) Simply PUSHD do the troublesome path and run the command from there :-)

pushd "Y:path with spaces"
xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:exclude.txt
popd

answered Jun 4, 2015 at 19:52

dbenham's user avatar

/EXCLUDE:file switch will not exclude the file specified. As per xcopy command reference:

/exclude:FileName1[+[FileName2][+[FileName3](…)] Specifies a list of
files. At least one file must be specified.
Each file will contain search strings with each string on a separate line in the file. When any of the strings match any part of the
absolute path of the file to be copied, that file will be excluded
from being copied.

answered Jun 4, 2015 at 19:22

JosefZ's user avatar

JosefZJosefZ

27.2k5 gold badges45 silver badges80 bronze badges

1

It took me some time to get this right as well (I had the same errors), but ultimately, this format worked for me. As with all things DOS, absolute precision is critical, so feel free to copy and paste the below.

xcopy /t /e "C:UsersusernameYour Folder" "C:UsersuserYour Folder"

Fedor's user avatar

Fedor

15k5 gold badges38 silver badges114 bronze badges

answered Jan 6 at 17:54

DAKNYC's user avatar

Я пытаюсь скопировать файлы из E: / bin / Debug / в E: / New с помощью xcopy. Мой синтаксис

xcopy /s "E:binDebug*.*E:New"

На окнах 10.

Он возвращается

ошибка неверный номер параметра

Или иногда

Новый не найден неверный путь

. Пожалуйста, помогите мне найти мою ошибку. Что я делаю неправильно?

1 ответ

Лучший ответ

Вам нужен пробел между аргументами, и каждый параметр должен быть в кавычках *.

E:> xcopy /s /i "E:binDebug*.*" "E:New"
E:binDebugTestInnerDirFileA.txt
E:binDebugTestInnerDirFileB.txt
2 files copied

По умолчанию xcopy не создает целевой каталог, если он не существует. Используйте опцию /i, если вы этого хотите. Документацию xcopy можно найти здесь.

/ i:
Если источник — это каталог или содержит символы подстановки, а пункт назначения не существует, xcopy предполагает, что пункт назначения указывает имя каталога и создает новый каталог. Затем xcopy копирует все указанные файлы в новый каталог. По умолчанию xcopy предлагает указать, является ли пункт назначения файлом или каталогом.

В качестве альтернативы вы можете использовать mkdir для создания ‘E: New ‘

Quotemarks *: требуется только в том случае, если ваши аргументы содержат пробелы, такие как имена каталогов, такие как Program Files, в которых есть пробелы. Но всегда включать их в список — хорошая идея.


4

FalcoGer
8 Апр 2019 в 09:45

Вопрос:

выдавший:

xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y

работает как ожидалось. Однако:

xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:"Y:...exclude.txt"

возвращает ошибку:

Недопустимое количество параметров

Что также происходит, когда имена путей (содержащие пробелы) не заключены в кавычки. Однако это не так. Пути (отредактированные для удобочитаемости) все правильно соответствуют. Синтаксис (согласно Документация по продукту – Xcopy) также верен. В отношении ОС – Windows XP Professional x32 SP3.

Почему вторая CMD возвращает ошибку и как ее решить? Я не ищу альтернативы xcopy (robocopy и т.д.).

Лучший ответ:

XCOPY – это старая команда, возвращающаяся к дням DOS. Похоже, опция /EXCLUDE никогда не обновлялась для поддержки длинных имен файлов. Ugh: – (

Если вы удаляете кавычки, текст после пробела интерпретируется как дополнительный параметр, и вы получаете ошибку “Недопустимое количество параметров”. Если вы сохраняете кавычки, то он рассматривает кавычки как часть пути и сообщает, что не может найти файл.

Я считаю, что у вас есть три возможных решения:

1) Используйте короткие имена папок 8.3 в вашем пути.

Конечно, это не сработает, если ваш том имеет короткие имена.

2) Используйте команду SUBST, чтобы создать псевдоним диска для вашего трудного пути.

subst Q: "Y:path with spaces"
xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:Q:exclude.txt
subst Q: /d

Это может быть проблемой, если вы не знаете бесплатную букву диска.

3) (мой любимый) Просто PUSHD выполните неприятный путь и выполните команду оттуда: -)

pushd "Y:path with spaces"
xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:exclude.txt
popd

Подробнее см. https://sevenx7x.wordpress.com/2009/01/02/xcopy-with-exclude-option-shows-cant-read-file/ и http://forums.majorgeeks.com/showthread.php?t=54300.

Ответ №1

/EXCLUDE:file не исключает указанный файл. По xcopy ссылка на команду:

/exclude:FileName1[+[FileName2][+[FileName3](…)] Задает список файлы. Необходимо указать хотя бы один файл. Каждый файл будет содержать строки поиска с каждой строкой в ​​отдельной строке в файле. Когда какая-либо из строк соответствует любой части абсолютный путь к файлу, который будет скопирован, этот файл будет исключен от копирования.

при некоторых обстоятельствах xcopy вернет ошибку Invalid number of parameters не давая вам понятия о том, что происходит. Обычное решение для этого-убедиться, что ваши имена файлов заключены в кавычки, так как это может быть проблемой с пакетными файлами, где у вас есть что-то вроде xcopy %1 %2 и xcopy "%1" "%2". Недавно я столкнулся с проблемой, однако, где проблема была не в пробелах:

C:Tempfoo>c:/windows/system32/xcopy.exe /f /r /i /d /y * ..bar
Invalid number of parameters

источник

1 ответов

решение это было сложно: получается, что команда xcopy является разбор слеши в пути к собственному бинарных. Это прекрасно работает:

C:Tempfoo>c:windowssystem32xcopy.exe /f /r /i /d /y * ..bar
C:Tempfooblah -> C:Tempbarblah
1 File(s) copied

вы также можете столкнуться с этим, если у вас есть свой PATH определяется с использованием косой черты вместо обратной.

отвечен Slothman 2010-02-26 00:37:24

источник

Я искал ответ по всему Google, и хотя здесь, в SO, есть несколько тем, в которых обсуждается проблема, ни один из предоставленных ответов, похоже, не работает.

У меня есть следующий цикл для копирования каталогов с одного диска на другой:

for /F "tokens=2 delims==" %%z in ('set dirs[') do (
    xcopy "%%z*.*" "!outdrive!:!dir!%%~nxz" /C /S /D /Y /I
)

«dirs» — это массив, содержащий несколько (неизвестное количество) строк, обозначающих каталоги. Например, одним элементом может быть C:UsersownerDocuments, а другим — C:UsersownerPicturesfoo barTrip. «Outdrive» — это диск, на который xcopy копирует файлы, а «dir» — это просто папка, созданная до этого с помощью md с именем «backup xx-xx-xxxx», где x составляют текущую дату. В любом случае, когда я запускаю программу, я получаю сообщение об ошибке «Недопустимое количество параметров». Я вижу, как это было бы вызвано, если бы у меня не было кавычек вокруг каталогов, поскольку каталог, такой как C:UsersownerPicturesfoo barTrip, имеет пробел в одном из имен папок. Однако, поскольку у меня есть кавычки, окружающие каждый параметр, я не совсем уверен, что вызывает эту проблему. Я надеюсь, что кто-то может пролить свет на это.

Пакетный файл — это Windows .bat ОС — это Windows 8 x64. Отложенное расширение включено, следовательно, «!», хотя я не думаю, что мне даже нужно отложенное расширение для этого цикла.

РЕДАКТИРОВАТЬ
Изменив команду XCOPY на echo и увидев, как именно выглядит строка, я заметил, что «dir» заключен в кавычки, поэтому он обрабатывает его как еще один параметр. Я добавил строку:

set dir=!dir:"=!

и это сработало. Извините за такой глупый вопрос, я не знаю, как я пропустил это раньше.

Asked
4 years, 1 month ago

Viewed
10k times

I am trying to copy files from E:/bin/Debug/ to E:/New using xcopy. My syntax is

xcopy /s "E:binDebug*.*E:New"

on windows 10.

It returns

error invalid number of parameter

or sometimes

New not foundinvalid path

. Please help me to find my mistake. What am I doing wrong?

LocoGris's user avatar

LocoGris

4,4123 gold badges15 silver badges30 bronze badges

asked Apr 8, 2019 at 6:20

user310602's user avatar

You need a space between the arguments, and each parameter needs to be in quotes*.

E:> xcopy /s /i "E:binDebug*.*" "E:New"
E:binDebugTestInnerDirFileA.txt
E:binDebugTestInnerDirFileB.txt
2 files copied

By default xcopy does not create the target directory if it does not exist. Use the /i option if that is what you want. xcopy documentation can be found here.

/i:
If Source is a directory or contains wildcards and Destination does not exist, xcopy assumes Destination specifies a directory name and creates a new directory. Then, xcopy copies all specified files into the new directory. By default, xcopy prompts you to specify whether Destination is a file or a directory.

Alternatively you can use mkdir to create ‘E:New’

Quotemarks*: Only needed when your arguments contain spaces, such as Directory names like Program Files, which have spaces. But it’s a good idea to always include them.

answered Apr 8, 2019 at 6:23

FalcoGer's user avatar

FalcoGerFalcoGer

2,20811 silver badges33 bronze badges

3

Under some circumstances, xcopy will return the error Invalid number of parameters without giving you a clue as to what’s going on. The usual solution for this is to be sure that your filenames are enclosed in quotes, as this can be an issue with batch files where you have something like xcopy %1 %2 and you really need xcopy "%1" "%2". I recently ran into a problem, however, where the problem wasn’t spaces:

C:Tempfoo>c:/windows/system32/xcopy.exe /f /r /i /d /y * ..bar
Invalid number of parameters

asked Feb 26, 2010 at 0:36

Slothman's user avatar

The solution to this one was tricky: it turns out that xcopy is parsing the forward slashes in the path to its own binary. This works fine:

C:Tempfoo>c:windowssystem32xcopy.exe /f /r /i /d /y * ..bar
C:Tempfooblah -> C:Tempbarblah
1 File(s) copied

You can also run into this if you have your PATH defined using forward slashes instead of backslashes.

answered Feb 26, 2010 at 0:37

Slothman's user avatar

SlothmanSlothman

3511 gold badge2 silver badges9 bronze badges

2

My discovery was that I needed double forward slashes on options

c:windowssystem32xcopy.exe //f //r //i //d //y * "..bar"

answered Oct 8, 2019 at 7:51

Kenneth Hov's user avatar

Issuing:

xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y

works as expected. However:

xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:"Y:...exclude.txt"

returns error:

Invalid number of parameters

Which also occurs when path names (containing spaces) are not enclosed by quotation marks. This however, is not the case. Paths (edited for readability) all correspond correctly. Syntax (as per Product Documentation — Xcopy) is also correct. Concerning OS is Windows XP Professional x32 SP3.

Why is second cmd returning error and how is it to be solved? I am not looking for alternatives to xcopy (robocopy etc.).

Ross Ridge's user avatar

Ross Ridge

38.2k7 gold badges80 silver badges111 bronze badges

asked Jun 4, 2015 at 18:47

user4157124's user avatar

user4157124user4157124

2,75113 gold badges26 silver badges42 bronze badges

XCOPY is an old command harking back to the days of DOS. It looks like the /EXCLUDE option was never updated to support long file names. Ugh :-(

If you remove the quotes, then the text after the space is interpreted as an additional parameter, and you get the «Invalid number of parameters» error. If you keep the quotes, then it treats the quotes as part of the path, and reports it cannot find the file.

I believe you have three possible solutions:

1) Use the short 8.3 folder names in your path.

Of course this cannot work if your volume has short names disabled.

2) Use the SUBST command to create a drive alias for your troublesome path.

subst Q: "Y:path with spaces"
xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:Q:exclude.txt
subst Q: /d

This could be a problem if you don’t know a drive letter that is free.

3) (my favorite) Simply PUSHD do the troublesome path and run the command from there :-)

pushd "Y:path with spaces"
xcopy X: "Y:...bin9876543210" /c /g /d /i /e /r /h /y /exclude:exclude.txt
popd

answered Jun 4, 2015 at 19:52

dbenham's user avatar

/EXCLUDE:file switch will not exclude the file specified. As per xcopy command reference:

/exclude:FileName1[+[FileName2][+[FileName3](…)] Specifies a list of
files. At least one file must be specified.
Each file will contain search strings with each string on a separate line in the file. When any of the strings match any part of the
absolute path of the file to be copied, that file will be excluded
from being copied.

answered Jun 4, 2015 at 19:22

JosefZ's user avatar

JosefZJosefZ

28k5 gold badges44 silver badges83 bronze badges

1

It took me some time to get this right as well (I had the same errors), but ultimately, this format worked for me. As with all things DOS, absolute precision is critical, so feel free to copy and paste the below.

xcopy /t /e "C:UsersusernameYour Folder" "C:UsersuserYour Folder"

Fedor's user avatar

Fedor

16.2k10 gold badges39 silver badges125 bronze badges

answered Jan 6 at 17:54

DAKNYC's user avatar

fandorin_official

Недопустимое число параметров?

Сделал batник для копирования файлов.

xcopy D:_База 1С 8.2_ D:DropboxApps1001 мелочь f/ i/ /y /s
TIMEOUT /T 100 /NOBREAK

В результате запуска получаем следующее:
5a052614f0a74782985442.png

Пути файлов заключал в кавычки. Не особо помогло.
Как можно исправить?


  • Вопрос задан

    более трёх лет назад

  • 4130 просмотров

Кодировку поправьте.
Не видите какой путь у вас на скриншоте?

И копировать базу 1с таким образом далеко не лучшая идея. Надо бы сначала теневую копию сделать, а уж с нее копировать куда надо.

Пригласить эксперта

Заменить
f/ i/
на
/f /i,
например

1. Все пути берутся в кавычки т.е.:
xcopy «D:_База 1С 8.2_» «D:DropboxApps1001 мелочь»

2. батник должен быть в кодировке 866


  • Показать ещё
    Загружается…

04 июн. 2023, в 16:13

2000 руб./за проект

04 июн. 2023, в 16:13

3000 руб./за проект

04 июн. 2023, в 16:06

2000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Xcomew exe ошибка 0xc000007b
  • Xcom ошибка при запуске приложения 0xc000007b
  • Xcom ошибка 0xc0000142
  • Xcom enemy within ошибка 0xc0000906

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии