What I was hoping to do is grab some windows counters and output it as something like this
ID, Hostname, Timestamp, CPU % usage, Disk I/O, network trafic, Memory %usage
What I want to see if once I take an hour or so sample, I am going to view it in splunk and chart it out to look for performance spikes and what not to troubleshoot performance issues. I pieced together a script from a few examples and it kind of works. I was wondering if anyone can help me with the output as I am fairly new to Powershell.
So here is the the example of the script:
param([string]$installpath, [string]$customerident, [string]$email, [string]$emailserver, [string]$server, [string]$role, [string]$test, [int]$delay, [int]$count, [string]$path)function Export-CSV {
[CmdletBinding(DefaultParameterSetName='Delimiter',
SupportsShouldProcess=$true, ConfirmImpact='Medium')]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[System.Management.Automation.PSObject]
${InputObject},
[Parameter(Mandatory=$true, Position=0)]
[Alias('PSPath')]
[System.String]
${Path},
#region -Append
[Switch]
${Append},
#endregion
[Switch]
${Force},
[Switch]
${NoClobber},
[ValidateSet('Unicode','UTF7','UTF8','ASCII','UTF32',
'BigEndianUnicode','Default','OEM')]
[System.String]
${Encoding},
[Parameter(ParameterSetName='Delimiter', Position=1)]
[ValidateNotNull()]
[System.Char]
${Delimiter},
[Parameter(ParameterSetName='UseCulture')]
[Switch]
${UseCulture},
[Alias('NTI')]
[Switch]
${NoTypeInformation})
begin
{
# This variable will tell us whether we actually need to append
# to existing file
$AppendMode = $false
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Export-Csv',
[System.Management.Automation.CommandTypes]::Cmdlet)
#String variable to become the target command line
$scriptCmdPipeline = ''
# Add new parameter handling
#region
if ($Append) {
$PSBoundParameters.Remove('Append') | Out-Null
if ($Path) {
if (Test-Path $Path) {
# Need to construct new command line
$AppendMode = $true
if ($Encoding.Length -eq 0) {
# ASCII is default encoding for Export-CSV
$Encoding = 'ASCII'
}
# For Append we use ConvertTo-CSV instead of Export
$scriptCmdPipeline += 'ConvertTo-Csv -NoTypeInformation '
# Inherit other CSV convertion parameters
if ( $UseCulture ) {
$scriptCmdPipeline += ' -UseCulture '
}
if ( $Delimiter ) {
$scriptCmdPipeline += " -Delimiter '$Delimiter' "
}
# Skip the first line (the one with the property names)
$scriptCmdPipeline += ' | Foreach-Object {$start=$true}'
$scriptCmdPipeline += '{if ($start) {$start=$false} else {$_}} '
# Add file output
$scriptCmdPipeline += " | Out-File -FilePath '$Path'"
$scriptCmdPipeline += " -Encoding '$Encoding' -Append "
if ($Force) {
$scriptCmdPipeline += ' -Force'
}
if ($NoClobber) {
$scriptCmdPipeline += ' -NoClobber'
}
}
}
}
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
if ( $AppendMode ) {
# redefine command line
$scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
$scriptCmdPipeline
)
} else {
# execute Export-CSV as we got it because
# either -Append is missing or file does not exist
$scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
[string]$scriptCmd
)
}
# standard pipeline initialization
$steppablePipeline = $scriptCmd.GetSteppablePipeline(
$myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Export-Csv
.ForwardHelpCategory Cmdlet
#>
}
param([string]$server, [string]$role, [string]$test, [int]$delay, [int]$count, [string]$path)
function CollectPerf {
param(
[string]$server,
[string]$role,
[string]$test,
[int]$delay,
[int]$count,
[string]$path
)
if ($role -eq "IOPS")
{
$counters = @(
"PhysicalDisk(*)\Disk Reads/sec",
"PhysicalDisk(*)\Disk Writes/sec"
)
}
if ($role -eq "general")
{
$counters = @(
"\Processor(*)\% Processor Time",
"\Memory\Page Faults/sec",
"\Memory\Available Bytes",
"\Paging File(_Total)\% Usage",
"\Paging File(_Total)\% Usage Peak",
"PhysicalDisk(*)\Avg. Disk sec/Read",
"PhysicalDisk(*)\Avg. Disk sec/Write",
"Network Interface(*)\Bytes Total/sec"
)
}
$sequence = 1;
$metrics = Get-Counter -ComputerName $server -Counter $counters -SampleInterval $delay -MaxSamples $count
foreach($metric in $metrics)
{
$obj = $metric.CounterSamples | Select-Object -Property Timestamp, CookedValue;
$obj | Add-Member -MemberType NoteProperty -Name Sequence -Value $Sequence -Force;
$obj | Add-Member -MemberType NoteProperty -Name LoadTest -Value $Test -Force;
$obj | Add-Member -MemberType NoteProperty -Name Computer -Value $Server -Force;
# export with unique file name
$obj | Export-Csv -Append -Path "$path$server.$test.csv" -NoTypeInformation;
$sequence += 1;
}
}
CollectPerf -server $server -role $role -test $test -delay $delay -count $count -path $path
$srcdir = "$path$server.$test.csv"
$zipFilename = "$server.$test.zip"
$zipFilepath = "$installpath\tmp\"
$zipFile = "$zipFilepath$zipFilename"
#"$srcdir"
#"$zipFilename"
#"$zipFilepath"
#"$zipFile"
#Prepare zip file
if(-not (test-path($zipFile))) {
set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipFile).IsReadOnly = $false
}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipFile)
$files = Get-ChildItem -Path $srcdir | where{! $_.PSIsContainer}
foreach($file in $files) {
$zipPackage.CopyHere($file.FullName)
#using this method, sometimes files can be 'skipped'
#this 'while' loop checks each file is added before moving to the next
while($zipPackage.Items().Item($file.name) -eq $null){
Start-sleep -seconds 1
}
}
$HOST.UI.RawUI.WindowsTitle = "BSTATS"
### email attachment
$file = "$path$server.$test.zip"
$mailboxdata = "$file"
$att = new-object Net.Mail.Attachment($file)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($emailserver)
$msg.From = "bstats-noreply@conestogac.on.ca"
$msg.To.Add($email)
$msg.Subject = "BSTATS data for $server"
$msg.Body = "Attached is the bstats data for $server."
$msg.Attachments.Add($att)
$smtp.Send($msg)
$att.Dispose()
Thanks everyone :-)