Powershell - trying to merge 2 result in 1 txt/csv - powershell

I'm trying to make a daily script to check status of list of URLS and pinging servers.
I've tried to combine the csv, however, the output of $status code is different from the one in csv
$pathIn = "C:\\Users\\test\\Desktop\\URLList.txt"
$URLList = Get-Content -Path $pathIn
$names = gc "C:\\Users\\test\\Desktop\\hostnames.txt"
#status code
$result = foreach ($uri in $URLList) {
try {
$res = Invoke-WebRequest -Uri $uri -UseBasicParsing -DisableKeepAlive -Method Head -TimeoutSec 5 -ErrorAction Stop
$status = [int]$res.StatusCode
}
catch {
$status = [int]$_.Exception.Response.StatusCode.value__
}
# output a formatted string to capture in variable $result
"$status - $uri"
}
$result
#output to log file
$result | Export-Csv "C:\\Users\\test\\Desktop\\Logs.csv"
#ping
$output = $()
foreach ($name in $names) {
$results = #{ "Host Name" = $name }
if (Test-Connection -Computername $name -Count 5 -ea 0) {
$results["Results"] = "Up"
}
else {
$results["Results"] = "Down"
}
New-Object -TypeName PSObject -Property $results -OutVariable nameStatus
$output += $nameStatus
}
$output | Export-Csv "C:\\Users\\test\\Desktop\\hostname.csv"
#combine the 2 csvs into 1 excel file
$path = "C:\\Users\\test\\Desktop" #target folder
cd $path;
$csvs = Get-ChildItem .\*.csv
$csvCount = $csvs.Count
Write-Host "Detected the following CSV files: ($csvCount)"
foreach ($csv in $csvs) {
Write-Host " -"$csv.Name
}
Write-Host "--------------------"
$excelFileName = "daily $(get-Date -Format dd-MM-yyyy).xlsx"
Write-Host "Creating: $excelFileName"
foreach ($csv in $csvs) {
$csvPath = ".\" + $csv.Name
$worksheetName = $csv.Name.Replace(".csv", "")
Write-Host " - Adding $worksheetName to $excelFileName"
Import-Csv -Path $csvPath | Export-Excel -Path $excelFileName -WorkSheetname $worksheetName
}
Write-Host "--------------------"
cd $path;
Get-ChildItem \* -Include \*.csv -Recurse | Remove-Item
Write-Host "Cleaning up"
Output in PowerShell
200 - https://chargebacks911.com/play-404/
200 - https://www.google.com/
500 - httpstat.us/500/
Host Name Results
----------------
x.x.x.x Down
x.x.x.x Up
Detected the following CSV files: (2)
- daily 26-03-2022.csv
- Logs.csv
--------------------
Creating: daily26-03-2022.xlsx
- Adding daily 26-03-2022 to daily26-03-2022.xlsx
- Adding Logs to daily26-03-2022.xlsx
--------------------
Cleaning up
\----------------------------------
result in excel
\#Hostname
Host Name Results
x.x.x.x Down
x.x.x.x Up
\#Logs
Length
42
29
22
I would like to know
how to correct the output in "Logs" sheet
if there's anyway to simplify my script to make it cleaner

Welcome to SO. You're asking for a review or refactoring of your complete script. I think that's not how SO is supposed be used. Instead you may focus on one particular issue and ask about a specific problem you have with it.
I will focus only on the part with the query of the status of your servers. You should stop using Write-Host. Instead you should take advantage of PowerShells uinique feature - working with rich and powerful objects instead of stupid text. ;-)
I'd approach the task of querying a bunch of computers like this:
$ComputernameList = Get-Content -Path 'C:\Users\test\Desktop\hostnames.txt'
$Result =
foreach ($ComputerName in $ComputernameList) {
[PSCustomObject]#{
ComputerName = $ComputerName
Online = Test-Connection -ComputerName $ComputerName -Count 1 -Quiet
}
}
$result
Now you have a PowerShell object you can pipe to Export-Csv for example or use it for further steps.
For example filter for the offline computers:
$result | Where-Object -Property Online -NE -Value $true
If you insist to have a visual control during the runtime of the script you may use Write-Verbose or Write-Debug. This way you can switch on the output if needed but omit it when the script runs unattended.

Related

CSV Output Unreadable

