Add time in output file - powershell

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 :)

Related

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

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.

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

How can I speed up this Powershell Loop

I am very new at Powershell, but I recently decided to try and recreate an old tool we sometimes use but as a Powershell script. The script takes in user input to get an IP Range then pings, gets hostname, checks if service exists and is running, and then exports it to a CSV file. I haven't done too much cleaning up of the code yet. It does what I want but when I was testing it on larger IP ranges it was taking several minutes ie. 1-254 took around 10 minutes. Any tips would be appreciated.
Add-Content -Path ".\$fullrange.csv" -Value '"Ping","IP","Hostname","Service State","Startup","Version"'
ForEach($IP in $range) {
$status = test-connection -computername ($IP) -count 1 -Quiet -ErrorAction SilentlyContinue
if ($status) {
$hostname = [System.Net.Dns]::GetHostbyAddress("$IP")."HostName"
$service = Get-WmiObject -Class Win32_Service -ComputerName $IP -ErrorAction SilentlyContinue | Where-Object Name -like "SysaidAgent"
if ($service) {
$xml = [xml](Get-Content "\\$IP\C$\Program Files\SysAid\Configuration\AgentConfigurationFile.xml")
$ver = $xml.SelectSingleNode("//AgentVersion")."#text"
}
else{
$service = "Not Found"
$ver = "N/A"
}
Add-Content -Path .\$fullrange.csv -Value "$status,$IP,$hostname,$service.state,$service.startmode,$ver"
}
else{
Add-Content -Path .\$fullrange.csv -Value "$status,$IP"
}
}

Powershell Export to CSV from ForEach Loop

I'm new to Powershell but I've given it my best go.
I'm trying to create a script to copy a file to the All Users Desktop of all the XP machines in an Array. The script basically says "If the machine is pingable, copy the file, if not, don't." I then want to export this information into a CSV file for further analysis.
I've set it all but no matter what I do, it will only export the last PC that it ran though. It seems to run through all the PC's (tested with outputting to a txt file) but it will not log all the machines to a CSV. Can anyone give any advise?
$ArrComputers = "PC1", "PC2", "PC3"
foreach ($Computer in $ArrComputers) {
$Reachable = Test-Connection -Cn $Computer -BufferSize 16 -Count 1 -ea 0 -quiet
$Output = #()
#Is the machine reachable?
if($Reachable)
{
#If Yes, copy file
Copy-Item -Path "\\servername\filelocation" -Destination "\\$Computer\c$\Documents and Settings\All Users\Desktop\filename"
$details = "Copied"
}
else
{
#If not, don't copy the file
$details = "Not Copied"
}
#Store the information from this run into the array
$Output =New-Object -TypeName PSObject -Property #{
SystemName = $Computer
Reachable = $reachable
Result = $details
} | Select-Object SystemName,Reachable,Result
}
#Output the array to the CSV File
$Output | Export-Csv C:\GPoutput.csv
Write-output "Script has finished. Please check output files."
The problem is this:
#Store the information from this run into the array
$Output =New-Object -TypeName PSObject -Property #{
SystemName = $Computer
Reachable = $reachable
Result = $details
} | Select-Object SystemName,Reachable,Result
}
#Output the array to the CSV File
$Output | Export-Csv C:\GPoutput.csv
Each iteration of your foreach loop saves to $Output. Overwriting what was there previously, i.e., the previous iteration. Which means that only the very last iteration is saved to $Output and exported. Because you are running PowerShell v2, I would recommend saving the entire foreach loop into a variable and exporting that.
$Output = foreach ($Computer in $ArrComputers) {
New-Object -TypeName PSObject -Property #{
SystemName = $Computer
Reachable = $reachable
Result = $details
} | Select-Object SystemName,Reachable,Result
}
$Output | Export-Csv C:\GPoutput.csv
You would want to append the export-csv to add items to the csv file
Here is an example
foreach ($item in $ITGlueTest.data)
{
$item.attributes | export-csv C:\organization.csv -Append
}
Here you go. This uses PSCustomObject which enumerates data faster than New-Object. Also appends to the .csv file after each loop so no overwriting of the previous data.
foreach ($Computer in $ArrComputers) {
$Reachable = Test-Connection -Cn $Computer -BufferSize 16 -Count 1 -ea 0 -quiet
#Is the machine reachable?
if($Reachable)
{
#If Yes, copy file
Copy-Item -Path "\\servername\filelocation" -Destination "\\$Computer\c$\Documents and Settings\All Users\Desktop\filename"
$details = "Copied"
}
else
{
#If not, don't copy the file
$details = "Not Copied"
}
#Store the information from this run into the array
[PSCustomObject]#{
SystemName = $Computer
Reachable = $reachable
Result = $details
} | Export-Csv C:\yourcsv.csv -notype -Append
}

