Damien Damien - 1 year ago 138
HTML Question

Parse a website and turn html content into variables within PowerShell

How would I call a URL and turn the page content into variables to use in PowerShell?

The HTML page looks like this:

<!DOCTYPE html>

<span class="server1var1">8</span>
<span class="server1var2">2</span>

<span class="server2var1">5</span>
<span class="server2var2">1</span>


Then in PowerShell I want these variables:

$server1var1 = "8"
$server1var2 = "2"

$server2var1 = "5"
$server2var2 = "1"

Accepting the answer below with one modification to make it work for me. Changing
solved the issue.

$content = Invoke-WebRequest -Uri 'http://urltomysite'
$content.ParsedHtml.getElementsByTagName('span') | ForEach-Object {
New-Variable -Name $_.className -Value $_.innerhtml

Answer Source

Use the Invoke-WebRequest cmdlet to retrieve the content of your website. Then use the getElementsByTagName of the ParsedHtml property to retrieve all span tags. Finally turn them into a variable using the New-Variable cmdlet:

$content = Invoke-WebRequest -Uri 'http://gameadmin.zerosurvival.com/servercodes.php'
$content.ParsedHtml.getElementsByTagName('span') | ForEach-Object { 
    New-Variable -Name $_.className -Value $_.textContent 

After you run this, if you type $server1var1 you will get 8.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download