I'm trying to export the results of this simple script to a .csv file. I get the results but it either returns information about data of the results or a long jumble of data I'm sure how to parse correctly.
<#
Will ping all devices in list and display results as a simple UP or DOWN, color coded Red or Green.
#>
$Names = Get-Content -Path "C:\TestFolder\GetNames.txt"
$Output = #()
foreach ($name in $names)
{
if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue)
{
$Result1 += "$name, up"
Write-Host "$name, up" -ForegroundColor Green
}
else
{
$Result2 += "$name, down"
Write-Host "$name, down" -ForegroundColor Red
}
}
$Output += $Result1, $Result2
$Output = $Output | Select-Object
$Output | Export-Csv -Path 'C:\psCSVFiles\mycsv.csv' -NoTypeInformation
Results of this return:
Length
49768
25081
What am I doing wrong here? Thanks
Don't attempt to "format" the output strings manually - Export-Csv will take care of that part.
What you want to do is create objects with properties corresponding to the columns you want in your CSV:
$Names = Get-Content -Path "C:\TestFolder\GetNames.txt"
$Output = foreach ($name in $names) {
# test if computer is reachable/pingable
$isUp = Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue -Quiet
# construct output object with results
[pscustomobject]#{
ComputerName = $name
Status = if($isUp){ 'Up' }else{ 'Down' }
}
}
# Export to CSV
$Output |Export-Csv -Path 'C:\psCSVFiles\mycsv.csv' -NoTypeInformation
Alternatively, use Select-Object to modify the input strings directly using the pipeline:
Get-Content -Path "C:\TestFolder\GetNames.txt" |Select #{Name='ComputerName';Expression={$_}},#{Name='Status';Expression={if(Test-Connection -ComputerName $_ -Count 1 -ErrorAction SilentlyContinue -Quiet){'Up'}else{'Down'}}} |Export-Csv -Path 'C:\psCSVFiles\mycsv.csv' -NoTypeInformation

PowerShell Exporting

Can someone point me in the right direction? Basically, I would like to export the results of my testpath to a csv. Below is what I am working with. I have read a couple Microsoft documents but they only seem to confuse me even more. Any feedback is appreciated.
$ComputerList = (Get-ADComputer -Filter *).name
$ComputerList
write-host "`n"
Foreach ($Computer in $ComputerList)
{
$userfolders = get-childitem "\\$Computer\C$\users\"
foreach ($user in $userfolders) {
$ErrorActionPreference= 'silentlycontinue'
$path = $user.fullname
write-host $path
$t = test-path -Path "$path\AppData\Local\Google\Chrome\User Data\Default"
IF ($t -eq 'True') {write-host "Has it" -ForegroundColor yellow} ELSE {write-host "no"}
write-host "`n"
}
$Output =New-Object -TypeName PSObject -Property #{
} | Select-Object
}
$Output | C:\Users\"user"\Chrome.csv
write-output "Script finished. Please check output files"
Assuming you want a record per user per computer, there's two things you want to change structurally:
Create new objects in the inner foreach loop
Assign all the objects created to $Output:
$ComputerList = (Get-ADComputer -Filter *).name
$ComputerList
write-host "`n"
$Output = Foreach ($Computer in $ComputerList) {
$userfolders = get-childitem "\\$Computer\C$\users\"
foreach ($user in $userfolders) {
$ErrorActionPreference = 'silentlycontinue'
$path = $user.fullname
write-host $path
$t = test-path -Path "$path\AppData\Local\Google\Chrome\User Data\Default"
IF ($t -eq 'True') {write-host "Has it" -ForegroundColor yellow} ELSE {write-host "no"}
write-host "`n"
New-Object -TypeName PSObject -Property #{
# We still need a bit of magic here
}
}
}
$Output | C:\Users\"user"\Chrome.csv
write-output "Script finished. Please check output files"
Now we just need to decide on what properties to add to our output objects:
New-Object -TypeName PSObject -Property #{
# We definitely want to know which computer and user profile the results are for!
ComputerName = $Computer
ProfileName = $user.Name
# And finally we want the results of `Test-Path`
Result = $t
}
Here's another option. Though nowhere near as elegant as what Matthias gave you. ;-}
It's just a refactor, to narrow down your code and pass everything directly and output by default, without the need for all the, Write-* stuff and the like. PowerShell just grants a number of ways to accomplish a use case.
Clear-Host
$null = New-Item -Path 'C:\Temp\Chrome.csv' -Force
$Status = $null
$env:COMPUTERNAME,'Localhost', '127.0.0.1' |
Foreach {
Get-ChildItem "\\$PSItem\C$\users\" |
foreach {
$ErrorActionPreference = 'silentlycontinue'
# Use variable squeezing to assign and output to the screen
($path = $PSItem.fullname)
If (test-path -Path "$path\AppData\Local\Google\Chrome\User Data\Default") {$Status = 'Has it'}
Else {$Status = 'no'}
}
[PSCustomObject] #{
ComputerName = $PSItem
Status = $Status
} | Export-Csv -Path 'C:\Temp\Chrome.csv' -Append
}
'Script finished. Please check output files'
# Results on screen
<#
\\104DB2FE-76B8-4\C$\users\ContainerAdministrator
\\104DB2FE-76B8-4\C$\users\ContainerUser
\\104DB2FE-76B8-4\C$\users\Public
\\104DB2FE-76B8-4\C$\users\WDAGUtilityAccount
\\Localhost\C$\users\ContainerAdministrator
\\Localhost\C$\users\ContainerUser
\\Localhost\C$\users\Public
\\Localhost\C$\users\WDAGUtilityAccount
\\127.0.0.1\C$\users\ContainerAdministrator
\\127.0.0.1\C$\users\ContainerUser
\\127.0.0.1\C$\users\Public
\\127.0.0.1\C$\users\WDAGUtilityAccount
Script finished. Please check output files
#>
Import-Csv -Path 'C:\Temp\Chrome.csv'
# Results
<#
104DB2FE-76B8-4 no
Localhost no
127.0.0.1 no
#>
Clear-Host
$null = New-Item -Path 'C:\Temp\Chrome.csv' -Force
$Status = $null
$env:COMPUTERNAME,'Localhost', '127.0.0.1' |
Foreach {
Get-ChildItem "\\$PSItem\C$\users\" |
foreach {
$ErrorActionPreference = 'silentlycontinue'
# Use variable squeezing to assign and output to the screen
($path = $PSItem.fullname)
If (test-path -Path "$path\AppData\Local\MicrosoftEdge") {$Status = 'Has it'}
Else {$Status = 'no'}
}
[PSCustomObject] #{
ComputerName = $PSItem
Status = $Status
} | Export-Csv -Path 'C:\Temp\Chrome.csv' -Append
}
'Script finished. Please check output files'
# Results
<#
\\104DB2FE-76B8-4\C$\users\ContainerAdministrator
\\104DB2FE-76B8-4\C$\users\ContainerUser
\\104DB2FE-76B8-4\C$\users\Public
\\104DB2FE-76B8-4\C$\users\WDAGUtilityAccount
\\Localhost\C$\users\ContainerAdministrator
\\Localhost\C$\users\ContainerUser
\\Localhost\C$\users\Public
\\Localhost\C$\users\WDAGUtilityAccount
\\127.0.0.1\C$\users\ContainerAdministrator
\\127.0.0.1\C$\users\ContainerUser
\\127.0.0.1\C$\users\Public
\\127.0.0.1\C$\users\WDAGUtilityAccount
Script finished. Please check output files
#>
Import-Csv -Path 'C:\Temp\Chrome.csv'
# Results
<#
ComputerName Status
------------ ------
104DB2FE-76B8-4 Has it
Localhost Has it
127.0.0.1 Has it
#>

Add time in output file

