Mount Point comparison - powershell

I have a PowerShell function that pulls the free space on a mounted volume. Ideally I would like to take the results and do a If comparison on the value.
If the results equal true I would write that to a text file. This will allow me to use REGEX through a monitoring tool to create a trouble ticket.
I am having issues doing any comparisons on the results. Here is a snip of the code.
$FreePerc = #{name="Free(%)";expression={[Math]::Round(((($_.FreeSpace / 1073741824)/($_.Capacity / 1073741824)) * 100),0)}}
function Get-Mountpoints {
$volumes = Get-WmiObject -Computer localhost Win32_Volume |
Where-Object {$_.DriveLetter -eq $null}
$volumes | Select $FreePerc | Write-Output
}
The Get-Mountpoints function returns the correct results but I have been unable to run any comparison on it.

Related

PowerShell script to calculate the memory usage per user

We have an environment of 240 VMs. Clients are using ICA/RDP connection to connect to these servers. Sometimes users are hogging the memory and causing the slowing and crash on that particular server.
I would like to have a PowerShell script to calculate the memory usage for each user connected to the server. I spent hours and hours searching and trying different scripts but was not successful.
Some scripts giving me the working sets value using Get-WmiObject Win32_Process and GetOwner(). but the calculation is not correct.
What I need is exactly the format that I can see in the users tab in Task Manager. The main information which I need is the memory usage, but it would be nice to have the disk and CPU usage per user as well.
Here is the code which i am using. When i run this script after a minute or two It returns an error which says $.GetOwner() can not be found and in another line it gives me the user name which utilizing the memory more than the others but the calculation is not correct when i compare it with TaskManager user's tab.
$h = #{}
get-wmiobject win32_process | foreach {
$u = $_.getowner().user;
if ( $u -ne $null)
{
if ( !$h.ContainsKey($u) )
{
$h.add( $u, $_.WS);
}
else
{
$h.item($u) = $h.item($u) + $_.WS;
}
}
}
$h.GetEnumerator() | sort value -desc
try this:
get-wmiobject win32_process |
select #{N='User';E={$_.getowner().user}}, WorkingSetSize |
group user |
select Name, #{N='CPU';E={($_.Group.WorkingSetSize | Measure-Object -Sum).Sum / 1Mb }}
gwmi win32_process |
select #{N='User';E={$_.getowner().user}},WorkingSetSize |
group User | select Name,#{N='RAM';E={[math]::Round(($_.Group.WorkingSetSize | Measure-Object -Sum).Sum/1MB) }} |
sort RAM -Descending | select -first 1 ;

Powershell Process CPU checking

