Как скачать файл через командную строку windows

How can I download something from the web directly without Internet Explorer or Firefox opening Acrobat Reader/Quicktime/MS Word/whatever? I'm using Windows, so a Windows version of Wget wou...

If PowerShell is an option, that’s the preferred route, since you (potentially) won’t have to install anything extra:

(new-object System.Net.WebClient).DownloadFile('http://www.example.com/file.txt', 'C:tmpfile.txt')

Failing that, Wget for Windows, as others have pointed out is definitely the second best option. As posted in another answer it looks like you can download Wget all by itself, or you can grab it as a part of Cygwin or MSys.

If for some reason, you find yourself stuck in a time warp, using a machine that doesn’t have PowerShell and you have zero access to a working web browser (that is, Internet Explorer is the only browser on the system, and its settings are corrupt), and your file is on an FTP site (as opposed to HTTP):

start->run "FTP", press "OK".

If memory serves it’s been there since Windows 98, and I can confirm that it is still there in Windows 8 RTM (you might have to go into appwiz.cpl and add/remove features to get it). This utility can both download and upload files to/from FTP sites on the web. It can also be used in scripts to automate either operation.

This tool being built-in has been a real life saver for me in the past, especially in the days of ftp.cdrom.com — I downloaded Firefox that way once, on a completely broken machine that had only a dial-up Internet connection (back when sneakernet’s maximum packet size was still 1.44 MB, and Firefox was still called «Netscape» /me does trollface).

A couple of tips: it’s its own command processor, and it has its own syntax. Try typing «help». All FTP sites require a username and password; but if they allow «anonymous» users, the username is «anonymous» and the password is your email address (you can make one up if you don’t want to be tracked, but usually there is some kind of logic to make sure it’s a valid email address).

Without using any non-standard (Windows included) utilities, is it possible to download using the Windows command line?

The preferred version is Windows XP, but it’s also interesting to know for newer versions.

To further clarify my question:

  • It has to be using HTTP
  • The file needs to be saved
  • Standard clean Windows install, no extra tools

So basically, since everybody is screaming Wget, I want simple Wget functionality, without using Wget.

Peter Mortensen's user avatar

asked Oct 23, 2009 at 14:58

Robert Massa's user avatar

Robert MassaRobert Massa

1,6354 gold badges13 silver badges17 bronze badges

6

You can write a VBScript and run it from the command line

Create a file downloadfile.vbs and insert the following lines of code:

' Set your settings
    strFileURL = "http://www.it1.net/images/it1_logo2.jpg"
    strHDLocation = "c:logo.jpg"

' Fetch the file
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")

    objXMLHTTP.open "GET", strFileURL, false
    objXMLHTTP.send()

If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary

objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0    'Set the stream position to the start

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing

objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if

Set objXMLHTTP = Nothing

Run it from the command line as follows:

cscript.exe downloadfile.vbs 

phuclv's user avatar

phuclv

24.7k13 gold badges105 silver badges219 bronze badges

answered Oct 23, 2009 at 15:31

3

Starting with Windows 7, I believe there’s one single method that hasn’t been mentioned yet that’s easy:

Syntax:

bitsadmin  /transfer job_name       /download  /priority priority   URL  localpathfile

Example:

bitsadmin  /transfer mydownloadjob  /download  /priority normal  ^
                  http://example.com/filename.zip  C:UsersusernameDownloadsfilename.zip

(Broken into two separate lines with ^ for readability
(to avoid scrolling).)

Warning: As pointed out in the comments,
the bitsadmin help message starts by saying:

BITSAdmin is deprecated and is not guaranteed to be available in future versions of Windows.
Administrative tools for the BITS service are now provided by BITS PowerShell cmdlets.

… but another comment reported that it works on Windows 8.

G-Man Says 'Reinstate Monica''s user avatar

answered May 16, 2011 at 9:13

timeshift's user avatar

timeshifttimeshift

8696 silver badges3 bronze badges

14

PowerShell (included with Windows 8 and included with .NET for earlier releases) has this capability. The powershell command allows running arbitrary PowerShell commands from the command line or a .bat file. Thus, the following line is what’s wanted:

powershell -command "& { (New-Object Net.WebClient).DownloadFile('http://example.com/', 'c:somefile') }"

