Menu
  • HOME
  • TAGS

Get Average CPU utilization for test execution in powershell

Tag: powershell,cpu-usage,powershell-v3.0,scriptblock

Context:
I want to run a test, and while it is running to gather CPU utilization. Basically, when I start the test I also want to start collecting data for CPU utilization, at the end of the test I also want to stop collecting data for CPU utilization (and average it afterwards).
Using PowerShell 3 on a Win7

Approach:
At the beginning of the test I added a function that starts a background job. The background job executes a scriptblock that runs a 'while ($true)' loop that collects the Average CPU utilization and saves it to a file. At the end of the test I read the file, average the collected data and stop and remove the job.

Problems:
For the current approach, the scriptblock doesn't always get executed, and no new data gets gathered. If I run the test several times, the scriptblock gets executed (in one of the runs) - I can't think of anything that would be relevant or this behavior. Also the scriptblock always gets executed if I use breakpoints anywhere in the test.
Can't think of another approach.

Answers desired:
1. Why isn't the script block being executed? and how to get it to execute?
2. Is there another way to collect resource data for the duration of the test?

Please note that the code has been through various try and fail runs and is no longer 'pretty'.
Code:

function Start-ResourceMonitor
{
    param()
    [email protected]()
    $timestamp = Get-Date -Format o | foreach {$_ -replace ":", "."}
    $compName=$env:COMPUTERNAME
    $myFilePath = Join-Path -path $env:TEMP -childpath .\temp_$timestamp.txt
    $scriptBlock = {
        $avgSB = $args[0]
        $timestampSB = $args[1]
        while ($true) {
            $avgSB += Get-WmiObject win32_processor -computername $args[2] | Measure-Object -property LoadPercentage -Average | Foreach {$_.Average}            
            $avgSB | Out-File -FilePath $args[3] -Force
            start-sleep -Milliseconds 500 
        }
    }
    $res = start-job -RunAs32 -Name 'MyJob' -ScriptBlock $scriptBlock -ArgumentList @($avg,$timestamp,$compName,$myFilePath)
    while (($res.State -ne 'Running') -or (-not (Test-Path $myFilePath))){
        start-sleep -Milliseconds 500
    }
}

[other test functions]

function Stop-ResourceMonitor
{
    param()
    Stop-Job -Name MyJob
    $testFN = Get-ChildItem -Path $env:TEMP -Filter "temp*.txt" | sort LastWriteTime -Descending | select -First 1
    $global:CPU_Average = get-content -path $testFN.FullName
    $global:CPU_Average | Measure-Object -Average | select -ExpandProperty Average | Write-Host
    Remove-Job -Name MyJob
}

Best How To :

The underlying problem was that the test was running for anywhere between 2 and 60 seconds, and there where runs where the Get-WmiObject was taking longer than the test run, and thus the code for creating the file with the collected metrics wasn't executed for those runs.
Adding a wait loop, after starting the job, (while and sleep) for the job to actually start running and the files to get created solved the problem.
The code from the question has also been updated with the solution.

PS pipe WorkingSet as variable

variables,powershell

