Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

How to upload a file, the PowerShell way


If you haven’t activated scripting in PowerShell, do that first.

To access the System.Net namespace, I have to load it using the Load method (System.Reflection.Assembly.Load). To know what version and public key you must refer to, check the System.Net item in Explorer (C:\Windows\assembly).

This is the code, directly converted from the Visual Basic version:

#Load the System.Net namespace.
("System.Net, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

#The full path to the source file.
$Source =  "C:\MyFiles\SourceFile.txt"

#The full destination path (will be created).
$Destination = ""

#Use the static method Create to create a web request.
#Pass the destination as an argument, and cast it to a FtpWebRequest.

#Tell the request how it will login (using a NetworkCredential object)
$R.Credentials = New-Object System.Net.NetworkCredential("myUsername", "P@ssw0rd")

#...and what kind of method it will represent. A file upload.
$R.Method = "STOR"

#Here I use the simplest method I can imagine to get the
#bytes from the file to an byte array.
$FileContens = [System.IO.File]::ReadAllBytes($Source)

#Finaly, I put the bytes on the request stream.
$S = $R.GetRequestStream()
$S.Write($FileContens, 0, $FileContens.Length)

This code gives a good example on PowerShell syntax and it clearly illustrates the power and versatility of the language.

I used Graphical Windows with PowerShell 2.0 to do this example.

This example shows how to download a file using PowerShell.

Categories: PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *

En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!


Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   |   |   |   Filmtips