Peter Mortensen's user avatar

answered May 29, 2014 at 2:22

Nik's user avatar

NikNik

2693 silver badges2 bronze badges

4

I found a way of doing it, but really, just install Wget.

You can use Internet Explorer from a command line (iexplore.exe) and then enter a URL as an argument. So, run:

iexplore.exe http://blah.com/filename.zip

Whatever the file is, you’ll need to specify it doesn’t need confirmation ahead of time. Lo and behold, it will automatically perform the download. So yes, it is technically possible, but good lord do it in a different way.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:12

DHayes's user avatar

DHayesDHayes

2,17313 silver badges17 bronze badges

2

Windows Explorer (not to be confused with Internet Explorer) can download files via HTTP. Just enter the URL into the Address bar. Or from the command line, for example, C:windowsexplorer.exe http://somewhere.com/filename.ext.

You get the classic File Download prompt. Unless the file is a type that Windows Explorer knows how to display inline, (.html, .jpg, .gif), in which case you would then need to right-click to save it.

I just tested this on my VMware image of a virgin install of Windows XP 2002 SP1, and it works fine.

Peter Mortensen's user avatar

answered Aug 8, 2011 at 15:18

Chris Noe's user avatar

Chris NoeChris Noe

3972 gold badges5 silver badges16 bronze badges

3

You can use (in a standard Windows bat):

powershell -command "& { iwr http://www.it1.net/it1_logo2.jpg -OutFile logo.jpg }"

It seems to require PowerShell v4…

(Thanks to that comment and this one)

a_horse_with_no_name's user avatar

answered May 10, 2016 at 14:10

Anthony O.'s user avatar

Anthony O.Anthony O.

2601 gold badge6 silver badges8 bronze badges

Use FTP.

From the command line:

ftp ftp.somesite.com
user
password

etc. FTP is included in every Windows version I can remember; probably not in 3.1, maybe not in Windows 95, but certainly everything after that.

@RM: It is going to be rough if you don’t want to download any other tools. There exists a command line Wget for Windows and Wget is designed to do exactly what you’re asking for.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:01

Satanicpuppy's user avatar

SatanicpuppySatanicpuppy

6,7371 gold badge21 silver badges17 bronze badges

4

Use PowerShell like this:

  1. Create a download.ps1 file:

    param($url, $filename)
    $client = new-object System.Net.WebClient 
    $client.DownloadFile( $url, $filename)
    
  2. Now you can download a file like this:

    powershell Set-ExecutionPolicy Unrestricted
    powershell -ExecutionPolicy RemoteSigned -File "download.ps1" "http://somewhere.com/filename.ext" "d:filename.ext"
    

answered Apr 21, 2013 at 21:55

Thomas Jespersen's user avatar

1

On Win CMD (if you have write access):

set url=https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg
set file=file.jpg
certutil -urlcache -split -f %url% %file%
echo Done.

Built in Windows app. No need for external downloads.

Tested on Win 10

answered Apr 25, 2020 at 17:58

Zimba's user avatar

ZimbaZimba

96310 silver badges14 bronze badges

If you have python installed here’s an example which fetches the get-pip.py from the web

python -c "import urllib; urllib.urlretrieve ('https://bootstrap.pypa.io/get-pip.py', r'C:python27Toolsget-pip.py')"

gronostaj's user avatar

gronostaj

54.8k17 gold badges118 silver badges174 bronze badges

answered Aug 29, 2014 at 23:15

Sipherlab's user avatar

0

From Windows 10 build 17063 and later, ‘Curl’ is now included, so that you can execute it directly from Cmd.exe or PowerShell.exe.

For example:

C:>curl.exe -V
curl 7.55.1 (Windows) libcurl/7.55.1 WinSSL
Release-Date: 2017-11-14, security patched: 2019-11-05
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL

To download a file:

curl.exe -O https://cdn.sstatic.net/Sites/superuser/Img/logo.svg

answered Sep 10, 2020 at 14:41

gsl's user avatar

gslgsl

2072 silver badges9 bronze badges

If you install Telnet, I imagine you could make a HTTP request to a server to download a file.

You can also install Cygwin, and use wget to download a file as well. This is a very easy way to download files from the command line.

