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
  • 27,717
  • 28
  • 128
  • 190
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
  • 121,444
  • 32
  • 184
  • 206
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,935
  • 6
  • 39
  • 48
Arcass
  • 932
  • 10
  • 19
  • 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,025
  • 3
  • 19
  • 27
Bryan
  • 11
  • 1