- Объект FileSystemObject метод CopyFolder и BuildPath — Как скопировать папку
- Как скопировать папку вручную
- Как скопировать в папку
- Windows copy command syntax and examples
- Copy the contents of a file to another file
- Copy file to another directory
- Copy files with white space in name
- Copy multiple files
- Use of environment variables
- Use PowerShell to Copy Files and Folders to a New Location
- Using Copy-Item to copy files
- Easily copy multiple files by using Copy-Item
Объект FileSystemObject метод CopyFolder и BuildPath — Как скопировать папку
Всем привет, с вами автор блога scriptcoding.ru. В этой статье мы продолжим программировать, а точнее, изучать файловую систему Windows с помощью объекта FileSystemObject и его методов. Сегодня мы рассмотрим два метода, один из них показывает, как скопировать папку или структуру папок программным путем, а другой позволяет добавить к заданному пути дополнительное имя…
Прежде чем приступать к программированию, давайте посмотрим, как скопировать папку в ручном режиме:
Как скопировать папку вручную
Прежде всего, вам нужно открыть директорию или диск, в котором находится пака, которую надо скопировать. Нажимаем правой кнопкой мыши по папке, в появившемся контекстном меню выбираем пункт «Копировать«, нажимаем мышкой по данному пункту. Теперь нам надо открыть тот каталог или диск, в который надо скопировать структуру папок или просто папку. Щелкаем правой кнопкой мыши по пустой области и в появившемся меню выбираем пункт «Вставить«, нажимаем по данному пункту и всё, выбранная папка скопирована. Однако, можно скопировать таким же методом и несколько папок, просто выделяем нужные директории и по одному из них выбираем пункт «Копировать», а уже далее, как и в примере выше, вставляем выбранные документы в нужное место.
Стоит обратить внимание, что скопировать структуру папок проще всего через менеджер файлов, например, Total Commander, он хорош тем, что весь процесс копирования папок позволяет держать под контролем, и вы всегда сможете проверить, все ли данные скопированы. В случае с примером выше, вы можете просто использовать комбинации клавиш «Ctrl + C» и «Ctrl + V«, чтобы скопировать одну или несколько папок в нужное место. Также обратите внимание, что если вы скопируете папки в одно и то же место, то Windows автоматически добавит к их именам префикс , так как папок с одинаковыми именами в одном месте быть не может.
Хорошо, теперь наступило время заняться программированием и описанием методов объекта FileSystemObject:
BuildPath (path, name) – Метод позволяет добавить к заданному пути path новое имя name. Как это работает, мы рассмотрим ниже.
CopyFolder (source, destination [,overwrite]) – Собственно, то, что нам и надо, метод показывает как скопировать папку на диск или в другую директорию.
- source – Путь к папке, которую нужно скопировать, можно использовать подстановочные знаки «?» – любой один символ или «*» – любое количество символов. В случае использования подстановочных знаков, мы можем, как копировать папку в одном экземпляре, так и сразу несколько, это позволит не использовать в программном коде циклы.
- destination – Путь к директории, в которую нужно скопировать папку.
- overwrite – Если параметр установлен в логическое значение true – будет происходить замена, false – не производить замены (по умолчанию).
И так, с теорией разобрались, теперь настало время приступить к программированию. Давайте сделаем так, я сначала приведу программный код на языке VBScript, дам пояснения к программному коду, и мы продолжим двигаться дальше.
Теперь давайте рассмотрим, как работает данный программный код:
Сначала создается новая папка «Новый каталог_vbs» в текущей директории, далее идет цикл for, в котором есть 9 итераций, то есть, в текущей директории будет создаваться 9 папок с шаблонным названием.
- fso.CopyFolder cur_dir & «\?_папка», fso.BuildPath(cur_dir, «Новый каталог_vbs»), true – тут мы используем метод CopyFolder для копирования папок, мы задали шаблон «\?_папка», то есть первый символ может быть любым, далее идёт знак подчеркивания, и слово «папка». В качестве пути, куда мы будем производить копирование папок Windows, мы указали fso.BuildPath(cur_dir, «Новый каталог_vbs»), перед этим я указал альтернативный вариант указания пути, без использования метода BuildPath.
Как скопировать в папку
Сам метод показывает, как копировать папку с заменой и без замены. Кроме того, он копирует не только сами папки, но и все файлы, которые в них находятся, то есть, нам не надо использовать метод CopyFile объекта FileSystemObject. Также стоит обратить внимание, что метод CreateFolder, который нам нужен, что бы предварительно создать директории, вернёт ошибку, если такие директории уже есть – проблема решается включением обработчика ошибок языка vbscript.
Хорошо, продолжим программировать, и теперь напишем программный код для сценария на языке jscript:
Данный пример альтернативен предыдущему с некоторыми изменениями, он также показывает, как скопировать папку на диск. Имена девяти новых папок будут начинаться с чисел от 10 до 19, это сделано, чтобы не создавать конфликт при создании каталогов, если вы перед этим запускали программный сценарий на языке vbscript. В конечном итоге, оба сценария будут производить копирование 9 папок в одну заданную директорию.
Стоит обратить внимание на одну особенность файловой системы Windows – общий путь не должен превышать 256 символов, начиная с корневого диска. Например, если путь к файлу вместе с его именем составляет 255 символов, а потом вы увеличите длину имени той директории, которая находится на уровень или несколько уровней выше, то уже не сможете получить доступ к конечной точке, так как общая длина будет превышать 256 символов.
Спасибо за внимание. Автор блога Владимир Баталий
Windows copy command syntax and examples
Using copy command, we can copy files from one directory to another directory. This command is similar to the Linux cp command, but it does not match with the full functionality of cp. Windows copy command can be used to copy files only, we can’t copy directories.
The syntax and usecases of copy command are explained below with examples.
Copy the contents of a file to another file
Example: To copy a file from c:\data\file1.doc to D:\backup\file2.doc
If the destination file already exists you will be prompted for confirmation. To suppress this confirmation you can use /Y switch with copy command. This would be useful if you are executing copy command from a batch file.
If the destination file exists, the above command will overwrite the same without asking the user for confirmation.
Copy file to another directory
When we specify a directory path as the destination, the files will be copied with the same name. We can assign a different name by specifying the new name in the destination path. Example is shown below.
To copy the file 1.doc loated at c:\data\documents to the directory c:\data\newdocs
Copy files with white space in name
If the file name has white space within it, we can wrap up the name in double quotes.
Example: To copy file, my resume.doc to another folder
Copy multiple files
We can’t specify multiple file names in copy command. However, we can use wildcards to identify a group of files and then copy all of them in a single command.
For example, to copy all excel files from current folder to another folder F:\backup
To copy all files in current folder to another folder
Use of environment variables
We can use environment variables in the copy command to specify the path of the folders. Like USERPROFILE, SystemRoot, ProgramFiles, TEMP, WINDIR, APPDATA, HOMEPATH.
For example, to copy a file to a user’s documents folder
The above command copies the file to the My Documents folder of the current logged in user.
You may also want to read
Windows «copy» is funny. Type «copy 1 2» and the file «1» will be copied into a new file «2». Now separate them by a plus sign instead of a space (copy 1+2) and you’ll concatenate 1 and 2 and replace the old file «1» with the result of the concatenation!
Yes, we can concatenate two or more files using copy command. You need to separate the list of files using +. You can redirect the resultant data to a new file also.
The above command will not alter the file 1. It creates a new file 3 with the concatenated data of 1 & 2. If no file name is provided it stores the result in the first file.
My Win7 cannot find a copy command, and when i run xcopy, a window flashes and exits.
I have the same problem. If you solved it, could you please explain how?
If you can not find your copy.exe file, you can download it to your windows directory or C:\ Directory depending the setting on your OS you should also be able to copy and run it from system32 or system folder.
how can i combine 2 .exe files and be able to use both after concatenation
I want to copy 2 different files(.exe,.config) from source to destination server of windows.
can you please help me on this command.
Hello i have a problem with my cmd windows 7.when i try to copy a command. Like help > file.pdf. i mean in extension pdf because i have this problem only with .pdf extension but not with .txt.So whe i execute the command. No problem. Then when i go to open the file.pdf ftom user destination the file.pdf doesn’t open say that is corrupted.please do help me .thanks
i have a file contain many lines as sources and another file has the same numbre of lines as destinations. i want to copy first line as source( c:/test/*.txt) to first line in destination ( d:/test2/), secend line ( c:/test/*.pdf) to second line in destination ( E:/test3/)……
Can I use the DOS/Windows “COPY” command in a BAT file to copy a file or a short string of text to computer memory and then paste (Ctrl +V) that string or file into a document?
Use PowerShell to Copy Files and Folders to a New Location
April 19th, 2013
Summary : The Scripting Wife learns about using Windows PowerShell to copy files and folders in prep for the 2013 Scripting Games.
The days seem to start early, and the evening arrives later this time of year in Charlotte, North Carolina. I am sitting on the lanai drinking a cup of English Breakfast tea, and checking my email with my Microsoft Surface RT device. In my mind, it is a perfect way to ease in to the day, and my Surface is great for stuff like checking email and sending tweets.
I hear a sort of a thump, thump, thump, rattle, rattle, rattle sound and I look up. Strangely enough, I see nothing, so I go back to reading my email. But the sound persists. I get up from my swing and go into the house. I see the source of the noise: the Scripting Wife is digging through the front closet, and she has boxes, books, and other assorted paraphernalia spread out over the vestibule floor. In situations like this, I have learned to keep my mouth shut, and to wait for a natural opening.
“I can’t find the flippin’ book,” the Scripting Wife exclaimed without looking up.
Not sure if this is a question, a remark, or even if it was directed at me, I decide to keep quiet.
“Well are you going to help?” she asked as she stood up.
“How can I help you, my peach?” I implored.
“You can help me find my autographed copy of Don’s book.”
I wait, knowing there is more to come.
“I saw your blog post about the upcoming 2013 Scripting Games, and I need to get back into shape by writing some code,” she stated.
“You are sort of like a scripting butterfly. You go here and there in random directions looking for nectar, but you never light for very long,” I paused to catch my breath.
“But I don’t need to know how to write scripts when I have my very own script monkey. Besides I just do this for fun,” she said.
“Well, I have no idea where you put your book, but I can help you for a few minutes if you wish,” I offered.
“I saw you reading your email, and I did not want to disturb you,” she said.
“Then why all the noise?” I asked.
“Maybe I figured if you came in here, then you were no longer reading your email and I could get you to help,” she posited.
“So what do you need to do?” I asked.
“Tell me about copying files. I have a bunch of pictures on my laptop that I want to copy up to the SAN so they do not get lost,” she said.
“Grab your laptop and come out to the lanai,” I instructed.
Using Copy-Item to copy files
“To copy a file from one folder to another, what cmdlet do you think you might use?” I asked.
“Copy-File,” she posited.
“Close. It is called Copy-Item,” I said.
“Oh, yeah. Now I remember,” she said.
“Open your Windows PowerShell console, and use Copy-Item to copy any file from your C:\fso folder to your C:\fsox folder,” I said.
She thought for about a second and typed the following until she had a file selected:
Next she typed the following:
The completed command is shown here:
Copy-Item -Path C:\fso\20110314.log -Destination c:\fsox\mylog.log
When she pressed ENTER, an error arose. The command and the error message are shown in the following image.
“Well, that did not work,” she said, “I guess I do need to go find Don’s book after all.”
“No, I wanted to show you what happens if the destination folder does not exist,” I said.
“How can I avoid that problem?”
“You can use the Test-Path cmdlet. Type Test-Path and supply the path to the folder,” I said.
She typed the following into the Windows PowerShell console:
The command is shown here:
The command and the output from the command are shown in the image that follows.
“So the command says False. I guess that means the folder does not exist?” she asked.
“Yep. That is right. Now use the MD command and give it a path so that you create the new C:\fsox folder,” I said.
She typed the following:
The command is shown here.
The command and the output from the command are shown in the image that follows.
“Now use the Up arrow and retrieve your previous Copy-Item command,” I said.
The Scripting Wife pressed the Up arrow a few times until the following command appeared:
Copy-Item -Path C:\fso\20110314.log -Destination c:\fsox\mylog.log
When the command appeared in the Windows PowerShell console window, she pressed ENTER to run the command. Nothing came back.
Easily copy multiple files by using Copy-Item
“That is OK, but I specifically want to copy my pictures, and I do not want to type a bunch of names. So how can I make Windows PowerShell copy my pictures for me?” she asked.
“To do that, use the Filter parameter and specify .jpg, which is the extension you use for your pictures. You will also need to specify the Recurse parameter,” I said.
She typed the following:
Copy-i -p c:\fso -fi *.jpg -d c:\fsox -r
The command is shown here:
Copy-Item -Path C:\fso -Filter *.jpg -Destination c:\fsox –Recurse
The newly copied files are shown in the following image.
“Cool,” she said as she bounded through the front door.
Scripting Games Prep Week will continue tomorrow when I will talk about Windows Management Instrumentation and obtaining basic computer information.
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy