How do round memory size - powershell

I have this script line:
Get-WmiObject Win32_ComputerSystem | Select-Object TotalPhysicalMemory, #{Name="GB";Expression={$_.TotalPhysicalMemory/1GB}}
How to round this result 2 separate places after coma.
result at the moment is enter image description here

You can use the format string operator and specify the number of decimal places like this
Get-WmiObject Win32_ComputerSystem |
Select-Object TotalPhysicalMemory,
#{Name="GB";Expression={"{0:n2}" -f ($_.TotalPhysicalMemory/1GB)}}

Related

How do we grep for a value and store it in a variable in powershell?

I am new to powershell and writing a piece of script that will check for the size of the disk and calculate the free space. The code is as follows
$disk_space = Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object Size
$FreeSpace = Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object FreeSpace
$space_available = $disk_space - $FreeSpace
I am looking to have the variables calculated and print the space_available variable. The error I receive is as follows
InvalidOperation: Method invocation failed because [System.Management.Automation.PSObject] does not
contain a method named 'op_Subtraction'.
How can this be fixed?
You can't subtract a property with another property, you have to subtract the value of each property :) this is one way you can do what you want:
$disk_space = Get-CimInstance -ClassName Win32_LogicalDisk
$space_available = $disk_space.Size - $disk_space.FreeSpace
You can also then do:
[math]::Round($space_available / 1Gb,2)
To get the value in Gigabytes. Note 2 is the number of decimal points.

add string to calculated output in PowerShell

I am using a line of PowerShell to check RAM on a machine and it works great but I need to add a string to the output:
Get-CimInstance -class Win32_PhysicalMemory |
Measure-Object -Property capacity -Sum |
% {[Math]::Round(($_.sum / 1GB),2)}
This produces a result based on how much memory the machine has but I need to add "GB" to the end so the output is 16GB not just 16.
I have tried various things, none has worked. I guess I am struggling to understand how to add a string to the output of a calculated property.
(a) Use an expandable string (string interpolation):
Get-CimInstance -class Win32_PhysicalMemory |
Measure-Object -Property capacity -Sum |
% { "$([Math]::Round($_.sum / 1GB,2))GB" }
You can use $(...), the subexpression operator, to embed expressions and even multiple statements in a double-quoted string.
(b) Alternatively, use .NET string formatting via the -f operator:
Get-CimInstance -class Win32_PhysicalMemory |
Measure-Object -Property capacity -Sum |
% { '{0:G2}GB' -f ($_.sum / 1GB) }
The format string on the LHS must contain a placeholder for each RHS argument, starting with {0}; optionally, formatting instructions can be embedded in each placeholder, which in this case performs the desired rounding and displays up to 2 decimal places (G2).
The -f operator uses .NET's String.Format() method behind the scenes.
Important:
Method (a) always uses the invariant culture, in which . is the decimal mark.
Method (b) is culture-sensitive, so it uses the current culture's decimal mark (use Get-Culture to determine the current culture).
You can use the .ToString() Method and then add the GB
(Get-CimInstance -class Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | % {[Math]::Round(($_.sum / 1GB),2)}).ToString() + " GB"
hope its helps

Powershell on 2012 PrintServer searching for printer port with certain subnets

I am interning at a company and we need to redefine our client's printer IP schema. I'm fairly green with powershell and I am using Powershell ISE and when I use:
Get-PrinterPort
I get the full list as expected. However, if I am looking for any printer ports within the subnet set of 192.168.228.*, I have used the following:
$IPAddress = Get-WmiObject -Class Win32_TCPIPPrinterPort | Where-Object ({$_.Name.Split('.').index[-1]} -eq '228')
$IPAddress = Get-WmiObject -Class Win32_TCPIPPrinterPort | Where-Object ({$_.Name.Split('.')} -match '192.168.228*')
$IPAddress = Get-WmiObject -Class Win32_TCPIPPrinterPort | Where-Object ({$_.Name.Split('.').index[-1]} -match '228')
Nothing will display. I have tried many variations of the -match, -icontains, -contains, -like and several others that will search for the partial IP address
$IPAddress = Get-WmiObject -Class Win32_TCPIPPrinterPort | Where-Object ({$_.Name.Split('.')} -match '*228')
I have also modified the script to:
Get-WmiObject -Class Win32_TCPIPPrinterPort -OutVariable allIPs
foreach ($splitIP in $allIPs -split '.' ){
$splitIP = $allIPs -split '.'
sort $splitIP[2] -Unique -OutVariable uniqueSubnetIP
}
$uniqueSubnetIP
This is the output I get from the above code
Ultimately, I want to filter through each of the subnet IPs and locate the ones where the last octet are outside the schema and automate a process to put them in range like this:
< 192.268.***.50 || > 192.168.***.60
Any help you can offer is really appreciated; I've spent days trying to figure this out.
First, I wouldn't consider $printerport.name to be reliable for detecting subnets; use $printerport.hostaddress instead.
Get-WMIObject -Class Win32_TCPIPPrinterPort | Where-Object {($_.HostAddress -split '\.')[2] -eq 228} appears to return the printerport objects in the subnet you want - for a different subnet, just change the 228 to whatever the appropriate value is.
The -split operator takes a regular expression, so the . must be escaped, \.. The operation will result in an array of four items, representing the octets of the IP address of the port. The third octet is in #()[2]; you can test other octets similarly by changing the [2] to [0], [1], or [3].

Display drive letter with disk space

I'm just trying to display the drive letter with the freespace from this. I'm pretty sure I need to include it in the ForEach, but not sure how. Right now all I get is the free disk space.
Get-WMIObject Win32_LogicalDisk -Filter "DeviceID='C:' or DeviceID='D:' or DeviceID='L:'" | ForEach-Object {[math]::truncate($_.freespace / 1GB)}
33
33
33
Try this:
Get-WMIObject Win32_LogicalDisk -Filter "DeviceID='C:' or DeviceID='D:' or DeviceID='L:'" | Select DeviceID,#{N='FreeSpace';E={[math]::truncate($_.freespace / 1GB)}}
DeviceID FreeSpace
-------- ---------
C: 75
D: 0
Instead of ForEach-Object, use Select-Object and place your free space calculation inside a calculated property expression instead:
Get-WmiObject ...| Select-Object DeviceID,#{Name='FreeSpace';Expression={[math]::Truncate($_.FreeSpace / 1GB)}

powershell how to remove `{}#` from output. Is there a special command to do it?

I entered gwmi win32_product | select -property name | select -first 1 and output to a file. My result was #{name=Google Talk Plugin}.
How can I get rid of #{}, and name. I only want it to show Google Talk Plugin?
#{} means your exporting an object with properties. Try the -ExpandProperty parameter in Select-Object. You could also combine both select-object commands, like:
gwmi win32_product | select -expandproperty name -first 1
I ran into a problem similar with
$drive = Get-WmiObject Win32_LogicalDisk -ComputerName $servername | Select-Object DeviceID
$drive comes up as #{DeviceID=C:}, #{DeviceID=D:}, ...
Here is my brute force hack at it.
The second Trim statement was because for some reason if I put it in the first Trim it starts to Trim the letters in the Drive =D: becomes :
enter code here
$Asdrive = #() #declared before to get rid of null pointer issue, also to tell PS this is an array not a string
#Write-Host "Trimming for Get-WmiObject"
for($i=0;$i -lt $drive.length; $i++) {
[string]$sdrive = $drive[$i]
[string]$sdrive1 = $sdrive.Trim("#","{","}","D","e","v","i","c","e","I","D")
[string]$sdrive2 = $sdrive1.Trim("=")
$Asdrive += $sdrive2
}
If you're running at least Version 3, you can also use the member enumeration feature and then array slicing to take the first one, instead of using select:
(gwmi win32_product).name[0]
I add some code as I found this question with google.
Frode F. solution is the best one.
If you write out something like:
Get-ADComputer -Filter * -SearchBase $OU | Select-Object Name
you get a proper List of all Computers in an OU. You can also pipe that to a CVS/HTML file and its still nice.
| Export-CSV "mylist.csv"
But if you store it into a variable (array) every name will be wrapped in #{}.
In my case I needed computer names in a variable. Here is the solution thanks to Frodo:
$computerList = Get-ADComputer -Filter * -SearchBase $OU | Select-Object -ExpandProperty Name
Hope it helps someone.
(would add it as comment under the right solution, but I don't have enough reputation to do so)