Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Wednesday, September 7, 2011

How to execute and analyze a dos command in PowerShell

Sometimes you may want to automate a process that involves using a DOS command.  You may also want to analyze the results.  The following PowerShell script shows you how to look for a positive result from a Ping command.  Granted, the Test-Connection cmdlet would be a better choice, but this is an example using commands that most everyone is familiar with.

 

$StartAddress = 1
$EndAddress = 10

# Loop through each address and test
For ($X=$StartAddress; $X -lt $EndAddress; $X++)
{
# Display the address that is being tested.
Write-Host "Testing 192.168.1.$X" -ForegroundColor blue

# Create the string that you would normally type.
$String = "Ping 192.169.249.$X -n 2"

# Use the Invoke-Expression cmdlet to execute the string
# and record the results in $Result.
$Result = Invoke-Expression $String

# Use Regular Expresses to determine if a positive
# responce came back. It the Responce is $True, then
# Write the string to the deafult output.
$Result -match "Reply from"
If ($_ -eq $True)
{
Write-Output $Sting}
}

No comments: