script get cpu use & ram every x hours, write to file

This topic contains 9 replies, has 4 voices, and was last updated by  Vern Anderson 3 years, 6 months ago.

  • Author
    Posts
  • #13074

    Jake Sully
    Participant

    Howdy,
    I'm trying to get this script to write to a csv file and then append to it, but also add in a column with the date/time that the information was captured. I want to schedule this as a task to run as I have to provide this info for mgmt. I can't use our monitoring tool as it doesn't have historical data capabilities yet...

    I've been able to get this function running, but I know I can make it better, I'd like to put in the get-content for a list of servers in the top of the function and I'm just stuck as to what to do to move that part to the top of the function, and then do an export to a csv, add that column with date/time, and append to the csv or excel file (in a perfect world an excel sheet per server) would be ideal.

    Thank you all, this is a fantastic learning resource and a great group of people!

    function Get-ResourceUse {
    param(
    [Parameter(Mandatory=$true, Position=0,
    ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [ValidateNotNull()]
    [string[]]$ComputerName
    )

    process {
    foreach ($c in $ComputerName) {
    $avg = Get-WmiObject win32_processor -computername $c |
    Measure-Object -property LoadPercentage -Average |
    Foreach {$_.Average}
    $mem = Get-WmiObject win32_operatingsystem -ComputerName $c |
    Foreach {"{0:N2}" -f ((($_.TotalVisibleMemorySize – $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize)}
    #new-object psobject -prop @{ # Work on PowerShell V2 and below
    [pscustomobject] [ordered] @{ # Only if on PowerShell V3
    ComputerName = $c
    AverageCpu = $avg
    MemoryUsage = $mem
    #PercentFree = $free
    }
    }
    }
    }

    cat '.\servers.txt' | Get-resourceuse | Format-Table

  • #13075

    Don Jones
    Keymaster

    So you need to start by adding the current date time (Get-Date) to your PSCustomObject.

    Stop formatting it as a table. You can't export a table to a CSV.

    Pipe Get-ResourceUse to Export-CSV. Specify the -Append parameter.

    You shouldn't need to add a "Get-Content for a list of servers in the top of the function;" the function is already properly accepting pipeline input. You can pipe Get-Content to it. That's how the shell likes it.

  • #13076

    Dave Wyatt
    Moderator

    You may be reinventing the wheel here; this look a lot like a basic Data Collector Set that you could create and schedule in perfmon.msc.

  • #13077

    Jake Sully
    Participant

    Thank you both, Don I appreciate it, does this look right, because I can't get it to accept the get-content, I tried importing the function as a module, that fails, then I also tried just get-content | .\get-resourceuse and I get ".\get-resourceuse is unknown".

    Dave – I know 🙂 But we aren't "allowed today at least to turn on perfmon", but if you have any other suggestions, I'd like to hear them....This is reinventing the wheel, I was hoping to use the get-counter info with perfmon, but we can't enable it, quite literally.

    Get-Content c:\temp\servers.txt | Get-ResourceUse | Export-CSV -Append -NoTypeInformation c:\temp\test.csv

    function Get-ResourceUse {
    param(
    [Parameter(Mandatory=$true, Position=0,
    ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
    [ValidateNotNull()]
    [string[]]$ComputerName
    )

    process {
    foreach ($c in $ComputerName) {
    $avg = Get-WmiObject win32_processor -computername $c |
    Measure-Object -property LoadPercentage -Average |
    Foreach {$_.Average}
    $mem = Get-WmiObject win32_operatingsystem -ComputerName $c |
    Foreach {“{0:N2}” -f ((($_.TotalVisibleMemorySize – $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize)}
    #new-object psobject -prop @{ # Work on PowerShell V2 and below
    [pscustomobject] [ordered] @{ # Only if on PowerShell V3
    ComputerName = $c
    AverageCpu = $avg
    MemoryUsage = $mem
    #PercentFree = $free
    }
    }
    }
    }

  • #13078

    Don Jones
    Keymaster

    If you're putting this in a script file, then you can't run it like that. It needs to be saved as a script module, in the correct directory for those, so that PowerShell can find it when you try to run Get-ResourceUse.

    When you run the script as-is, you're defining the function. That's all. Not running it. Look into script modules.

    And "not allowed to turn on PerfMon" is absolutely retarded. Those performance counters are running whether you "turn on" the PerfMon console or not, and the "solution" you're building it going to produce more overhead and higher negative impact than using perf counters would. My suggestion would, frankly, be to fire the idiot who came up with that policy. Refusing to use the native features of the OS, and instead using something vastly more impactful, is dumb. Sounds like a horrible place to work.

  • #13079

    Dave Wyatt
    Moderator

    Fair enough; if you aren't allowed to use perfmon for some reason, this should be a reasonable substitute.

    Your code looks fine to me, though you need to have the function defined before you call it, in PowerShell. If your file looks exactly like that, then you need to move the line that starts with "Get-Content" down after the end of the function.

  • #13080

    Jake Sully
    Participant

    Hi Don (your books and vids are awesome, I at least understand now what you are referring to, never having been a scripted or programmer, I'm learning a ton!!). Been in IT a long time, 15 years and PowerShell is the biggest dive I've taken, batch files and old kixstart scripts I just did basics.

    I agree entirely and tried to explain this, sent out documentation proving the counters run, etc...it's not a bad place, just lots of people who are running the show that don't have any idea how technology works. However I did want to ask about the counters because I've seen issues with perfmon consuming a lot of CPU, but only when someone set up a large set of criteria and left it running for a couple days. I've read many instances of that online as well, but then used it without issues. I know it's improved in 2008-2012, I had seen a couple issues in 2003. So is it correct it's when someone is really gathering to much data? Here's one link I got sent back today when debating this, and I know it's a lousy source, but today's been a headache overall 🙂 . processlibrary.com/en/directory/files/perfmon/29094/

    As for the script, I've hit the function issues a few times. I've read about using the dot-source method, then about importing as a module, and then read that you don't have to do either, what is the best way to use a function if you are using it in a single command, and I scraped this together from examples, but got stuck trying to just turn it into a script, I know functions are good for re-use, but how could I make this a script?

  • #13081

    Jake Sully
    Participant

    Dave,
    Thanks, I tried doing the get-content at the bottom and it fails.

    It comes back with an error that the computer name param is empty.

    How would you guys do this – aside from perform?

    My goal now is to use perfmon and then export to a file. Would you use powershell to get the data from the counters or just use perfmon straight up?

    I'm trying to use powershell as much as possible.

  • #13083

    Don Jones
    Keymaster

    You do either have to dot source or make the script into a module. One or the other. If you want to just run it as a script, remove the function keyword, function name, and opening and closing curly bracket. It'll run the same as a script.

  • #13092

    Vern Anderson
    Participant

    One word "PAL" PAL is also PowerShell underneath but using perfmon to accomplish a very human readable and comprehensive report.

    http://msdn.microsoft.com/en-us/library/cc296652(v=bts.10).aspx

You must be logged in to reply to this topic.