PSObject bug with specific parameter

I have a powershell script that does some simple auditing of group membership on remote servers. The output is as expected except in the case of one group.
There are two parameters two this script, an OU to check in AD and a Group name to check. The OU parameter returns a list of server names, the Group name is the group to return members on. This all works fine except in one case, Backup Operators.
param([parameter(mandatory=$true)][string]$region,[string]$group)
### Debug flag for viewing output when running the script.
$DEBUG = 1
$self = $myinvocation.mycommand.name
function cmdopts {
if ($DEBUG) {
write-host "$self running with options"
write-host "Region: $region"
write-host "Group: $group"
}
}
### Function to handle custom messages to the user.
function usageRegion {
# Removed for brevity
}
function usageGroups {
# Removed for brevity
}
### Cleanup from previous run of the script.
function cleanup {
# Removed for brevity
}
#### Function to load powershell modules at runtime
function loadmod {
param([string]$name)
if ( -not(get-module -name $name)) {
if (get-module -listavailable| where-object { $_.name -eq $name}) {
import-module -name $name
$true
} else {
$false
}
} else {
$true
}
}
### Main()
cmdopts
#### Validate commandline options
if ( "cnr","nwr","swr","ner","ser","emr","lar","apr" -notcontains $region ) {
usageRegion
exit
}
if ( "Administrators","Backup Operators","Event Log Readers","Hyper-V Administrators","Power Users",
"Print Operators","Remote Desktop Users" -notcontains $group) {
usageGroups
exit
} else {
### We are creating three files for each run, previous runs need to be cleaned up before we start.
cleanup
### The ActiveDirectory module is a dependency for this script, we use it to get a list of machine names from AD for the OU.
if ( loadmod -name "activedirectory" ) {
write-host "Loading ActiveDirectory powershell module..." -foregroundcolor green
} else {
write-host "Sorry, you do not have the ActiveDirectory powershell module installed." -foregroundcolor yellow
write-host "The script cannot contnue." -foregroundcolor yellow
exit
}
### Get the list of servers from AD for the OU specified by the user.
get-adcomputer -f * -searchbase "ou=$region,ou=servers,dc=domain,dc=com" | select name | out-file "c:\scripts\ps\$region.srvtmp.txt" -append
### We need to fix some format issues with the file before continuing
# Removed for brevity, cleans up the file output from get-adcomputer and sets variable $srvlist
$srvlist = gc "c:\scripts\ps\$region.srvlist.txt"
# Store for the return
$store = #()
# Fix the group string for the filename
$filestring = $group
$filestring = $filestring.replace(' ', '')
$filestring = $filestring.tolower()
foreach ( $srv in $srvlist ) {
if ( $srv -eq "bustedserver" ) {
# This box hangs and does not tear down WMI when it can't complete, timeout does not work
write-host "skipping $srv"
} else {
$response = test-connection $srv -count 1 -quiet
### This does not work super well, might have to try a custom function
if ($response -eq $false ) {
write-host "$srv was offline during test" -foregroundcolor darkmagenta
} else {
write-host "Checking $group on " -nonewline; write-host $srv -foregroundcolor cyan
$groupinfo = new-object PSObject
$members = gwmi -computer $srv -query "SELECT * FROM Win32_GroupUser WHERE GroupComponent=`"Win32_Group.Domain='$srv',Name='$group'`""
$members = $members | sort-object -unique
$count = 0
if ($members -ne $null) {
add-member -inputobject $groupinfo -membertype noteproperty -name "Server" -value $srv
add-member -inputobject $groupinfo -membertype noteproperty -name "Group" -value $group
foreach ($member in $members) {
$count += 1
$data = $member.partcomponent -split "\,"
$domain = ($data[0] -split "=")[1]
$name = ($data[1] -split "=")[1]
$line = ("$domain\$name").replace("""","")
add-member -inputobject $groupinfo -membertype noteproperty -name "Member $count" -value $line
}
}
if ($DEBUG) {
write-host $groupinfo
}
$store += $groupinfo
}
}
}
}
#$store | export-csv -path "$HOME\desktop\$region-$filestring-audit.csv" -notype
$store
If I run this script against a group like Administrators, or Remote Desktop Users the output looks like the following.
Server: SERVER1
Group: Remote Desktop Users
Member1: GroupName1
Member2: GroupName2
Member3: GroupName3
If I run this script against the group Backup Operators, I only get the first group even if there are many. In the debug write-host statement, it will show all of the groups. When printing the store, it only shows the first one. Even if there are two or more, it will alsways print...
Server: SERVER1
Group: Backup Operators
Member1: GroupName1
Any ideas on why this is broken specifically for 'Backup Operators' and not others would be appreciated.