6

I'm not a programmer/scripter. I just need to get the following script to write to a file:

[CmdletBinding()]
param ()

# Create a web client object
$webClient = New-Object System.Net.WebClient


# Returns the public IP address
$webClient.DownloadString('http://myip.dnsomatic.com/')

I've tried out-file and export-csv but it write a blank file. I'm sure it's something simple...but having no knowledge makes it difficult for me.

Liam
  • 25,247
  • 27
  • 110
  • 174
pace
  • 63
  • 1
  • 1
  • 3

3 Answers3

9

You could also use the DownloadFile method:

$webClient.DownloadFile('http://myip.dnsomatic.com/', 'c:\ip.txt')
Shay Levy
  • 114,369
  • 30
  • 175
  • 198
8

The add-content cmdlet should do what you want.

Assuming $webClient.DownloadString('http://myip.dnsomatic.com/') returns a string, try:

Add-Content -Path $filename -Value $webClient.DownloadString('http://myip.dnsomatic.com/')

Reference: http://technet.microsoft.com/en-us/library/dd347594.aspx

VertigoRay
  • 5,425
  • 6
  • 37
  • 46
Arcass
  • 922
  • 10
  • 19
  • No problem. If this helped can you make the as the accepted answer. – Arcass Feb 20 '12 at 17:34
  • I get an error, perhaps a space is needed between $webclient and -value ? EDIT: Aah my mistake, dont forget to include $webClient = New-Object System.Net.WebClient – user230910 Oct 28 '14 at 06:46
1
$PublicIP="C:\PublicIP.txt"

$WebClient=New-Object net.webclient

$String=$WebClient.DownloadString("http://checkip.dyndns.com") -replace "[^\d\.]"

If (Test-Path $PublicIP) {

    Remove-Item $PublicIP
}

New-Item $PublicIP -type file

Add-Content -Path $PublicIP -Value $String
bencripps
  • 2,009
  • 3
  • 17
  • 27
Bryan
  • 11
  • 1