Have the following which works OK, but with an in issue in PowerShell:
$FileName = "E:\Work\ps\Inventory.htm"
$serverlist = "E:\Work\ps\Monitored_computers.txt"
foreach ($server in Get-Content $serverlist)
{
$servern=$server.split(",")[0]
$ip=$server.split(",")[1]
$cpu = gwmi Win32_PerfFormattedData_PerfProc_Process -Computer $servern -filter "Name <> '_Total' and Name <> 'Idle'" | Sort-Object PercentProcessorTime -Descending | where { $_.PercentProcessorTime -gt 0 }| select -First 1
if ($cpu.PercentProcessorTime -ge "92") {
write-host $servern ' ' $cpu.Name ' ' $cpu.PercentProcessorTime
}
}
I have seen some other code in PowerShell, that takes an Average but almost seems like an "average of an average" - which is meaningless. And, this is for overall CPU Usage
gwmi win32_processor | Measure-Object -property LoadPercentage -Average | Foreach {$_.Average}
Now, if we can take the same logic and apply for our process issue:
gwmi Win32_PerfFormattedData_PerfProc_Process | Sort-Object PercentProcessorTime -Descending | where { $_.PercentProcessorTime -gt 0 } | select -First 1 | Measure-Object -property PercentProcessorTime -Average | Foreach {$_.PercentProcessorTime}
What am trying to ask is: I do get the CPU Percentage, which seems to be a "point in time". How do locate the true CPU Percentage? This is why I am pointing out the average. I really want to get around the "point in time" part of this.
The point being, when we have seen on several occasions, a high CPU per process on a server, we login to the server and the high CPU has subsided. This is not to say, this has been each time, but we know that sometimes a CPU will spike and then quiet down.
Thanks for any insight!
First issue, you are stuck at a Point In Time because when you execute your script it captures a snapshot of what is happening right then and there. What you are looking for is historical data, so you can figure out the average CPU usage of processes over a set amount of time, and pinpoint the process that's bogging down your CPU. Do you have performance monitors in place to track CPU usage for individual processes? You may need to setup performance logging if you want to be able to get the numbers you're looking for after the fact.
Secondly, I think that you misunderstand how Measure-Object works. If you run Get-Help on the cmdlet and check the Output you'll see that it outputs a GenericMeasureInfo object. This object will have a property for the relevant stat that you are looking for, which in your case is the Average property. It is not an average of an average, the most common usage I see for it is to calculate something, like a Sum or Average, and then output the value of that property.
Let's try a simple example...
Find the average size of the files in a folder. First we use Get-ChildItem to get a collection of files, and pipe it to Measure-Object. We will specify the -Average argument to specify that we want the Average calculated, and -Property length, so that it knows what to average:
GCI C:\Temp\* -file | Measure-Object -Average -Property length
This outputs a GenericMeasureInfo object like this:
Count : 30
Average : 55453155
Sum :
Maximum :
Minimum :
Property : Length
That lets me know that it had 30 files piped to it, and it found the Average for the Length property. Now, sometime you want to calculate more than one thing, so you can use more than one argument, such as -Sum and -Maximum, and those values will be populated as well:
Count : 30
Average : 55453155
Sum : 1663594650
Maximum : 965376000
Minimum :
Property : Length
So it looks like my average file is ~55MB, but out of the 1.6GB in the whole folder I've got one file that's 965MB! That file is undoubtedly skewing my numbers. With that output I could find folders that have multiple files, but one file is taking up over half of the space for the folder, and find anomalies... such as the ISO that I have saved to my C:\temp folder for some reason. Looks like I need to do some file maintenance.
Thanks to #TheMadTechnician I have been able to sort this out. I had a wrong component with
$_.Average
where I had
$_.PercentProcessorTime
and that would never work. Here is the correct script:
$serverlist = "D:\Work\ps\Monitored_computers.txt"
foreach ($server in Get-Content $serverlist) {
$servern=$server.split(",")[0]
$ip=$server.split(",")[1]
$cpu = gwmi Win32_PerfFormattedData_PerfProc_Process -Computer $ip | `
Where-Object {$_.Name -like "*tomcat*"} | `
Measure-Object -property PercentProcessorTime -Average | `
Foreach {$_.Average}
if ($cpu -ge "20") {
write-host $servern $cpu ' has a tomcat process greater than 20'
}
}

Powershell select-string using -inputobject for HV replication

I'm trying to write a query of the replication status of our VMs. I would like to be more selective in what I'm looking for, however.
I can run this:
PS C:\Users\hc> Get-VMReplication -computername servername
and it'll return this:
Image 1
I'd like it to return the line in the list when there is a match, or nothing when there isn't. Ive so far gotten it to select an item from the list by writing it as this:
PS C:\Users\hc> ((Get-VMReplication -computername servername | select-string -inputobject {$_.Health} -pattern “Normal”) -like “Normal”)
but it unfortunately only displays a list of Normal:
Image 2
Ultimately I would like it it to list the column headings and the entire row if possible but I'm unsure as to where to go next. (note that I've used the "Normal" pattern just so it would create entries in this list. The final product will look for "Warning" and "Critical")
Don't use Select-String, use Where instead.
Get-VMReplication -computername servername | Where{ $_.Health -eq "Normal"}
Or later down the road it would look like:
Get-VMReplication -computername servername | Where{ $_.Health -eq "Warning" -or $_.Health -eq "Critical"}

Powershell free disk space for drives without drive letter

I am working on a power shell script based on http://www.powershellneedfulthings.com/?p=36 to check the disk space for volumes that do not have a driver letter assigned.
The script works pretty well, but I'd like to filter that only drives are shown that have less than 10% free disk space. I'm running into troubles using the where-object filter with hash tables.
# calculations for displaying disk size information
$TotalGB = #{Name="Capacity(GB)";expression={[math]::round(($_.Capacity/ 1GB),2)}}
$FreeGB = #{Name="FreeSpace(GB)";expression={[math]::round(($_.FreeSpace / 1GB),2)}}
$FreePerc = #{Name="Free(%)";expression={[math]::round(((($_.FreeSpace / 1GB)/($_.Capacity / 1073741824)) * 100),0)}}
# array declarations
$volumes = #()
# import server names to check
$servers = (Get-Content .\servers.txt)
# check disk space for volumes without drive letter
foreach ($server in $servers){
$volumes += Get-WmiObject -computer $server win32_volume | Where-Object {$_.DriveLetter -eq $null -and $_.Label -ne "System Reserved"}
}
$volumes | Select SystemName, Label, $TotalGB, $FreeGB, $FreePerc | Format-Table -AutoSize
What I tried is:
Where-Object {$FreePerc -le 10}
The current output is:
SystemName Label Capacity(GB) FreeSpace(GB) Free(%)
---------- ----- ------------ ------------- ----
SERVER01 X:\data\ 9.97 0.89 9
SERVER01 X:\log\ 9.97 1.20 12
SERVER01 X:\info\ 9.97 3.49 35
I'd like to only show the volumes that have less than 10% free disk space. So in this case, only the first entry should be shown.
Thanks!
I think the where clause variable $FreePerc is the issue. Arco had the right idea.
$volumes | Select SystemName, Label, $TotalGB, $FreeGB, $FreePerc | Where-Object {$_.'Free(%)' -le 10} | Format-Table -AutoSize
I put the property in single quotes because i think PowerShell would try to evaluate (%) otherwise. Also to make Arco's solution work it might just be easier to call the Name propery of $FreePerc. That way you only have to update one location
$volumes | Select SystemName, Label, $TotalGB, $FreeGB, $FreePerc | Where-Object {$_.($FreePerc.Name) -le 10} | Format-Table -AutoSize

Change powershell script to output without ellipses (...)

I need some help with the output of the following script so the output doesn't show with the ellipses (...).
I tried to insert | Format-Table -Wrap -AutoSize but I just can't seem to get it right.
clear-host Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
$services = new-object system.collections.sortedlist
$servers = (get-spfarm).servers
foreach ($server in $servers) {
foreach($service in $server.serviceinstances)
{
if ($service.status = "Online")
{
$s = $service.typename
if ($services.contains($s))
{
$serverlist = $services[$s]
$servername = $server.name
$services[$s] = "$serverlist - $servername"
}
else
{
$services[$s] = $server.name
}
}
} }
$services
output:
Name Value
---- -----
Access Database Service SE5APP - SE5FE - SE7FE - FAQ3
Application Discovery **and L...** SE5APP - SE5FE - SE7FE - FAQ3
Application Registry Service SE5APP - SE5FE - SE7FE - FAQ3
Either Format-List (fl) or Format-Table -auto (ft -auto) should help here.
$services | fl
OR
$services | ft -auto
I came across this post and would like to add some information, as the accepted solution did not resolve my problem and I'm sure others may find the following information useful:
Quick Story: Running commands using Microsoft Online Services Module with Powershell, much of the results were continually be retrieved as truncated with data cutoff and missing as an ellipsis (...).
The fix: As explained in this post by Greig, I inevitably came to the conclusion $FormatEnumerationLimit=-1 is the unlimate solution to the problem. Using any variant of Format-Wide, Format-List, Format-Table, Format-Custom, -AutoSize, Out-String -Width, etc. require a hefty amount of additional considerations/code. In the case where all you want is to see all the data being returned, regardless of columns, arrays, etc., $FormatEnumerationLimit=-1 ensures you will get everything and you don't need to mess around.
Additional information, as credited in Greig's post include:
PowerShell Quick Tip: Creating wide tables with PowerShell, where the author explains:
If you have a specific property that contains a collection of items,
that property may still show an ellipsis in the file produced here if
the number of items in that collection exceeds the number assigned to
the built-in $FormatEnumerationLimit variable.
...and that "passing the results to | Format-Table -Property * [will] show all of the columns." But content from the columns may still be truncated ("PowerShell truncates table output by default"), and that even using | Format-Table -Property * -AutoSize will be limited by your screen buffer
("Auto-sized tables are limited to the width of your screen buffer"). The solution offered, before the absolute $FormatEnumerationLimit=-1, seems to be using | Format-Table -Property * -AutoSize in conjunction with | Out-String -Width 4096 or whatever width you require.
Using Format Commands to Change Output View provides some more delailed documentation on the Format cmdlets: Format-Wide, Format-List, and Format-Table.
What I do in this situation is to create a format description then use that as an argument to my Format-Table command. I've developed a function (Get-MaxLength) to examine the data field with the longest data (helps to have this at the end of the format description) and set the width in the format description with the value it returns. You can see the calculations in the code below. Notice the Number value for the Intel(4) Management Engine Interface. Also notice the use of -Wrap on the Format-Table command. This concept can be modified to calculate all fields widths or just the last one, it's just a little math.
Function Get-MaxLength {
<#
.SYNOPSIS
Finds the length of the longest item in collection.
.DESCRIPTION
Use this Function to get the length of the longest item in a
collection for use in format strings or other places where
needed.
.PARAMETER TestObj
The qualified object to be tested. See example!
.Parameter MinLen
The minimum length of the item (if using for formatting) which
should be the Label (title) length. Note if the object item
being tested does not have a Length property you MUST specify
the label length!
.OUTPUTS
Returns a numerical value
.EXAMPLE
$NameLen = Get-MaxLength -TestObj $DotNet.PSChildName
$VerLen = Get-MaxLength -TestObj $DotNet.Version
$RNLen = Get-MaxLength -TestObj $DotNet.Release -MinLen 11
#--- .Net Information ---
$fmtDotNet =
#{Expression={$_.PSChildName};Label=".Net Type";Width=$NameLen},
#{Expression={$_.Version};Label="Version No:";Width=$VerLen},
#{Expression={$_.Release};Label="Release No:";Width=$RNLen}
$Dotnet | Format-Table $fmtDotNet
#>
Param(
[Parameter(Mandatory=$True)]
[object] $TestObj,
[Parameter(Mandatory=$False)]
[int] $MinLen = 0,
[Parameter(Mandatory=$False)]
[int] $MaxLen = 0
)
$ErrorActionPreference = "SilentlyContinue"
foreach ($x in $TestObj) {
If ($x.Trim().length -gt $MinLen) {
$MinLen = $x.Trim().length
}
}
If ($MaxLen -ne 0) {
If ($MinLen -gt $MaxLen) {
$MinLen = $MaxLen
}
}
$ErrorActionPreference = "Continue"
Return ,$MinLen
} #End Function ----------- Get-MaxLength -------------------
$OstrWidth = 80
$DriverInfo =
Get-CimInstance -ClassName 'Win32_PNPSignedDriver' |
Where-Object -Property DriverProviderName -ne "Microsoft" |
Where-Object -Property DeviceName -ne -Value $Null |
Sort-Object -Property DeviceName -Unique
$DriverCnt = $DriverInfo.Count
$DVLen =
Get-MaxLength -TestObj $DriverInfo.DriverVersion -MinLen 14
$DDLen = $OstrWidth - $DVLen
$fmtDRVR = #{Label="`nDriver Description";Width=$DDLen;
Expression={$_.DeviceName}},
#{Label="Version Number"; Width=$DVLen;
Expression={$_.DriverVersion}}
$DrvTitle = "$($DriverCnt) Non-Windows Unique Drivers and " +
"Version Numbers:" | Out-String
$DriverInfo =
$DriverInfo | Format-Table -Property $fmtDRVR -Wrap |
Out-String -Width $OStrWidth
Sample Output:
Driver Description Number
------------------- -------------
Alcor Micro USB 2.0 Card Reader 2.0.150.10135
ASMedia USB3.1 eXtensible Host Controller 1.16.42.1
...
Intel(R) HD Graphics 630 21.20.16.4550
Intel(R) Management Engine Interface 1914.12.0.125
6
Intel(R) Ready Mode Technology Device 1.2.0.0
...
Realtek Audio 6.0.1.8248
Samsung NVMe Controller 3.0.0.1802