I'm trying to export just the numerical value for two performance counters to CSV. I've been able to get something built together but I still need some assistance.
$counter1 = "\\ygex01wal\SMTP Server(_total)\Messages Received Total"
$counter2 = "\\ygex01wal\SMTP Server(_total)\Messages Sent Total"
$data1 = Get-Counter $counter1
$data1cooked = $data1.countersamples | Select-Object cookedvalue
$data2 = Get-Counter $counter2
$data2cooked = $data2.countersamples | Select-Object cookedvalue
$object = New-Object PSObject
add-member -InputObject $object Noteproperty 'Received' $data1cooked
add-member -InputObject $object Noteproperty 'Sent' $data2cooked
$object | Export-Csv c:\csv.csv -NoTypeInformation
My csv ends up looking like:
"Received","Sent"
"#{CookedValue=2469610}","#{CookedValue=307718}"
I would prefer it to look like
"Received","Sent"
"2469610","307718"
Any suggestions on how I can get there?
Add the -expandproperty parameter to the select-object cmdlet.
excerpt:
$data1 = Get-Counter $counter1
$data1cooked = $data1.countersamples | Select-Object -expandproperty cookedvalue
$data2 = Get-Counter $counter2
$data2cooked = $data2.countersamples | Select-Object -expandproperty cookedvalue
Here's a blog post about that parameter:
http://powershellstation.com/2009/11/11/an-overlooked-parameter/
Related
I'm having some trouble copying data from 1 CSV and pasting it into a template of another one.
The template has specific column names.
and the csv file I have with the data, I'm able to get each column, but I am having trouble pasting it into a the template.
I'm trying to copy the following data from 1 csv to the template and here are the columns
email --> internal_customer_ID
givenname --> first_name
surname --> last_name
mail --> email_address
mobilephone --> mobile_phone_1
officePhone --> landline_phone_1
Here is my current code.
#Clear Screen
CLS
#The path we are working with (use the path where we execute this script from)
$global:path = Split-Path $script:MyInvocation.MyCommand.Path
$DataFile = $path + "\dataFile.csv"
$ExportedFileCSV = $path + "\PopulatedTemplate.csv"
#Export the data file with our user info
Get-ADGroupMember -Identity SomeGroup | Get-ADUser -Properties * | Select-Object -Property GivenName, SurName, Mail, MobilePhone, OfficePhone | Export-Csv -path $DataFile -NoTypeInformation -Force
$dataInput = Import-Csv $DataFile
$dataOutput = Import-Csv $ExportedFileCSV
$dataInput | ForEach-Object {
$newData = $_
$dataOutput |
Add-Member -MemberType NoteProperty -Name "internal_customer_ID" -Value $newData.Mail -PassThru -Force|
Add-Member -MemberType NoteProperty -Name "landline_phone_1" -Value $newData.OfficePhone -PassThru -Force|
Add-Member -MemberType NoteProperty -Name "email_address" -Value $newData.Mail -PassThru -Force|
Add-Member -MemberType NoteProperty -Name "mobile_phone_1" -Value $newData.MobilePhone -PassThru -Force|
Add-Member -MemberType NoteProperty -Name "last_name" -Value $newData.SurName -PassThru -Force|
Add-Member -MemberType NoteProperty -Name "first_name" -Value $newData.GivenName -PassThru -force
} | Export-CSV $ExportedFileCSV
If I can avoid exporting the datafile in the first place and just appending the result from the
Get-ADGroupMember -Identity SomeGroup | Get-ADUser -Properties * | Select-Object -Property GivenName, SurName, Mail, MobilePhone, OfficePhone
Straight to the csv template, that would work for my needs too, I just wasn't sure how to do that.
Your line reading $dataOutput | Add-Member ... is the problem, I think. Add-Member is for adding an attribute to a single object, but $dataOutput at this point is a collection of objects. I think the interpreter thinks you're trying add a member attribute to an object array.
Try creating a new object for each output record, then do an Export-CSV -append onto your output CSV file.
I think something like this should work:
$dataInput | ForEach-Object {
$newData = $_
$newRecordProperties = [ordered]#{
"internal_customer_ID"=$newData.Mail
"landline_phone_1" = $newData.OfficePhone
"email_address" = $newData.Mail
"mobile_phone_1" = $newData.MobilePhone
"last_name" = $newData.SurName
"first_name" = $newData.GivenName
}
$newRecord = new-object psobject -Property $newRecordProperties
Write-Output $newRecord
} | Export-CSV $ExportedFileCSV -Append
As long as the columns names in the output CSV are the same as your new record object, I think it should be okay. I am not sure what happens if the columns in $ExportedFileCSV are in a different order than the $newRecord being exported, so I added [ordered] to the hash table. You may want to test this yourself.
For the second part of your question, pipe-lining the whole thing, something like this is probably what you're after:
Get-ADGroupMember -Identity SomeGroup |
Get-ADUser -Properties * |
Select-Object -Property #(
#{label="internal_customer_ID"; expression={$_.Mail}}
#{label="email_address"; expression={$_.Mail}}
#{label="landline_phone_1"; expression={$_.OfficePhone}}
#{label="first_name"; expression={$_.GivenName}}
#{label="last_name"; expression={$_.SurName}}
#{label="mobile_phone_1"; expression={$_.MobilePhone}}
) |
Export-Csv $ExportedFileCSV -Append
Select-Object above creates a custom object with the attribute name and attribute value matching label and the result of expression. Again, re-order to match the order the CSV columns should be in.
I am trying to output different attributes of a Skype response group queue for documentation purpose.
I want to get Name, TimeoutThreshold, TimeoutAction , Timeouturi, OverflowThreshold, OverflowAction , OverflowCandidate as a .csv file header in row 1 and then the output to be entered in various columns from row 2.
I have tried below, but the formatting is really bad and the headers keep repeating. Can some one please help.
Also tried getting output in HTML, but no luck.
$p = Get-CsRgsQueue | Where-Object {$_.Name -like "IPL*"} | Select-Object Name
foreach ($Name in $p)
{
$q = Get-CsRgsQueue -Name "$Name"
$N = $q.Name
$TT = $q.TimeoutThreshold
$TA = $q.TimeoutAction.Action
$TAU = $q.TimeoutAction.uri
$OF = $q.OverflowThreshold
$OFA = $q.OverflowAction
$OFC = $q.OverflowCandidate
$out = New-Object PSObject
$out | Add-Member NoteProperty QueueName $N
$out | Add-Member NoteProperty Timeout $TT
$out | Add-Member NoteProperty TimeoutAction $TA
$out | Add-Member NoteProperty TransferURI $TAU
$out | Add-Member NoteProperty OverflowThreshhold $OF
$out | Add-Member NoteProperty OverflowAction $OFA
$out | Add-Member NoteProperty OverflowCandidate $OFC
$out | FT -AutoSize | Export-Csv C:\abc.csv -Append
}
I have tried below, but the formatting is really bad and the headers
keep repeating. Can some one please help.
That's because you pipe your objects through FT -AutoSize (Format-Table -AutoSize) - only ever use the Format-* cmdlets when you're about to show/present your data.
You can also save some time by only calling Get-CsRgsQueue once, piping it to ForEach-Object and finally construct a hashtable for the object properties:
Get-CsRgsQueue | Where-Object {$_.Name -like "IPL*"} | ForEach-Object {
New-object psobject -Property #{
QueueName = $_.Name
Timeout = $_.TimoutThreshold
TimeoutAction = $_.TimeoutAction.Action
TransferURI = $_.TimeoutAction.Uri
OverflowThreshhold = $_.OverflowThreshold
OverflowAction = $_.OverflowAction
OverflowCandidate = $_.OverflowCandicate
}
} |Export-Csv c:\abc.csv -NoTypeInformation
short solution of Mathias Jessen
Get-CsRgsQueue | where Name -like "IPL*" | %{
[pscustomobject] #{
QueueName = $_.Name
Timeout = $_.TimoutThreshold
TimeoutAction = $_.TimeoutAction.Action
TransferURI = $_.TimeoutAction.Uri
OverflowThreshhold = $_.OverflowThreshold
OverflowAction = $_.OverflowAction
OverflowCandidate = $_.OverflowCandicate
}
} | Export-Csv C:\result.csv -NoType
I'm working on a basic PowerShell script that inputs a pair of dates then gets all accounts with passwords expiring between those times. I'd like to output the data to the console in a way that is compatible with Export-Csv. That way the person running the script can either just view in the console, or get a file.
Here is my script:
[CmdletBinding()]
param(
[string]$StartDate = $(throw "Enter beginning date as MM/DD/YY"),
[string]$EndDate = $(throw "Enter end date as MM/DD/YY")
)
$start = Get-Date($StartDate)
$end = Get-Date($EndDate)
$low = $start.AddDays(-150)
$high = $end.AddDays(-150)
$passusers = Get-ADUser -Filter { PasswordLastSet -gt $low -and PasswordLastSet -lt $high -and userAccountControl -ne '66048' -and userAccountControl -ne '66080' -and enabled -eq $true} -Properties PasswordLastSet,GivenName,DisplayName,mail,LastLogon | Sort-Object -Property DisplayName
$accts = #()
foreach($user in $passusers) {
$passLastSet = [string]$user.PasswordLastSet
$Expiration = (Get-Date($passLastSet)).addDays(150)
$obj = New-Object System.Object
$obj | Add-Member -MemberType NoteProperty -Name Name -Value $user.DisplayName
$obj | Add-Member -MemberType NoteProperty -Name Email -Value $user.mail
$obj | Add-Member -MemberType NoteProperty -Name Expiration -Value $expiration
$accts += $obj
}
Write-Output ($accts | Format-Table | Out-String)
This prints to the console perfectly:
Name Email Expiration
---- ----- ----------
Victor Demon demonv#nsula.edu 1/3/2016 7:16:18 AM
However when called with | Export-Csv it doesn't:
#TYPE System.String
Length
5388
I've tried multiple variations using objects, and data tables, however it seems like I can only get it to work for console or for CSV, not for both.
Replace
Write-Output ($accts | Format-Table | Out-String)
with
$accts
That way your users can run your script any way they like, e.g.
.\your_script.ps1 | Format-Table
.\your_script.ps1 | Format-List
.\your_script.ps1 | Export-Csv
.\your_script.ps1 | Out-GridView
...
Format-Table | Out-String converts your output to a single string whereas Export-Csv expects a list of objects as input (the object properties then become the columns of the CSV). If Export-Csv is fed a string, the only property is Length, so you get a CSV with one column and one record.
$accts | ConvertTo-Csv | Tee -File output.csv | ConvertFrom-Csv
I'm trying to get a list of processes with heavy I/O Reads along with the associated ProductVersion. The code would look something like this:
$counter = "\Process*\IO Read Operations/sec"
get-counter | ? {$counter -gt 10} | gps | select name,productversion,reads
and the output would look something like this:
Name ProductVersion Reads
----- -------------- -----
p1 16.1.723.2342 15.98324
p2 12.3.234.1231 11.34323
I think you can use Format-Table
I am using a different counter for fetching result on my system. You can draw out an analogy and use accordingly :-
$Proc = Get-counter "\Process(*)\% processor time"
$Proc.CounterSamples | where {$_.instanceName -ne "idle"} | where {$_.instanceName -ne "_total"} | Format-Table -auto
Output:-
Path InstanceName CookedValue
---- ------------ -----------
\\angshuman\process(system)\% processor time system 1.54907723252374
\\angshuman\process(smss)\% processor time smss 0
\\angshuman\process(csrss#1)\% processor time csrss 1.54907723252374
To create a custom table from multiple sources you need to create an array and then pipe each variable as a new object:
$counter = "\Process*\IO Read Operations/sec"
$processes = gps | select id | ForEach {$_.id}
$ccounter = get-counter -listset process | get-counter -maxsamples 1 | select -expandproperty countersamples | where {$_.path -like $counter -and $_cookedvalue -eq $processes} | select cookedvalue | ForEach {$_.cookedvalue}
function Get-CounterValue ($mypid) { Code Here.... }
function GetProductVersion ($mypid) { ...code here... }
function GetProcessName ($mypid) { ...code here... }
$myresults = #()
$x = foreach ($procc in $processes) {
$thisname = GetProcessName $procc
$thisprod = GetProductVersion $procc
$thisread = GetCounterValue $procc
$robj = New-Object System.Object
$robj | Add-Member -type NoteProperty -name Name -value $thisname
$robj | Add-Member -type NoteProperty -name ProductVersion -value $thisprod
$robj | Add-Member -type NoteProperty -name Reads -value $thisread
$myresults += $robj
}
$myresults | ft -auto
I have a small script which retrieves the LastLogonTimestamp and the SAMAccount for all users in a particular OU in AD and converts the timestamp to a date and extracts just the date from the string. That part works fine. I then would like to output that to a CSV so it may be opened in Excel and be perfectly formated into columns and look all pretty.
I have tried ConvertTo-Csv and Export-Csv but have been uncuccessful. The problem is I am new to Powershell. This is my first script and I don't fully understand how this works. My script is probably terribly messy and illogical but it does the job so far.
Please help. Thanks.
$userlist = Get-ADUser -SearchBase "OU=IT,DC=whatever,DC=com,DC=au" -Filter * -Properties * | Select-Object -Property Name,LastLogonTimestamp,SAMAccountName | Sort-Object -Property Name
$userlist | ForEach-Object {
$last = $_.LastLogonTimestamp;
$ADName = $_.SAMAccountName;
$tstamp = w32tm /ntte $last;
if($tstamp.Length -lt "40"){}else
{
$ADDate = [DateTime]::Parse($tstamp.Split('-')[1]).ToString("dd/MM/yyyy")
write-host $ADDate;
write-host $ADName;
}
}
You will have to create objects for each user and pipe those to the Export-CSV cmdlet:
$usersList | %{
# current logic
$user = new-object psobject
$user | add-member -membertype noteproperty -name LastLogon -value $last
$user | add-member -membertype noteproperty -name ADName -value $ADName
$user | add-member -membertype noteproperty -name ADDate -value $ADDate
$user
} | export-csv test.csv -notype
Alternative syntax for populating the object:
$properties = #{"LastLogon" = $last; "ADName" = $ADName; "ADDate" = $ADDate}
$user = new-object psobject -property $properties