This script add domain users to any other or remote domain computer / system's 'Administrators' group through the PowerShell.
This returns a final status in a csv with three columns (Computer name, availability, status)
I need to add a fourth column to this output file that contains the time and date.
#Create a file in the required path and update in the below command line
$Output = "C:\CSV\Output.csv"
#The output field of the computer will blank if the user is already exist in the group
Add-Content -Path $Output -Value "ComputerName,Availability,Status"
$status = $null
$availability = $null
#Save the CSV (Comma seperated) file with the server host name and the username to be added
Import-Csv C:\CSV\Computer.csv | ForEach-Object {
$Computer=$_.Computer
$User=$_.user
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
Write-Verbose "$Computer : Online"
$availability="Oniline"
try {
$GroupObj=[ADSI]"WinNT://$Computer/Administrators,group"
$GroupObj.PSBase.Invoke("Add",([ADSI]"WinNT://jdom.edu/$User").Path)
$status="Success"
#Update the status in the output file
Add-Content -Path $Output -Value ("{0},{1},{2}" -f $Computer, $availability, $status)
} catch {
Write-Verbose "Failed"
}
} else {
Write-Warning "$Computer : Offline"
$availability = "Offline"
$status = "failed"
#Update the status in the output file
Add-Content -Path $Output -Value ("{0},{1},{2}" -f $Computer, $availability, $status)
}
}
This is how the output file looks, this is where I want to add the fourth column with date and time:
ComputerName,Availability,Status
TD123696WJN339P,Oniline,Success
TD123419WJN339P,Oniline,Success
ComputerName,Availability,Status
5VERF9097LTIO01,Offline,failed
ZF001024DJH706G,Offline,failed
5MICF9017LTIO01,Offline,failed
The simple approach would be to just add another field to your output, i.e.
Add-Content -Path $Output -Value "ComputerName,Availability,Status,Timestamp"
and
"{0},{1},{2},{3}" -f $Computer, $availability, $status, (Get-Date)
However, unless you actually want multiple header lines in your output file (why?) you should rather use calculated properties and Export-Csv.
Import-Csv 'input.csv' |
Select-Object Computer, User, #{n='Status';e={
if (Test-Connection -ComputerName $_.Computer -Count 1 -Quiet) {
...
} else {
...
}
}}, #{n='Timestamp';e={Get-Date}} |
Export-Csv 'output.csv' -NoType
This is really interesting approach you have there working with CSV and it overcomplicates the scenario a bit (from my perspective and no disrespect!).
Why don't try using a PowerShell Custom Object?
#Create a file in the required path and update in the below command line
$Output = "C:\CSV\Output.csv"
#The output field of the computer will blank if the user is already exist in the group
Add-Content -Path $Output -Value "ComputerName,Availability,Status"
$status = $null
$availability = $null
#Save the CSV (Comma seperated) file with the server host name and the username to be added
$result = Import-Csv C:\CSV\Computer.csv | ForEach-Object {
$Computer=$_.Computer
$User=$_.user
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
Write-Verbose "$Computer : Online"
$availability="Oniline"
try {
$GroupObj=[ADSI]"WinNT://$Computer/Administrators,group"
$GroupObj.PSBase.Invoke("Add",([ADSI]"WinNT://jdom.edu/$User").Path)
$status="Success"
#Update the status in the output file
[PSCustomObject]#{
Computer = $Computer
Availability = $availability
Status = $status
Date = Get-Date
}
} catch {
Write-Verbose "Failed"
}
} else {
Write-Warning "$Computer : Offline"
$availability = "Offline"
$status = "failed"
#Update the status in the output file
[PSCustomObject]#{
Computer = $Computer
Availability = $availability
Status = $status
Date = Get-Date
}
}
}
$result | Export-Csv -Path $Output -NoTypeInformation
This way, you will store the result into the $result variable and will be able to export it as CSV, without any complication.
Using PowerShell Custom Object is a great way to store data from different sources and provide the output in the way you would like to see it.
Give it a try and provide a feedback, if you would like :)

Unable to generate HTML table from Powershell function

