使用PowerShell命令行开关下载文件

时间:2015-03-30 22:39:39

标签: windows powershell powershell-v2.0 webclient powershell-v3.0

该命令与Windows Server 2012(PowerShell 4.0)配合使用,但它不能与Windows 8(PowerShell 4.0)一起使用。

我想从IIS服务器下载文件。

 (New-Object System.Net.WebClient).DownloadFile('http://server12/vdir/v.exe','C:\pqr.exe')

我试过这个。它在Windows Server 2012上对我很好,但在Windows 8上它给了我一个方法调用错误:

  

使用“2”参数调用“DownloadFile”的异常:“WebClient请求期间发生异常。

2 个答案:

答案 0 :(得分:1)

我正在使用Windows 7(32位),我得到了和你一样的错误,因此,我编写了一个VBScript脚本,生成PowerShell脚本,以便在临时文件夹中下载此文件并执行它,它对我来说很好。

<强> DownloadPSVBS.vbs

Option Explicit
Dim URL,Ws,ByPassPSFile,PSFile,MyCmd,Result
URL = "http://hackoo.alwaysdata.net/Matrix.mp3"
Set Ws = CreateObject("wscript.Shell")
PSFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
ByPassPSFile = "PowerShell.exe -ExecutionPolicy bypass -noprofile -file "
MyCmd = "$source = " & DblQuote(URL) & VbCrlF
MyCmd = MyCmd & "$Filename = [System.IO.Path]::GetFileName($source)" & VbCrlF
MyCmd = MyCmd & "$dest = " & DblQuote("$env:temp\$Filename") & VbCrlF
MyCmd = MyCmd & "$wc = New-Object System.Net.WebClient" & VbCrlF
MyCmd = MyCmd & "$wc.DownloadFile($source,$dest)" & VbCrlF
MyCmd = MyCmd & "Start-Process $dest"
Call WriteMyPSFile(MyCmd)
Result = Ws.run(ByPassPSFile & PSFile,0,True)
'**********************************************************************************************
Sub WriteMyPSFile(strText)
Dim fs,ts,PSFile
Const ForWriting = 2
    PSFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set ts = fs.OpenTextFile(PSFile,ForWriting,True)
    ts.WriteLine strText
    ts.Close
End Sub
'**********************************************************************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************

答案 1 :(得分:0)

要使用PowerShell下载文件,您可以使用Invoke-WebRequest

mkdir c:\download
Invoke-WebRequest http://server12/vdir/v.exe -OutFile c:\download\pqr.exe

或者像这样使用它:

mkdir C:\download
$a = New-Object System.Net.WebClient
$a.DownloadFile("http://server12/vdir/v.exe","c:\download\pqr.exe")