answered Oct 23, 2009 at 15:01

EvilChookie's user avatar

EvilChookieEvilChookie

4,5691 gold badge24 silver badges34 bronze badges

10

There are a few ways that you can download using the command line in Windows:

  1. You can use Cygwin.

    Note: the included apps are not native Linux apps. You must rebuild your application from source if you want to run on Windows.

  2. Using telnet it’s possible to make a request but you won’t see any processing.

  3. You can write bat or VBS scripts.

  4. Write your own program that you can run from cmd.exe.

Gaff's user avatar

Gaff

18.3k15 gold badges56 silver badges68 bronze badges

answered Aug 20, 2011 at 3:22

Jesus's user avatar

JesusJesus

111 bronze badge

You can install the Linux application Wget on Windows. It can be downloaded from http://gnuwin32.sourceforge.net/packages/wget.htm. You can then issue the command ‘wget (inserturlhere)’ or any other URL in your command prompt, and it will allow you to download that URL/file/image.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:06

1

In default Windows, you can’t download via HTTP. Windows is a GUI-centric OS, so it lacks many of the commandline tools you’d find in other OS’s, like wget, which would be the prime candidate.

System.Net.WebClient.DownloadFile(), a function in the WiniNet API, can download files, but I’m not sure how far you’re getting into actual development vs. a batch file.

answered Oct 23, 2009 at 15:04

Andrew Scagnelli's user avatar

1

Without using any non-standard (Windows included) utilities, is it possible to download using the Windows command line?

The preferred version is Windows XP, but it’s also interesting to know for newer versions.

To further clarify my question:

  • It has to be using HTTP
  • The file needs to be saved
  • Standard clean Windows install, no extra tools

So basically, since everybody is screaming Wget, I want simple Wget functionality, without using Wget.

Peter Mortensen's user avatar

asked Oct 23, 2009 at 14:58

Robert Massa's user avatar

Robert MassaRobert Massa

1,6354 gold badges13 silver badges17 bronze badges

6

You can write a VBScript and run it from the command line

Create a file downloadfile.vbs and insert the following lines of code:

' Set your settings
    strFileURL = "http://www.it1.net/images/it1_logo2.jpg"
    strHDLocation = "c:logo.jpg"

' Fetch the file
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")

    objXMLHTTP.open "GET", strFileURL, false
    objXMLHTTP.send()

If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary

objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0    'Set the stream position to the start

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing

objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if

Set objXMLHTTP = Nothing

Run it from the command line as follows:

cscript.exe downloadfile.vbs 

phuclv's user avatar

phuclv

24.7k13 gold badges105 silver badges219 bronze badges

answered Oct 23, 2009 at 15:31

3

Starting with Windows 7, I believe there’s one single method that hasn’t been mentioned yet that’s easy:

Syntax:

bitsadmin  /transfer job_name       /download  /priority priority   URL  localpathfile

Example:

bitsadmin  /transfer mydownloadjob  /download  /priority normal  ^
                  http://example.com/filename.zip  C:UsersusernameDownloadsfilename.zip

(Broken into two separate lines with ^ for readability
(to avoid scrolling).)

Warning: As pointed out in the comments,
the bitsadmin help message starts by saying:

BITSAdmin is deprecated and is not guaranteed to be available in future versions of Windows.
Administrative tools for the BITS service are now provided by BITS PowerShell cmdlets.

… but another comment reported that it works on Windows 8.

G-Man Says 'Reinstate Monica''s user avatar

answered May 16, 2011 at 9:13

timeshift's user avatar

timeshifttimeshift

8696 silver badges3 bronze badges

14

PowerShell (included with Windows 8 and included with .NET for earlier releases) has this capability. The powershell command allows running arbitrary PowerShell commands from the command line or a .bat file. Thus, the following line is what’s wanted:

powershell -command "& { (New-Object Net.WebClient).DownloadFile('http://example.com/', 'c:somefile') }"

Peter Mortensen's user avatar

answered May 29, 2014 at 2:22

Nik's user avatar

NikNik

2693 silver badges2 bronze badges

4

I found a way of doing it, but really, just install Wget.

You can use Internet Explorer from a command line (iexplore.exe) and then enter a URL as an argument. So, run:

