在Powershell中如何使用$webclient.downloadstring将内容写入文本文件?

6

我不是程序员或脚本编写者。我只需要让以下脚本写入到一个文件中:

[CmdletBinding()]
param ()

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


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

我尝试了out-file和export-csv,但它们只会生成空文件。我相信这是一些简单的问题...但由于缺乏知识,对我来说很难。

3个回答

9
您也可以使用DownloadFile方法:
$webClient.DownloadFile('http://myip.dnsomatic.com/', 'c:\ip.txt')

8

add-content命令应该可以满足您的需求。

假设$webClient.DownloadString('http://myip.dnsomatic.com/')返回一个字符串,请尝试:

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

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


我遇到了一个错误,也许是$webclient和-value之间需要加上空格?编辑:啊,我的错,不要忘记包括$webClient = New-Object System.Net.WebClient。 - user230910

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接