Use Select-Object -ExpandProperty to grab just a single property from the process: $WorkingSet = Get-Process spiceworks |Select-Object -First 1 -ExpandProperty WorkingSet if($WorkingSet -gt 120MB) { # Send email } ...

CPU usage missing from log for some processes

powershell

You can't get CPU for some processes because of insufficient rights. You get null value then. To output "Nothing" you have to compare the cpu value with $null, something like this: [email protected]{Expression={$_.ProcessName};Label="ProcessName";Width=40},@{Expression={$cpu=$_.CPU;if($cpu -eq $null){"Nothing";} else {$cpu;}};Label="CPU";Width=20} $ServiceTable = @{Expression={$_.Name};Label="Name";Width=40},@{Expression={$_.Status};Label="Status";Width=10} Get-Process | Sort-Object CPU -Descending | Select-Object ProcessName, CPU | format-table...

Get IP address of the Network Adapter of a computer having No gateway

powershell,ip-address,gateway

$configs=gwmi win32_networkadapterconfiguration | where {$_.ipaddress -ne $null -and $_.defaultipgateway -eq $null} if ($configs -ne $null) { $yourtargetIP= $configs[0].IPAddress[0] } # $yourtargetIP will have the IP address to make the gateway from In fact, should you have more than one IPv4 address on your network card, $configs[0].IPAddress will have them all,...

PowerShell XML formatting issue

xml,powershell

You're missing a set of parentheses (()) at the end of $XmlWriter.WriteEndElement: $xmlWriter.WriteStartElement("Disk$count") # Add tag for each drive $xmlWriter.WriteElementString("DriveLetter","$DriveLetter") # Write Drive Letter to XML $xmlWriter.WriteElementString("DriveSize","$DriveSize") # Write Drive Size to XML $xmlWriter.WriteElementString("DriveFreeSpace","$DriveFreeSpace") # Write Drive Free Space to XML $xmlWriter.WriteEndElement() # <-- Closing Drive Tag - don't forget...

What is the `.` shorthand for in a PowerShell pipeline?

powershell

. is the dot sourcing operator, which runs a script in the current scope rather than a new scope like call operator (i.e. &). That second segment invokes a script block and in that script block defines an advanced function. The advanced function iterates each item in the pipeline and...

Color a cell on the basis of another cell value

html,powershell,powershell-v2.0

You should format your HTML result with a different style if there's a condition. To do that, you declare a variable for data style that should be equal to $normalDataStyle if your condition is false, and a special style if it's true. $redDataStyle='style = "border: 1px solid black; background: #c00000;...

Programmatically accessing TFS history [closed]

c#,.net,powershell,tfs

Shai Raiten's Blog is great for learning the TFS API. For getting file history - read this post: http://blogs.microsoft.co.il/shair/2014/09/10/tfs-api-part-55-source-control-get-history/...

How to get stored procedure output parameter into variable using Powershell?

powershell,stored-procedures,output-parameter

Modify your script to be like below $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=myserver;Database=mydb;Integrated Security=True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = "testsp3" $SqlCmd.Connection = $SqlConnection $SqlCmd.CommandType = [System.Data.CommandType]'StoredProcedure'; <-- Missing $outParameter = new-object System.Data.SqlClient.SqlParameter; $outParameter.ParameterName = "@answer"; $outParameter.Direction =...

Increment Serial Number using EXIF

windows,powershell,command-line,exif,exiftool

You'll probably have to go to the command line rather than rely upon drag and drop as this command relies upon ExifTool's advance formatting. Exiftool "-SerialNumber<001-001-0001-${filesequence;$_=sprintf('%04d', $_+1 )}" <FILE/DIR> If you want to be more general purpose and to use the original serial number in the file, you could use...

View All Certificates On Smart Card

powershell,x509certificate

So, the main problem is actually that you're linking an x86 DLL into a x64 Powershell process. You can check whether your Powershell process is x64 like here (by querying (Get-Process -Id $PID).StartInfo.EnvironmentVariables["PROCESSOR_ARCHITECTURE"]), and if an x64 Powershell detected, start manually a Powershell (x86) located at $env:windir\syswow64\WindowsPowerShell\v1.0\powershell.exe with the same...

Enhancing the pipeline's content?

powershell,powershell-v3.0

Updating archive .\files.zip ... Compressing files.zip ? Check if your function has a case when adding Archive.zip to Archive.zip, this should throw a warning like copying over itself. About pipeline - I think you should employ -passthru switch, if the switch is present, return the archive as a Get-Item result...

Define an array with prefixes using the range operator

arrays,powershell

Would that do? @(4..9) | % {"usr" + $_} ...

Error with Get-ADUser: Invalid enumeration context

powershell,active-directory

The biggest issue you have here is you are asking a lot from Get-ADUser. Based on your comment you are pulling in over 900,000 accounts. On top of that you are pulling all properties of those users. There is a touch of insanity there. While I am not perfectly clear...

Powershell Invoke-Command with PSCredential Cannot process argument transformation on parameter 'Credential'

powershell,arguments,transformation,credentials,invoke-command

You have a mistake calling ImpersonateSql function. You should not use any parenthesis or commas for specifying parameters when calling function (unless you deliberately want to pass a subexpression or an array as an argument), it's not like C# or javascript function you are used to. Look at an example:...

Powershell Reading text file

powershell,text,text-files

To read the text after the # characters you must read the file content up to the # characters first. Also, in PowerShell you normally read files either line by line (via Get-Content) or completely (via Get-Content -Raw). You can discard thos parts of the read content that don't interest...

Disconnect Session via Powershell [closed]

session,powershell,user,server,disconnect

Powershell can use normal commands, this one should (according to manual) disconnect a given session: tsdiscon <ID> [/server:PC] [/V] [/VM] Pretty much the same as you use, just the executable is sifferent....

PowerShell Where-Object $_.name -like -in $list

powershell

The Where-Object FilterScript block is just a scriptblock that returns $true, $false or nothing - you can do all kinds of crazy things inside it, including looping over an array to see if there is a wildcard match in one of the entries: Where-Object { $ProductName = $_.Name $_.pscomputername -like...

Loop Issue - Remote Server

powershell

You never output $DRIVE anywhere, and the expression for $DRIVE shouldn't be in a scriptblock in the first place. The computer name is repeated several times, because you get the SystemName property for each logical disk object. Also, $OS gets the OS name for the local computer, not the remote...

Post messages from async threads to main thread in F#

.net,powershell,f#,system.reactive,f#-async

I ended up creating an EventSink that has a queue of callbacks that are executed on the main PowerShell thread via Drain(). I put the main computation on another thread. The pull request has the full code and more details. ...

Send email with body consisting of objects

email,powershell,foreach

Also if you want it to look more nice and readable you can do something like this that will spit it out in a table: $body += "<body><table width=""560"" border=""1""><tr>" $bodyArray[0] | ForEach-Object { foreach ($property in $_.PSObject.Properties){$body += "<td>$($property.name)</td>"} } $body += "</tr><tr>" $bodyArray | ForEach-Object { foreach ($property...

How do I write a loop to read text file and insert it to the database

sql-server,loops,powershell

To add a simple loop, you can use your existing AutoImportFlatFiles function like this: $Folder= $(read-host "Folder Location ('C:\Test\' okay)") foreach ($file in (get-childitem $Folder)) { $location = split-path $file.FullName -Parent $filename = (split-path $file.FullName -Leaf).split(".")[0] $extension = (split-path $file.FullName -Leaf).split(".")[1] AutoImportFlatFiles -location $location -file $filename -extension $extension -server "WIN123"...

Join SQL query Results and Get-ChildItem Results

sql-server,sql-server-2008,powershell

OK so if the SQL query does not have results then NULL is returned and, in essence, nothing is added to the $dbResults array. Instead lets append the results to a custom object. I don't know what PowerShell version you have so I needed to do something that I know...

PowerShell logic to remove objects from Array

arrays,powershell

How about not performing a remove, but just sort on tastecode descending and taking just one first result? $DuplicateMembers = $Fruits | Group-Object Name $DuplicateMembers | ForEach-Object { $Outcome = $_.Group | Sort-Object TasteCode -descending | Select -First 1 $Outcome } This way you should not bother to remove anything...

Powershell workflow - Get-Service not filtering

powershell,workflow

I have no idea why -Name [wildcard] works and -DisplayName [wildcard] doesn't (inside a workflow), but you can use Where-Object to accomplish the filtering if you like: workflow Restart-Services{ $services = Get-Service |Where-Object -FilterScript {$_.DisplayName -like "S*"} Foreach -Parallel ($svc in $services){ $name = $svc.Name Restart-Service -Name $name } }...

How to pass a switch variable?

powershell,parameter-passing

You can use splatting: $xtraOptions = @{} if ($NoPromptForPushPackageToNuGetGallery) { $xtraOptions.Add("NPFPPTNG",$true) } & "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" -Verbose -ProjectFilePath $project -PO "$packOptions" @xtraOptions If $xtraOptions is just an empty hashtable, @xtraOptions will simply have no effect on the parameters passed. You could also push all the parameters into the splatting table...

Using --check on a md5sum command generated checksum file is failing

powershell,cygwin,md5sum

Using the redirection operator to write the checksums to an output file causes the file to be created with the default encoding (Unicode). md5sum expects an ASCII file. Use Set-Content (or Out-File) to save the file with ASCII encoding: md5sum jira_defect.txt | Set-Content result.md5 -Encoding ASCII You can also work...

How to get current working directory inside a Cmdlet

c#,powershell,cmdlet

I am starting in C:\Users\<myusername>. If I know enter cd.. I am in C:\Users\ Entering (Get-Location).Path returns C:\Users. Thats what you want, isnt it? Altrnativly try: WriteObject(this.SessionState.Path.CurrentFileSystemLocation); Reference: How can I get the current directory in PowerShell cmdlet?...

Get list of files whose creation date is greater than some date time

powershell,windows-server-2012

Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" | Where-Object { $_.CreationTime -gt [datetime]"2014/05/28" } | Sort-Object CreationTime | Format-Table Name, CreationTime String is cast to datetime if you specify [datetime] before it. You can read about comparison operators by typing help about_Comparison_Operators in PowerShell console....

setting up azure ad certificate auth using powershell

powershell,azure,azure-active-directory

The 'value' field for the key credentials is always returned as 'null' for applications and service principals.

Filter and delete Registry values with Where-Object

powershell,registry

I think this issue is a matter of stepping back and taking a look at the bigger picture. You're focused on the value or a property, and how to get that property name that you aren't taking into consideration that the property is just a part of a larger object,...

Issue filtering out certain event logs from output

html,powershell

I think I see a couple of potential issues. If we have a look at a few event from my local computer. EventID InstanceId Message ------- ---------- ------- 1202 2147484850 Security policies were propagated with warning.... 0 0 The description for Event ID '0' in Source 'gupdate' cannot be found....

Powershell comparison of text file

powershell,readfile

Something to get you started: # $file1 will be an array with each element containing the line contents $file1 = get-content .\text1.txt # $file2 will be an array with each element containing the line contents just like $file1 $file2 = get-content .\text2.txt # This splits each line of $file2 on...

Remove all folders .old

powershell

Get-ChildItem produces a list of objects. Use a pipeline for processing that list: Get-ChildItem '\\kiewitplaza\vdi\Appsense_profiles' | Where-Object { $_.Name -like '*.old' } | Remove-Item ...

Turn environment variable into an array

powershell

Split the value of the environment variable at whatever delimiter is used. Example: PS C:\> $env:Path C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\ PS C:\> $a = $env:Path -split ';' PS C:\> $a C:\WINDOWS\system32 C:\WINDOWS C:\WINDOWS\System32\Wbem C:\WINDOWS\System32\WindowsPowerShell\v1.0\ PS C:\> $a.GetType().FullName System.String[] Edit: The PowerShell equivalent to bash code like this for a in ${MYARR[@]} ; do...

Why does piping Get-PSSession to Exit-PSSession not work?

powershell

You've not looked closely enough. Don't forget, it's easy to get all cmdlets related to a certain subject by doing something like this: Get-Help PSSession This gets a list of all cmdlets with "PSSession" it its name. If you carefully review the output, there's Exit-PSSession and Disconnect-PSSession, but there's one...

Get actual path from path with wildcard

powershell,if-statement

Sounds like you want Resolve-Path: if(($Paths = @(Resolve-Path "C:\Test6_*_15.txt"))){ foreach($file in $Paths){ # do stuff } } else { # Resolve-Path was unable to resolve "C:\Test6_*_15.txt" to anything } ...

Search for certain UPN suffix

powershell,active-directory

You use Get-ADUser and filter on user principal names that end with @sec213.com: $domain = ([adsi]'').distinguishedName $ou = "OU=users,OU=SEC213,OU=Uofguelph,$domain" $suffix = '@sec213.com' Get-ADUser -Filter "userPrincipalName -like '*$suffix'" -SearchBase $ou ...

Where is git command after installing “GitHub for Windows”? [closed]

windows,git,powershell,github,github-for-windows

After checking, it should under: %LocalAppData%\GitHub For example, in my PC, it is: C:\Users\xiaona\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin ...

How do I select a string from a string and replace it in powershell?

powershell

Not the best regex but this would be a good start. You aren't specific about what the line looks like so I will assume that it is on its own line with variable whitespace and or text. Get-ChildItem C:\temp\*.asp | ForEach-Object{ $file = $_.FullName (Get-Content $file) -replace '(.*UserRights\s*)"(.*?)"(.*)','$1("$2")$3' | Set-Content...

Testing for path in SysWOW64 returns true if path does not exist, but does exist in System32

excel,powershell,automation,system32,syswow64

Assuming: C:\Windows\SysWOW64\config\systemprofile\Desktop exists, but: C:\Windows\System32\config\systemprofile\Desktop does not. 64bit PowerShell: Test-Path C:\Windows\SysWOW64\config\systemprofile\Desktop True Test-Path C:\Windows\System32\config\systemprofile\Desktop False 32bit PowerShell: Test-Path C:\Windows\SysWOW64\config\systemprofile\Desktop True Test-Path C:\Windows\System32\config\systemprofile\Desktop True The second test in the 32bit PowerShell is redirected from system32 to syswow64. Checks for syswow64 are usually not...

PowerShell - Convert CSV to XLSX

powershell

What is the whole "gps" part of the script for? The two (gps excel -ErrorAction SilentlyContinue).count lines at the start and end of the script count the number of Excel executables running. gps is the shorthand alias for get-process. You can find out more by doing help gps which...

How to retrieve the name and path of VM's through powercli

powershell

If the text infront and including "Resources" is redundant then using a simple regex we can replacing it before it is output from your function. From $path to $path -replace "^.*?Resources/" So that would replace the similar line inside your function ( Where you return the property). We take everything...

Extract e-mail from grouped objects

powershell

Your second bit of code hurts my brain, but I think what you want is to output where multiple accounts use the same email address, grouped by email address. So, let's start with getting duplicates. Your first bit of code is kind of functional, but it really collects way more...

Why doesn't “go get gopkg.in/…” work while “go get github.com/…” OK?

windows,git,powershell,github,go

The root cause has been found: Because my computer use a web proxy, so I need to set proxy in environment variable: C:\Users\xiaona>set https_proxy=https://web-proxy.corp.hp.com:8080/ C:\Users\xiaona>set http_proxy=https://web-proxy.corp.hp.com:8080/ C:\Users\xiaona>go get -v gopkg.in/fatih/pool.v2 Fetching https://gopkg.in/fatih/pool.v2?go-get=1 Parsing meta tags from https://gopkg.in/fatih/pool.v2?go-get=1 (status code 200) get "gopkg.in/fatih/pool.v2": found meta tag main.metaImport{Prefix:"gopkg.in/fa tih/pool.v2", VCS:"git",...

Copy File Name to New File

powershell

Use Get-ChildItem and Where-Object to find the relevant files, pipe them to ForEach-Object and create a new file with New-Item: Get-ChildItem -Filter *.txt |Where-Object {$_.Name -match "\d{4}Backup\d{8}.txt"} |Foreach-Object { New-Item "$($_.Name).pgp.trg" -ItemType File } ...

win32_physicalMemory.Capacity returns null in powershell

windows,powershell

It's because with powershell 2.0 you can't access an array with that method. get-WmiObject win32_physicalMemory -Impersonation 3 -ComputerName "localhost" | select -expand capacity that will work the other powershell 2.0 computers you mention probably only have one stick of memory, so it doesn't return an array...

Format a command in powershell including a comma, can't find the right way to escape

powershell,batch-file,escaping,powershell-v2.0,comma

".\pacli DELETEUSER DESTUSER='"[email protected]`,com"' sessionid=333" You have double quotes in single quotes in double quotes, so the inner double quotes will terminate the string, so this will be parsed as three values: ".\pacli DELETEUSER DESTUSER='" [email protected]`,com "' sessionid=333" The answer is to escape, with a back tick (`), the inner...

Create powershell parameter default value is current directory

powershell,powershell-v3.0

Use PSDefaultValue attribute to define custom description for default value. Use SupportsWildcards attribute to mark parameter as Accept wildcard characters?. <# .SYNOPSIS Does something with paths supplied via pipeline. .PARAMETER Path Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.)....

How to create a powershell script that triggers a NuGet Update-Package –reinstall?

powershell,nuget-package

You should run the update command from nuget.exe. One of the parameters of the update command is FileConflictAction, which tells what action to take when asked to overwrite or ignore existing files referenced by the project: overwrite, Ignore, None. You might have to wrap everything in a powershell script, possibly...

Logging actual error when script fails

powershell,automation,error-logging

Change this: catch { $status = "FAILED" Write-Verbose "`tFailed to Change the administrator password. Error: $_" } to this: catch { $status = "FAILED" Write-Verbose "`tFailed to Change the administrator password. Error: $_" $errmsg = $_.Exception.Message } to preserve the error message(s). And change this: if($Status -eq "FAILED" -or $Isonline...