iexplore.exe http://blah.com/filename.zip

Whatever the file is, you’ll need to specify it doesn’t need confirmation ahead of time. Lo and behold, it will automatically perform the download. So yes, it is technically possible, but good lord do it in a different way.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:12

DHayes's user avatar

DHayesDHayes

2,17313 silver badges17 bronze badges

2

Windows Explorer (not to be confused with Internet Explorer) can download files via HTTP. Just enter the URL into the Address bar. Or from the command line, for example, C:windowsexplorer.exe http://somewhere.com/filename.ext.

You get the classic File Download prompt. Unless the file is a type that Windows Explorer knows how to display inline, (.html, .jpg, .gif), in which case you would then need to right-click to save it.

I just tested this on my VMware image of a virgin install of Windows XP 2002 SP1, and it works fine.

Peter Mortensen's user avatar

answered Aug 8, 2011 at 15:18

Chris Noe's user avatar

Chris NoeChris Noe

3972 gold badges5 silver badges16 bronze badges

3

You can use (in a standard Windows bat):

powershell -command "& { iwr http://www.it1.net/it1_logo2.jpg -OutFile logo.jpg }"

It seems to require PowerShell v4…

(Thanks to that comment and this one)

a_horse_with_no_name's user avatar

answered May 10, 2016 at 14:10

Anthony O.'s user avatar

Anthony O.Anthony O.

2601 gold badge6 silver badges8 bronze badges

Use FTP.

From the command line:

ftp ftp.somesite.com
user
password

etc. FTP is included in every Windows version I can remember; probably not in 3.1, maybe not in Windows 95, but certainly everything after that.

@RM: It is going to be rough if you don’t want to download any other tools. There exists a command line Wget for Windows and Wget is designed to do exactly what you’re asking for.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:01

Satanicpuppy's user avatar

SatanicpuppySatanicpuppy

6,7371 gold badge21 silver badges17 bronze badges

4

Use PowerShell like this:

  1. Create a download.ps1 file:

    param($url, $filename)
    $client = new-object System.Net.WebClient 
    $client.DownloadFile( $url, $filename)
    
  2. Now you can download a file like this:

    powershell Set-ExecutionPolicy Unrestricted
    powershell -ExecutionPolicy RemoteSigned -File "download.ps1" "http://somewhere.com/filename.ext" "d:filename.ext"
    

answered Apr 21, 2013 at 21:55

Thomas Jespersen's user avatar

1

On Win CMD (if you have write access):

set url=https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg
set file=file.jpg
certutil -urlcache -split -f %url% %file%
echo Done.

Built in Windows app. No need for external downloads.

Tested on Win 10

answered Apr 25, 2020 at 17:58

Zimba's user avatar

ZimbaZimba

96310 silver badges14 bronze badges

If you have python installed here’s an example which fetches the get-pip.py from the web

python -c "import urllib; urllib.urlretrieve ('https://bootstrap.pypa.io/get-pip.py', r'C:python27Toolsget-pip.py')"

gronostaj's user avatar

gronostaj

54.8k17 gold badges118 silver badges174 bronze badges

answered Aug 29, 2014 at 23:15

Sipherlab's user avatar

0

From Windows 10 build 17063 and later, ‘Curl’ is now included, so that you can execute it directly from Cmd.exe or PowerShell.exe.

For example:

C:>curl.exe -V
curl 7.55.1 (Windows) libcurl/7.55.1 WinSSL
Release-Date: 2017-11-14, security patched: 2019-11-05
Protocols: dict file ftp ftps http https imap imaps pop3 pop3s smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL

To download a file:

curl.exe -O https://cdn.sstatic.net/Sites/superuser/Img/logo.svg

answered Sep 10, 2020 at 14:41

gsl's user avatar

gslgsl

2072 silver badges9 bronze badges

If you install Telnet, I imagine you could make a HTTP request to a server to download a file.

You can also install Cygwin, and use wget to download a file as well. This is a very easy way to download files from the command line.

answered Oct 23, 2009 at 15:01

EvilChookie's user avatar

EvilChookieEvilChookie

4,5691 gold badge24 silver badges34 bronze badges

10

There are a few ways that you can download using the command line in Windows:

  1. You can use Cygwin.

    Note: the included apps are not native Linux apps. You must rebuild your application from source if you want to run on Windows.

  2. Using telnet it’s possible to make a request but you won’t see any processing.

  3. You can write bat or VBS scripts.

  4. Write your own program that you can run from cmd.exe.

Gaff's user avatar

Gaff

18.3k15 gold badges56 silver badges68 bronze badges

answered Aug 20, 2011 at 3:22

Jesus's user avatar

JesusJesus

111 bronze badge

You can install the Linux application Wget on Windows. It can be downloaded from http://gnuwin32.sourceforge.net/packages/wget.htm. You can then issue the command ‘wget (inserturlhere)’ or any other URL in your command prompt, and it will allow you to download that URL/file/image.

Peter Mortensen's user avatar

answered Oct 23, 2009 at 15:06

1

In default Windows, you can’t download via HTTP. Windows is a GUI-centric OS, so it lacks many of the commandline tools you’d find in other OS’s, like wget, which would be the prime candidate.

System.Net.WebClient.DownloadFile(), a function in the WiniNet API, can download files, but I’m not sure how far you’re getting into actual development vs. a batch file.

answered Oct 23, 2009 at 15:04

Andrew Scagnelli's user avatar

1

Downloading files in PURE BATCH…
Without any JScript, VBScript, Powershell, etc… Only pure Batch!

Some people are saying it’s not possible of downloading files with a batch script without using any JScript or VBScript, etc… But they are definitely wrong!

Here is a simple method that seems to work pretty well for downloading files in your batch scripts. It should be working on almost any file’s URL. It is even possible to use a proxy server if you need it.

For downloading files, we can use BITSADMIN.EXE from the Windows system. There is no need for downloading/installing anything or using any JScript or VBScript, etc. Bitsadmin.exe is present on most Windows versions, probably from XP to Windows 10.

Enjoy!


USAGE:

You can use the BITSADMIN command directly, like this:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND "http://example.com/File.zip" "C:DownloadsFile.zip"

Proxy Server:
For connecting using a proxy, use this command before downloading.
bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080"

Click this LINK if you want more info about BITSadmin.exe


TROUBLESHOOTING:
If you get this error: «Unable to connect to BITS — 0x80070422»
Make sure the windows service «Background Intelligent Transfer Service (BITS)» is enabled and try again. (It should be enabled by default.)


CUSTOM FUNCTIONS
Call :DOWNLOAD_FILE "URL"
Call :DOWNLOAD_PROXY_ON "SERVER:PORT"
Call :DOWNLOAD_PROXY_OFF

I made these 3 functions for simplifying the bitsadmin commands. It’s easier to use and remember. It can be particularly useful if you are using it multiple times in your scripts.

PLEASE NOTE…
Before using these functions, you will first need to copy them from CUSTOM_FUNCTIONS.CMD to the end of your script. There is also a complete example: DOWNLOAD-EXAMPLE.CMD

:DOWNLOAD_FILE «URL»
The main function, will download files from URL.

:DOWNLOAD_PROXY_ON «SERVER:PORT»
(Optional) You can use this function if you need to use a proxy server.
Calling the :DOWNLOAD_PROXY_OFF function will disable the proxy server.

EXAMPLE:
CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"
CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:DownloadsFile.zip"
CALL :DOWNLOAD_PROXY_OFF


CUSTOM_FUNCTIONS.CMD

:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF

DOWNLOAD-EXAMPLE.CMD

@ECHO OFF
SETLOCAL

rem FOR DOWNLOADING FILES, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.


:SETUP

rem URL (5MB TEST FILE):
SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"

rem SAVE IN CUSTOM LOCATION:
rem SET "SAVING_TO=C:Folder5MB.zip"

rem SAVE IN THE CURRENT DIRECTORY
SET "SAVING_TO=5MB.zip"
SET "SAVING_TO=%~dp0%SAVING_TO%"

:MAIN

ECHO.
ECHO DOWNLOAD SCRIPT EXAMPLE
ECHO.
ECHO FILE URL: "%FILE_URL%"
ECHO SAVING TO:  "%SAVING_TO%"
ECHO.

rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"
 
rem THE MAIN DOWNLOAD COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"

rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
rem CALL :DOWNLOAD_PROXY_OFF

