Currently i have the below script to import from a csv file with a few columns. the ones i am interested in are Hostname and Ipaddress.
Ipaddress = ip address of servers
Hostname - hostnames of servers
basically what i am aiming to do is an audit of currently active servers in our CMDB (lot of old junk that hasn't been properly removed)
$servers = import-csv 'config-network devicetest.csv'
$collection = $()
foreach ( $IPAddress in $servers)
{
$status = #{ "ServerName" = $Hostname; "TimeStamp" = (Get-Date -f s) }
if (Test-Connection -IPAddress $IPAddress -Count 2 -ea 0 -quiet)
{
$status["Results"] = "Active"
}
else
{
$status["Results"] = "Inactive"
}
New-Object -TypeName PSObject -Property $status -OutVariable serverStatus
$collection += $serverStatus
}
$collection | Export-Csv .\ServerStatus.csv -NoTypeInformation
My goal is to run test-connection on each Ip address and output to a file that has timestamp/results/servername (being Hostname).
currently i am always getting the result "inactive" and i think this is due to me not calling the proper fields from the csv.
i'm fairly new to importing from csv so any help with how to properly import and export specific columns would be very helpful.
I've done a bit of a search on the web but nothing that really explains it clearly or in this context.
Thank you in advance.
Try to change these lines:
$status = #{ "ServerName" = $IPAddress.Hostname; "TimeStamp" = (Get-Date -f s); "Results"="" }
...
....
(Test-Connection -IPAddress $IPAddress.ipaddress -Count 2 -ea 0 -quiet)
...
..
.
Related
I am looking for some help with a script that will read a textfile full of server names and resolve the IP address and export this into a csv file. I am using powershell for this and the Test-Connection command. Please see below code - i am getting the error - cmdlet ForEach-Object at command pipeline position 1 Supply values for the following parameters:Process[0]:
(removed my username and swapped with ***)
$array=#()
$computer=Get-Content -Path c:\Users\****\Desktop\ping_IP_host\computers.txt
ForEach ($server in $computer){
if(Test-Connection $server -Quiet)
{
try {
$IP=
[System.net.dns]::GetHostEntry($server).AddressList | %
{$_.IpAddressTostring}
}
catch {"Invalid HostName" - $server}
$obj = New-Object PSObject -Property #{
Hostname=$server
IP=$IP
}
$array += $obj
else {
$IP="Invalid Host"
}
$obj = New-Object PSObject -Property #{
Hostname=$server
IP=$IP
}
$array += $obj
}
}
$array | Export-Csv C:\Users\****\Desktop\ping_IP_host\results.csv
There is a misplace curly bracket, duplicated code, logic error and unwrapped objects.
Indenting properly will help you to find errors and duplicated code.
The custom object you build does contain both IPv4 and IPv6 addresses, so you may want to join the 2 addresses OR just select the IPv4 address - I do not know your requirements.
Edit:
The try..catch block is not needed as it depends on GetHostEntry() getting a result for the DNS lookup of $server, which is already verified by the test-connection. In short, your code defaults to the else clause "Invalid Host" when the host does not exist OR the host does not answer to ICMP.
the try..catch block around $IP = ([System.net.dns]::GetHostEntry($server).AddressList should be located before the Test-Connection because an error means the host name is invalid so no point in trying a ping.
Note: The code below does not take into account the above edit.
Working code:
$array=#()
$computer=Get-Content -Path $env:userprofile\Desktop\ping_IP_host\computers.txt
ForEach ($server in $computer) {
if (Test-Connection $server -Quiet -count 1) {
try {
$IP = ([System.net.dns]::GetHostEntry($server).AddressList | ForEach-Object {$_.IPAddressToString} ) -join ";"
}
catch {"Invalid HostName" - $server}
}
else {
$IP="Invalid Host"
}
$obj = New-Object PSObject -Property #{
Hostname = $server
IP = $IP
}
$array += $obj
}
$array | Export-Csv -NoTypeInformation $env:userprofile\Desktop\ping_IP_host\results.csv
Output:
"IP","Hostname"
"216.58.206.68;2a00:1450:4002:803::2004","www.google.com"
"Invalid Host","jupiter"
"Invalid host","microsoft.com"
Select IPv4 address only
$array=#()
$computer=Get-Content -Path $env:userprofile\computers.txt
ForEach ($server in $computer) {
if (Test-Connection $server -Quiet -count 1) {
try {
$IP = [System.net.dns]::GetHostEntry($server).AddressList | Where-Object {$_.AddressFamily -eq 'InterNetwork'} | ForEach-Object {$_.IPAddressToString}
}
catch {"Invalid HostName" - $server}
}
else {
$IP="Invalid Host"
}
$obj = New-Object PSObject -Property #{
Hostname = $server
IP = $IP
}
$array += $obj
}
$array | Export-Csv -NoTypeInformation $env:userprofile\Desktop\ping_IP_host\results.csv
Output:
"IP","Hostname"
"216.58.206.68","www.google.com"
"Invalid Host","jupiter"
"Invalid host","microsoft.com"
I am trying to export the result of the powershell to csv with $server as the first column and online/offline as the second column. There are many column i want to define actually. I think this is a good start. Please let me know how to achieve this.
$ErrorActionPreference = 'SilentlyContinue'
$ServerName = "TDL498", "TDL498123", "TDL498456"
foreach ($Server in $ServerName)
{
if (test-Connection -ComputerName $Server -Count 2 -Quiet)
{
write-Host "$Server Online" -ForegroundColor Green
}
else
{
Write-Host "$Server Offline"
}
}
you can do that by making a PSCustomObject. [grin] as far as i can tell, there is no need to set any special error handling with the Test-Connection cmdlet since it returns a False/True for connection tests with the -Quiet parameter.
$ComputerNameList = #(
'LocalHost'
'10.0.0.1'
'127.0.0.1'
'BetterNotBeThere'
$env:COMPUTERNAME
)
$Results = foreach ($CNL_Item in $ComputerNameList)
{
[PSCustomObject]#{
ComputerName = $CNL_Item
Online = Test-Connection -ComputerName $CNL_Item -Count 1 -Quiet
}
}
# on screen
$Results
# to csv file
$Results |
Export-Csv -LiteralPath "$env:TEMP\MuhammadSuhailAsrulsani_ComputerStatus.csv" -NoTypeInformation
output to screen ...
ComputerName Online
------------ ------
LocalHost True
10.0.0.1 False
127.0.0.1 True
BetterNotBeThere False
[MySysName] True
CSV file content ...
"ComputerName","Online"
"LocalHost","True"
"10.0.0.1","False"
"127.0.0.1","True"
"BetterNotBeThere","False"
"[MySysName]","True"
I am trying to add the IP address to this script, it would be perfect if I could get this to work. Any help is greatly appreciated.
The input files has host names, and I like to get the IP address into the csv please.
$servers = Get-content "servers.txt"
$collection = $()
foreach ($server in $servers)
{
$status = #{ "ServerName" = $server; "TimeStamp" = (Get-Date -f s);"IP" = what to put here? }
if (Test-Connection $server -Count 1 -ea 0 -Quiet)
{
$status["Results"] = "Up"
}
else
{
$status["Results"] = "Down"
}
New-Object -TypeName PSObject -Property $status -OutVariable serverStatus
$collection += $serverStatus
}
$collection | Export-Csv -LiteralPath .\ServerStatus.csv -NoTypeInformation
Using -Quiet would suppress the information you are looking for. Remove the quiet and instead capture the results in a variable you can then query for both success and the ipaddress.
$status = #{ "ServerName" = $server; "TimeStamp" = (Get-Date -f s)}
$result = Test-Connection $server -Count 1 -ErrorAction SilentlyContinue
if ($result)
{
$status.Results = "Up"
$status.IP = ($result.IPV4Address).IPAddressToString
}
else
{
$status.Results = "Down"
$status.IP = "N/A"
}
I am unsure if this logic would produce misleading information but I am playing around with it just in case.
If you have already made the switch to IPv6 then you might be more interested in ($result.IPV6Address).IPAddressToString
Thank you, Matt, you helped me work through my issue.
I found that I wasn't able to use (.) in the new variables. Could be my own misunderstanding. I post this that it may help others with my same issue.
Based on your answer plus an example of how I had to adjust.
$status = #{ "ServerName" = $server; "TimeStamp" = (Get-Date -f s)}
$result = Test-Connection $server -Count 1 -ErrorAction SilentlyContinue
if ($result)
{
$StatusResult = "Up"
$statusIP = ($result.IPV4Address).IPAddressToString
}
I have put together a script from various sources, but cannot understand why i am getting duplicated entries in my results..
eg..
I need to check the scheduled tasks on remote servers, and verify which ones didnt complete sucesfully, and then investigate those.
I have a schedulers.csv file, which has two comlumns IP, and Name.
I downloaded the script Get-ScheduledTask.ps1 from https://gallery.technet.microsoft.com/scriptcenter/Get-Scheduled-tasks-from-3a377294
Works great and does what i needed.
I then wanted to from a list retrieve the servers names, run the above script as a parameter, then get back the scheduled tasks in a csv file.
NextRunTime Author Trigger State UserId ComputerName Name LastRunTime LastTaskResult Description NumberOfMissedRuns Enabled Path
The headers for the above script give me Name and LastTaskResult, which is what I wanted to query further.
The LastTaskResult should be 0 if it completed sucesfully, otherwise i would investigate further.
The code i have so far is :
$servers = Import-Csv "C:\test\schedulers.csv"
foreach($server in $servers){
$ServerName = $server.Name
$ServerAddress = $server.IP
Write-Host $ServerName : $ServerAddress
$importfile = Get-ScheduledTask.ps1 -ComputerName $ServerName
|Export-Csv -Path c:\test\scheds.csv -NoTypeInformation
$Lines = Import-Csv "C:\test\scheds.csv"
ForEach($line in $lines){
$lines | %{
$TaskName = $_.name
$taskresult = $_.LastTaskResult
if ($_.LastTaskResult -ne "0")
{
Write-Host $line.LastTaskResult : $_.name : $_.Path
}else{
}
}
}
}
There should be 3 results that show, that have a value of 1 in LastTaskResult, but i get about 38 which is the total amount of tasks on the two servers that i am testing on.
the 3 entries are there also as well, plus all the rest..
please can anyone see where i have gone wrong.. Many Thanks
not tested because i don't have your Get-ScheduledTask.ps1, but here's what i might change
$servers = Import-Csv "C:\test\schedulers.csv"
foreach ($server in $servers) {
$ServerName = $server.Name
$ServerAddress = $server.IP
Write-Host $ServerName : $ServerAddress
$importfile = Get-ScheduledTask.ps1 -ComputerName $ServerName
$importfile | Export-Csv -Path c:\test\scheds.csv -NoTypeInformation
foreach ($line in $importfile) {
if ($line.LastTaskResult -ne '0') {
Write-Host $line.LastTaskResult : $line.Name : $line.Path
}
}
}
Two issues,
I want a constaint ping to the two servers, and output to a .csv file.
The script below only runs twice and the output doesn't work. I'm a power newbie so please go easy.
$servers = "server1","server2"
$collection = $()
foreach ($server in $servers)
{
$status = #{ "ServerName" = $server; "TimeStamp" = (Get-Date -f s) }
if (Test-Connection $server -Count 1 -ea 0 -Quiet)
{
$status["Results"] = "Up"
}
else
{
$status["Results"] = "Down"
}
New-Object -TypeName PSObject -Property $status -OutVariable serverStatus
$collection += $serverStatus
}
$collection | Export-Csv -LiteralPath .\ServerStatus.csv -NoTypeInformation
The output works fine. Just run the script and then Invoke-Item ServerStatus.csv
If you want it to run forever just wrap the whole thing in a while loop:
$servers = "server1","server2"
$collection = $()
while(1) {
foreach ($server in $servers)
{
...
}
$collection | Export-Csv -LiteralPath .\ServerStatus.csv -NoTypeInformation
}