I have got a powershell function that gets all errors and warnings from the event logs, counts the occurance of each Event ID and returns a Powershell table. THe code that does this is as follows -
function Get-EventLogs {
[System.Collections.ArrayList]$results = #()
#Do you want to enable transcript for logging all output to file?
$enableLogging = $FALSE
$ExportEnabled = $FALSE
# logging
# if you need detailed logging for troubleshooting this script, you can enable the transcript
# get the script location path and use it as default location for storing logs and results
$log = $MyInvocation.MyCommand.Definition -replace 'ps1','log'
$resultPath = $PSScriptRoot + '\'
Push-Location $resultPath
if ($enableLogging)
{
Start-Transcript -Path $log -ErrorAction SilentlyContinue
Write-Host "Logging enabled..."
Write-Host
Write-Host "Powershell version"
$PSVersionTable.PSVersion
$Host.Version
(Get-Host).Version
Write-host
}
$currentCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
# Configuration
# selected Event log sources
# limit the feedback only to the following logs
$EventLogList = 'System','Application'
#for FIM Health Check the Security log has less signification value and is skipped
#add it to the eventlog list when you need it
#,'Security'
# if the event logs are containing too much data,
#collect x years of logs
$startdate = ((Get-Date).AddDays(-7))
$Count = 0
$Activity = "Checking log properties"
$allEvents = New-Object System.Collections.Hashtable
$Count = 0
$Activity = "Checking log detaills"
foreach ($eventlog in $EventLogList)
{
#$Count += 1
$pct = ($Count / $EventLogList.Count * 100)
$status = $EventLog + " (" + $Count + "/" + $EventLogList.Count +")"
Write-Progress -Activity $Activity -Status $status -PercentComplete $pct
write-host $count"." $eventlog
[System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"
# query the event log
# store the data in a hashtable, to avoid new queries
$allEvents = $Null
$allEvents = Get-WinEvent -FilterHashtable #{logname=$eventlog;StartTime=$startdate;level=0,1,2,3,4,5} -ErrorAction SilentlyContinue
#DEBUG if ($eventlog -eq "Application") { $allevents}
if ($allEvents.count -eq 0)
{
$message = "No events for " + $eventlog + "log since "+ $startdate + "."
Write-Host $message
Write-Host
# no data to process, skip processing for current loop
Continue
}
#For events detailed reporting we're only interested in error events
#not interested in informational events (level 0 and 4)
$evtStats = $allEvents | where -Property level -Notin -Value 0,4 | Group-Object id | Sort-Object Count -Descending
$allevents = $Null
#prep export
$exportfile = $resultPath + "_EventIDStats"+ $eventlog + ".csv.txt"
if ($exportEnabled) {$export | Export-Csv $exportfile -NoTypeInformation}
# evtStats has number and ID attribute
# other attributes must be added:
# - errortype name
# - Source
# - errortype name
# for each event id in the event statistics
# display the most recent event
$Activity = "Looking up last event occurrence..."
$i= 0
foreach ($item in $evtStats)
{
$i += 1
$pct = ($i / $evtStats.Count * 100)
$eventID = $item.Name
$status = "EventID: "+ $item.Name
Write-Progress -Activity $Activity -Status $status -PercentComplete $pct
$customobj = "" | select Count,ErrorID,ErrorType,Message
$customobj.Count = $item.Count
$customobj.ErrorID = $item.Name
#get most recent event from the eventID
$id = $item.Name.ToInt32($Null)
[System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"
$lastevent = get-winevent -FilterHashtable #{LogName=$eventlog;Id=$id} -MaxEvents 1 -ErrorAction SilentlyContinue
#depending on local settings, query might fail, if it fails reset to local culture
if ($lastevent.LevelDisplayName.Length -eq 0)
{
[System.Threading.Thread]::CurrentThread.CurrentCulture = $currentCulture
$lastevent = get-winevent -FilterHashtable #{LogName=$eventlog;Id=$id} -MaxEvents 1
}
$customobj.ErrorType = $lastevent.LevelDisplayName
$customobj.Message = $lastevent.Message
#prep EventID export
$exportfile = $resultPath + $eventlog +'_EventID_' + $customobj.ErrorID + ".csv.txt"
if ($exportEnabled)
{
$customobj | Export-Csv $exportfile -NoTypeInformation
}
$results += $customobj
}
#display with format
$results | Format-Table -AutoSize
return ,$results
if ($exportEnabled)
{
$exportfile = $resultPath + "_lastEvents_short_" + $eventlog + ".txt"
$results| Format-Table -AutoSize | out-file $exportfile
$exportfile = $resultPath + "_lastEvents_detail_" + $eventlog + ".txt"
$results | out-file $exportfile
}
}
#Write-Output $results | Format-Table -AutoSize
}
I then need to format the output of this function as a HTML table, so I can show it in my report.
$elogs = (Get-EventLogs) | Out-String
The code above outputs it as a long string (to be expected). But I cannot figure out how to format it as a HTML table. THe code that finally generates the report is as follows -
$Report = ConvertTo-Html -Title "$Computername" `
-Head "<center><h1>Server Report for <br><br>$Computername</h1></center><br /><br />" `
-Body "$Heading $Hardware $elogs $PercentFree $Output $Restarted $Services $Stopped $Css" }
Is there a way to output this as a table?
ConvertTo-Html is able to take an object and render that object as a HTML table. For simplicity's sake, I'll include the -Fragment switch that will ONLY return a HTML table (not all the HTML header, etc.).
Take a simple object, such as some basic process data, and you can create a HTML table:
[PS] $p = Get-Process | Select -First 3 -Property Name,ID
[PS] $p | ConvertTo-Html -Fragment
<table>
<colgroup><col/><col/></colgroup>
<tr><th>Name</th><th>Id</th></tr>
<tr><td>Process1</td><td>1888</td></tr>
<tr><td>Process2</td><td>1536</td></tr>
<tr><td>Process3</td><td>13920</td></tr>
</table>
Note that we don't need to specify a -Body with all the variables; we just need to make sure that we have all the data collected in an object (with the appropriate property names) and the cmdlet does the rest.
Going back to your script, there are a few things to look at:
Don't use Write-Host. If you want debug messages, consider using Write-verbose and Write-Debug. You'll need to set the $VerbosePreference and $DebugPreference variables to "Continue" to make this output visible.
Similarly, avoid using Format-Table
Your script returns an object ,$results. You should be able to pipe this into ConvertTo-Html with additional header and body content.
Note finally that the -Body switch doesn't format your object; it just includes extra HTML in front of the HTML table.

Invoke-Command: Null-value and positional parameter errors

I wanted to start a new thread for this, since I am using a different method in my code now. I have written a script that pings hundreds of devices and logs their online or offline status. It was taking an extremely long time to run, so I am now looking into using Invoke-Command to run the commands remotely on servers for each site (instead of all from the same server). I am receiving the following errors: "A positional parameter cannot be found that accepts argument 'Of'", "You cannot call a method on a null-valued expression", and this is happening for each server as it is iterating through them. Any ideas as to why this is happening? Thank you very much, here is my current code:
<#
.NOTES
===========================================================================
Created on: 11/17/2016 8:06 AM
Created by:
Organization:
Filename: Get-MPOSOfflinePrinters.ps1
===========================================================================
.DESCRIPTION
#>
#Define log file variables and remove any existing logs
$logfile = "D:\Logs\MPOSPrinterPingLog.txt"
$offlineprinters = "D:\Reports\MPOS\MPOSOfflinePrinters.txt"
If (Test-Path $logfile) {Remove-Item $logfile}
If (Test-Path $offlineprinters) {Remove-Item $offlineprinters}
Add-Content $logfile "Gathering server list"
#Compiling list of all MPOS Print Servers
$serverList = (Get-ADComputer -Filter "Name -like 'Q0*P30' -or Name -like 'Q0*P32'" -SearchBase "OU=Print,OU=Prod,OU=POS,DC=COMPANY,DC=NET").name | Sort-Object | Out-File C:\Temp\MPOS\MPOSPrintServers.txt
$serverListPath = "C:\Temp\MPOS\MPOSPrintServers.txt"
Add-Content $logfile "Compiling text file"
#Retrieve a list of MPOS Print servers from text file and set to variable $serverNames
$serverNames = Get-Content -Path $serverListPath
Invoke-Command -ComputerName $serverNames -ScriptBlock {
#Define log file variables and remove any existing logs
$logfile = "C:\Temp\MPOSPrinterPingLog.txt"
$offlineprinters = "C:\Temp\MPOSOfflinePrinters.txt"
$masteroffline = "\\a0345p689\d$\Reports\MPOS\MPOSOfflinePrinters.txt"
If (Test-Path $logfile) {Remove-Item $logfile}
If (Test-Path $offlineprinters) {Remove-Item $offlineprinters}
#process xml file to parse IP addresses for ping
$timestamp2 = (Get-Date -Format g)
Add-Content $logfile "$timestamp2 - Processing xml file from $serverName to parse data to csv"
$xml = [xml](Get-Content C:\ProgramData\Microsoft\Point Of Service\Configuration\Configuration.xml)
$PrinterNames = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property #{LogicalName=$_.LogicalName.Name}}
$PrinterIPs = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property #{HardwarePath=$_.HardwarePath}}
foreach ($PrinterIP in $PrinterIPs) {
$pingableIP = $PrinterIP.HardwarePath
If (Test-Connection $pingableIP -Quiet -Count 1) {
$timestamp3 = (Get-Date -Format g)
Add-Content $logfile "$timestamp3 - $serverName, $pingableIP is online and pingable"
}
Else {
$timestamp3 = (Get-Date -Format g)
Add-Content $offlineprinters "$timestamp3 - $serverName, $pingableIP is offline!"
}
Get-Content $offlineprinters | Out-File -FilePath $masteroffline -Append -NoClobber
} #foreach ($PrinterIP in $PrinterIPs) {
} #Invoke-Command -ComputerName $serverNames -ScriptBlock {