:RESULT
ECHO.
IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
ECHO.

:EXIT_SCRIPT
PAUSE
EXIT /B




rem FUNCTIONS SECTION


:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF

As a Linux user, I can’t help but spend most of my time on the command line. Not that the GUI is not efficient, but there are things that are simply faster to do with the keyboard.

Think about copy and paste. Select a text you want to copy, go to the edit menu, click, precisely move down to copy, click, then go to the destination, click where you want to paste, go to edit menu, click, move down to the paste option, then paste. Every time I see someone do this, I die a little inside. Sure you can save some time by right-clicking, copy, right-click, paste. But you can save some more time by pressing, ctrl-c then ctrl-v

My hands are already on the keyboard, and I would rather do the mundane things on the keyboard and not think about them.

One thing I do frequently is download files. They can be zip file, tgz, or jpg. On linux, all I have to do is open the command line, run wget with the file I want to download and it is done.

wget http://example.org/picture.jpg

Straight to the point. But how do you do that when you are on a Windows machine? Let me introduce you to cURL, pronounced curl. (i don’t know why I wrote it the way I did)

curl is a very powerful tool with too many feature. But I just want to download the file on Windows so let’s just learn how to do that.

Open PowerShell. That’s Windows Key + R then type powershell and press enter.

Now run the curl command with the -O option to specify the file output.

curl http://example.org/picture.jpg -O picture.jpg

Easy right? Now you can download files right from the command line all by simply using your keyboard.

OK. It is time I confess. This is not the curl tool you are using. It’s only an alias. In reality, we are calling the command Invoke-WebRequest. But hey! It works, so we don’t care. You can call it in its native format if you want to.

Invoke-WebRequest http://example.org/picture.jpg -O picture.jpg

Either way, now you know how to download a file from the command line.


Можно ли скачивать с помощью командной строки Windows без использования каких-либо нестандартных (включая Windows) утилит?

Предпочтительной версией является Windows XP, но также интересно узнать о новых версиях.

Чтобы уточнить мой вопрос:

  • Это должно быть использование HTTP
  • Файл должен быть сохранен
  • Стандартная чистая установка Windows, никаких дополнительных инструментов

В общем, так как все кричат о Wget, я хочу простую функциональность Wget без использования Wget.

изменён Peter Mortensen8k

Начиная с Windows 7, я считаю, что есть один единственный метод, который еще не был упомянут, это простой:

Синтаксис:

bitsadmin  /transfer job_name       /download  /priority priority   URL  localpathfile

Пример:

bitsadmin  /transfer mydownloadjob  /download  /priority normal  ^
                  http://example.com/filename.zip  C:UsersusernameDownloadsfilename.zip

(Разбито на две отдельные строки с ^ для удобства чтения (чтобы избежать прокрутки).)

Предупреждение: как указано в комментариях, сообщение справки bitsadmin начинается со следующего:

BITSAdmin is deprecated and is not guaranteed to be available in future versions of Windows.
Administrative tools for the BITS service are now provided by BITS PowerShell cmdlets.

… но другой комментарий сообщил, что он работает на Windows 8.

Вы можете написать VBScript и запустить его из командной строки

Создайте файл downloadfile.vbs и вставьте следующие строки кода:

' Set your settings
    strFileURL = "http://www.it1.net/images/it1_logo2.jpg"
    strHDLocation = "c:logo.jpg"

' Fetch the file
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")

    objXMLHTTP.open "GET", strFileURL, false
    objXMLHTTP.send()

If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary

objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0    'Set the stream position to the start

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing

objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if

Set objXMLHTTP = Nothing

Запустите его из командной строки следующим образом:

cscript.exe downloadfile.vbs 

PowerShell (входит в состав Windows 8 и входит в состав .NET для более ранних выпусков) имеет такую возможность. Команда powershell позволяет запускать произвольные команды PowerShell из командной строки или файла .bat . Таким образом, следующая строка — это то, что нужно:

powershell -command "& { (New-Object Net.WebClient).DownloadFile('http://example.com/', 'c:somefile') }"

изменён Peter Mortensen8k

Я нашел способ сделать это, но на самом деле просто установить Wget.

Вы можете использовать Internet Explorer из командной строки (iexplore.exe), а затем ввести URL-адрес в качестве аргумента. Итак, запустите:

iexplore.exe http://blah.com/filename.zip

Каким бы ни был файл, вам нужно указать, что он не требует подтверждения заранее. И вот, он автоматически выполнит загрузку. Так что да, это технически возможно, но добрый господин делает это по-другому.

изменён Peter Mortensen8k

Windows Explorer (не путать с Internet Explorer) может загружать файлы через HTTP. Просто введите URL в адресную строку. Или из командной строки, например, C:windowsexplorer.exe http://somewhere.com/filename.ext .

Вы получаете классическую подсказку для загрузки файла . Если файл не является типом, который Windows Explorer знает, как отображать встроенный файл (.html, .jpg, .gif), в этом случае вам потребуется щелкнуть правой кнопкой мыши, чтобы сохранить его.

Я только что проверил это на своем образе VMware девственной установки Windows XP 2002 SP1, и он работает отлично.

изменён Peter Mortensen8k

Вы можете использовать (в стандартной Windows bat):

powershell -command "& { iwr http://www.it1.net/it1_logo2.jpg -OutFile logo.jpg }"

Кажется, требуется PowerShell v4 …

(Благодаря этому комментарию и этому)

изменён a_horse_with_no_name133

Используйте FTP.

Из командной строки:

ftp ftp.somesite.com
user
password

и т.д. FTP включен в каждую версию Windows, которую я помню; вероятно, не в 3.1, может быть, не в Windows 95, но, конечно, все после этого.

@RM: Это будет грубо, если вы не хотите загружать какие-либо другие инструменты. Существует командная строка Wget для Windows, и Wget разработан именно для того, что вы просите.

изменён Peter Mortensen8k

Используйте PowerShell следующим образом:

  1. Создайте файл download.ps1:

    param($url, $filename)
    $client = new-object System.Net.WebClient 
    $client.DownloadFile( $url, $filename)
    
  2. Теперь вы можете скачать файл так:

    powershell Set-ExecutionPolicy Unrestricted
    powershell -ExecutionPolicy RemoteSigned -File "download.ps1" "http://somewhere.com/filename.ext" "d:filename.ext"
    

ответ дан Thomas Jespersen191

Если вы устанавливаете Telnet, я думаю, вы могли бы сделать HTTP-запрос к серверу для загрузки файла.

Вы также можете установить Cygwin и использовать wget для загрузки файла. Это очень простой способ загрузки файлов из командной строки.

Вы можете установить приложение Linux Wget на Windows. Его можно скачать с http://gnuwin32.sourceforge.net/packages/wget.htm. Затем вы можете выполнить команду «wget (inserturlhere)» или любой другой URL в командной строке, и он позволит вам загрузить этот URL/ файл / изображение.

изменён Peter Mortensen8k

Есть несколько способов загрузки с помощью командной строки в Windows:

  1. Вы можете использовать Cygwin.

    Примечание: включенные приложения не являются родными приложениями Linux. Вы должны пересобрать свое приложение из исходного кода, если хотите работать в Windows.

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

  3. Вы можете написать сценарии bat или VBS.

  4. Напишите свою собственную программу, которую вы можете запустить из cmd.exe.

Если у вас установлен python, вот пример, который выбирает get-pip.py из Интернета.

python -c "import urllib; urllib.urlretrieve ('https://bootstrap.pypa.io/get-pip.py', r'C:python27Toolsget-pip.py')"

В Windows по умолчанию вы не можете скачать через HTTP. Windows — это GUI-ориентированная ОС, поэтому в ней отсутствуют многие инструменты командной строки, которые вы могли бы найти в других ОС, например, wget , который был бы главным кандидатом.

System.Net.WebClient.DownloadFile() , функция в WiniNet API, может загружать файлы, но я не уверен, насколько далеко вы продвинулись в реальной разработке по сравнению с командным файлом.

ответ дан Andrew Scagnelli2k

Понравилась статья? Поделить с друзьями:
  • Как скачать файл с сервера через ssh windows
  • Как скачать файл с сервера ubuntu на компьютер windows
  • Как скачать файл с windows store
  • Как скачать файл с linux сервера на windows
  • Как скачать файл с linux на windows по ssh