I want to add Used space column in my powershell script? - powershell

I want to make some changes to below script .
try{
$space = Get-WmiObject Win32_logicaldisk `
| Format-Table DeviceID,`
#{Name="Size(GB)";Expression={[decimal]("{0:N0}" -f($_.size/1gb))}}, `
#{Name="Free Space(GB)";Expression={[decimal]("{0:N0}" -f($_.freespace/1gb))}}, `
#{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}} `
-AutoSize
}
catch
{
echo "Exception Occurred. Please try again on $servername"
}
echo "The total space on $servername are given below:"
echo $space
I want to add a column which shows used space without any changes to output format.
output is below:
The total space on are given below:
DeviceID Size(GB) Free Space(GB) Free (%)
-------- -------- -------------- --------
A: 0 0
C: 60 41 69 %
D: 100 78 78 %
E: 200 190 95 %
G: 0 0

You can extend the table as follows
try
{
$space = Get-WmiObject Win32_logicaldisk | Format-Table DeviceID,
#{Name="Size(GB)";Expression={[decimal]("{0:N0}" -f($_.size/1gb))}},
#{Name="Free Space(GB)";Expression={[decimal]("{0:N0}" -f($_.freespace/1gb))}},
#{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}},
#{Name="Used Space(GB)";Expression={[decimal]("{0:N0}" -f($_.size/1gb - $_.freespace/1gb))}},
#{Name="Used Space (%)";Expression={"{0,6:P0}" -f(($_.size/1gb - $_.freespace/1gb) / ($_.size/1gb))}}
-AutoSize
}
catch
{
echo "Exception Occurred. Please try again on $servername"
}
echo "The total space on $servername are given below:"
echo $space

I found the answer myself,refer to below code:
$servername = hostname
#checking for disk space
try{
$space = Get-WmiObject Win32_logicaldisk `
| Format-Table DeviceID,`
#{Name="Size(GB)";Expression={[decimal]("{0:N0}" -f($_.size/1gb))}}, `
#{Name="Free Space(GB)";Expression={[decimal]("{0:N0}" -f($_.freespace/1gb))}}, `
#{Name="Used Space(GB)";Expression={[decimal]("{0:N0}" -f(($_.size/1gb) - ($_.freespace/1gb)))}}, `
#{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}} `
-AutoSize
}
catch
{
echo "Exception Occurred. Please try again on $servername"
}
echo "The total space on $servername are given below:"
echo $space
The desired result required was :
The total space on sw02014 are given below:
DeviceID Size(GB) Free Space(GB) Used Space(GB) Free (%)
-------- -------- -------------- -------------- --------
A: 0 0 0
C: 60 41 18 69 %
D: 100 78 22 78 %
E: 200 190 10 95 %
G: 0 0 0

Related

Get Column values from text file

Below is the text file data I have
Disk ### Status Size Free Dyn Gpt
-------- ------------- ------- ------- --- ---
Disk 0 Online 100 GB 1024 KB
Disk 1 Online 6144 MB 1024 KB
Disk 2 Online 200 GB 1024 KB
Disk 3 Online 10 GB 1024 KB
I want to put this data in csv like below, removing the last 2 columns and adding the server value
server Disk ### Status Size Free
------ -------- ------------- ------- -------
s1 Disk 0 Online 100 GB 1024 KB
s1 Disk 1 Online 6144 MB 1024 KB
s1 Disk 2 Online 200 GB 1024 KB
s1 Disk 3 Online 10 GB 1024 KB
below is the code
$list = Get-Content -Path "C:\server.txt"
foreach($server in $list)
{
$diskpart = cmd /c 'echo list disk | diskpart'
}
$Lines = $diskpart
$Out = $False
$Line=#()
ForEach ($Line In $Lines)
{
If ($Line -match 'DISKPART>')
{
$Out = $False
}
If ($Out -eq $True)
{
$Line | Out-File "C:\d.txt" -Append
}
If ($Line -match 'DISKPART>')
{
$Out = $True
}
}
$data = Import-Csv -Path C:\d.txt
I tried reading line using foreach,but getting output with headers and ---
Disk ### Status Size Free Dyn Gpt
---------------------------------------------------
Disk 0 Online 100 GB 1024 KB
Please let me know how can I extract columns from text file and append the servername to it. Need some idea to do this
One way of converting this into a CSV file is like below.
Assuming you have the output from diskpart in a string array $lines and the current server is called 's1' :
$result = switch -Regex ($lines) {
'^\s*Disk \d' {
$disk,$status,$size,$free = $_.Trim() -split '\s{2,}'
[PsCustomObject]#{
'Server' = $server # 's1' in this example
'Disk ###' = $disk
'Status' = $status
'Size' = $size
'Free' = $free
}
}
}
# output on console screen
$result | Format-Table -AutoSize
# output to CSV file
$result | Export-Csv -Path 'C:\diskinfo.csv' -NoTypeInformation
Result on screen:
Server Disk ### Status Size Free
------ -------- ------ ---- ----
s1 Disk 0 Online 100 GB 1024 KB
s1 Disk 1 Online 6144 MB 1024 KB
s1 Disk 2 Online 200 GB 1024 KB
s1 Disk 3 Online 10 GB 1024 KB
P.S. It is strongly not recommended to use Out-File to build a CSV file. Use that only if other options are not available. To create CSV use Export-Csv
If you need to do this on a series of computers, you might use this:
$list = Get-Content -Path "C:\server.txt"
# parameter -ComputerName can handle an array of computer names at once
$lines = Invoke-Command -ComputerName $list -ScriptBlock { "list disk" | diskpart }
$result = switch -Regex ($lines) {
'^On computer: (\w+)' { $server = $Matches[1].Trim() }
'^\s*Disk \d' {
$disk,$status,$size,$free = $_.Trim() -split '\s{2,}'
[PsCustomObject]#{
'Server' = $server
'Disk ###' = $disk
'Status' = $status
'Size' = $size
'Free' = $free
}
}
}
# output on console screen
$result | Format-Table -AutoSize
# output to CSV file
$result | Export-Csv -Path 'C:\diskinfo.csv' -NoTypeInformation

Combine `Get-Disk` info and `LogicalDisk` info in PowerShell (but with formatted output)

This is a question about an answer for this Combine `Get-Disk` info and `LogicalDisk` info in PowerShell?
Here is the answer which I've tried to change to get the output formatted how I want it:
https://stackoverflow.com/a/31092004/8262102
It needs to work for multiple drives like the code below only in the desired format.
This is the code with all the details on what my attempts are to do so:
$info_diskdrive_basic = Get-WmiObject Win32_DiskDrive | ForEach-Object {
$disk = $_
$partitions = "ASSOCIATORS OF " + "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " + "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
Get-WmiObject -Query $partitions | ForEach-Object {
$partition = $_
$drives = "ASSOCIATORS OF " + "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " + "WHERE AssocClass = Win32_LogicalDiskToPartition"
Get-WmiObject -Query $drives | ForEach-Object {
[PSCustomObject][Ordered]#{
Disk = $disk.DeviceID
DiskModel = $disk.Model
Partition = $partition.Name
RawSize = '{0:d} GB' -f [int]($partition.Size/1GB)
DriveLetter = $_.DeviceID
VolumeName = $_.VolumeName
Size = '{0:d} GB' -f [int]($_.Size/1GB)
FreeSpace = '{0:d} GB' -f [int]($_.FreeSpace/1GB)
}
}
}
}
# Here's my attempt at formatting the output of the code above.
# 1. This trims the dead whitespace from the output.
$info_diskdrive_basic = ($info_diskdrive_basic | Out-String) -replace '^\s+|\s+$', ('')
# 2. I then separate the DiskModel, RawSize, DriveLetter, VolumeName, FreeSpace with the regexp below so this becomes:
# Disk Model, Raw Size, Drive Letter, Volume Name, Free Space
$info_diskdrive_basic = ($info_diskdrive_basic) -replace '(?-i)(?=\B[A-Z][a-z])', (' ')
# 3. Here I then format the string to how I want:
$info_diskdrive_basic = ($info_diskdrive_basic) -replace '(.+?)(\s+):\s*(?!\S)', ($id2 + '$1:$2 ')
$info_diskdrive_basic
The output should look like this:
I want to format the properties and the values like so: Properties: >spaces< value where the value is over to the right and aligned along the left of them
# Disk: \\.\PHYSICALDRIVE0
# Disk Model: Crucial_CT512MX100SSD1
# Partition: Disk #0, Partition #2
# Raw Size: 476 GB
# Drive Letter: C:
# Volume Name:
# Size: 476 GB
# Free Space: 306 GB
But my output ends up like this: (Notice how the text is not aligned)
# Disk: \\.\PHYSICALDRIVE0
# Disk Model: Crucial_CT512MX100SSD1
# Partition: Disk #0, Partition #2
# Raw Size: 476 GB
# Drive Letter: C:
# Volume Name:
# Size: 476 GB
# Free Space: 306 GB
To output the info as you apparently need, we need to know the maximum line length (which in your example is 79 characters) and work our way from that.
$maxLineLength = 79 # counted from the longest line in your example
$maxValueLength = 0 # a counter to keep track of the largest value length in characters
$info_diskdrive_basic = Get-WmiObject Win32_DiskDrive | ForEach-Object {
$disk = $_
$partitions = "ASSOCIATORS OF " + "{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " + "WHERE AssocClass = Win32_DiskDriveToDiskPartition"
Get-WmiObject -Query $partitions | ForEach-Object {
$partition = $_
$drives = "ASSOCIATORS OF " + "{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " + "WHERE AssocClass = Win32_LogicalDiskToPartition"
Get-WmiObject -Query $drives | ForEach-Object {
$obj = [PSCustomObject]#{
'Disk' = $disk.DeviceID
'Disk Model' = $disk.Model
'Partition' = $partition.Name
'Raw Size' = '{0:d} GB' -f [int]($partition.Size/1GB)
'Drive Letter' = $_.DeviceID
'Volume Name' = $_.VolumeName
'Size' = '{0:d} GB' -f [int]($_.Size/1GB)
'Free Space' = '{0:d} GB' -f [int]($_.FreeSpace/1GB)
}
# get the maximum length for all values
$len = ($obj.PsObject.Properties.Value.ToString().Trim() | Measure-Object -Property Length -Maximum).Maximum
$maxValueLength = [Math]::Max($maxValueLength, $len)
# output the object to be collected in $info_diskdrive_basic
$obj
}
}
}
# sort the returned array of objects on the DriveLetter property and loop through
$result = $info_diskdrive_basic | Sort-Object DriveLetter | ForEach-Object {
# loop through all the properties and calculate the padding needed for the output
$_.PsObject.Properties | ForEach-Object {
$label = '# {0}:' -f $_.Name.Trim()
$padding = $maxLineLength - $maxValueLength - $label.Length
# output a formatted line
"{0}{1,-$padding}{2}" -f $label, '', $_.Value.ToString().Trim()
}
# add a separator line between the disks
''
}
# output the result on screen
$result
# write to disk
$result | Set-Content -Path 'X:\theResult.txt'
# format for HTML mail:
'<pre>{0}</pre>' -f ($result -join '<br>')
Example output:
# Disk: \\.\PHYSICALDRIVE1
# Disk Model: Samsung SSD 750 EVO 250GB
# Partition: Disk #1, Partition #0
# Raw Size: 232 GB
# Drive Letter: C:
# Volume Name: System
# Size: 232 GB
# Free Space: 160 GB
# Disk: \\.\PHYSICALDRIVE2
# Disk Model: WDC WD7501AALS-00J7B0
# Partition: Disk #2, Partition #0
# Raw Size: 699 GB
# Drive Letter: D:
# Volume Name: Data
# Size: 699 GB
# Free Space: 385 GB
P.S. with creating [PsCustomObject], there is no need to add [Ordered]
Using your posted code as is, 'stringify' your properties
For example:
($info_diskdrive_basic = Get-WmiObject Win32_DiskDrive |
ForEach-Object {
$disk = $_
$partitions = "ASSOCIATORS OF " +
"{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +
"WHERE AssocClass = Win32_DiskDriveToDiskPartition"
Get-WmiObject -Query $partitions |
ForEach-Object {
$partition = $_
$drives = "ASSOCIATORS OF " +
"{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +
"WHERE AssocClass = Win32_LogicalDiskToPartition"
Get-WmiObject -Query $drives |
ForEach-Object {
[PSCustomObject][Ordered]#{
Disk = "$($disk.DeviceID)"
DiskModel = "$($disk.Model)"
Partition = "$($partition.Name)"
RawSize = "$('{0:d} GB' -f [int]($partition.Size/1GB))"
DriveLetter = "$($_.DeviceID)"
VolumeName = "$($_.VolumeName)"
Size = "$('{0:d} GB' -f [int]($_.Size/1GB))"
FreeSpace = "$('{0:d} GB' -f [int]($_.FreeSpace/1GB))"
}
}
}
})
# Results
<#
Disk : \\.\PHYSICALDRIVE0
DiskModel : Samsung SSD 950 PRO 512GB
Partition : Disk #0, Partition #0
RawSize : 477 GB
DriveLetter : D:
VolumeName : Data
Size : 477 GB
FreeSpace : 364 GB
...
#>
Point of note:
I am using PowerShell variable squeezing to assign the results to the variable and output to the screen at the same time.
Update
As for this...
"I want to format the properties and the values like so: Properties: >spaces< value"
$Spacer = ("`t")*8
($info_diskdrive_basic = Get-WmiObject Win32_DiskDrive |
ForEach-Object {
$disk = $_
$partitions = "ASSOCIATORS OF " +
"{Win32_DiskDrive.DeviceID='$($disk.DeviceID)'} " +
"WHERE AssocClass = Win32_DiskDriveToDiskPartition"
Get-WmiObject -Query $partitions |
ForEach-Object {
$partition = $_
$drives = "ASSOCIATORS OF " +
"{Win32_DiskPartition.DeviceID='$($partition.DeviceID)'} " +
"WHERE AssocClass = Win32_LogicalDiskToPartition"
Get-WmiObject -Query $drives |
ForEach-Object {
[PSCustomObject][Ordered]#{
Disk = "$Spacer$($disk.DeviceID)"
DiskModel = "$Spacer$($disk.Model)"
Partition = "$Spacer$($partition.Name)"
RawSize = "$Spacer$('{0:d} GB' -f [int]($partition.Size/1GB))"
DriveLetter = "$Spacer$($PSItem.DeviceID)"
VolumeName = "$Spacer$($PSItem.VolumeName)"
Size = "$Spacer$('{0:d} GB' -f [int]($PSItem.Size/1GB))"
FreeSpace = "$Spacer$('{0:d} GB' -f [int]($PSItem.FreeSpace/1GB))"
}
}
}
})
# Results
<#
Disk : \\.\PHYSICALDRIVE0
DiskModel : Samsung SSD 950 PRO 512GB
Partition : Disk #0, Partition #0
RawSize : 477 GB
DriveLetter : D:
VolumeName : Data
Size : 477 GB
FreeSpace : 364 GB
...
#>

Extract columns from text based table output

qfarm /load command shows me the load from my servers.
Output:
PS> qfarm /load
Server Name Server Load Load Throttling Load Logon Mode
-------------------- ----------- -------------------- ------------------
SERVER-01 400 0 AllowLogons
SERVER-02 1364 OFF AllowLogons
SERVER-03 1364 OFF AllowLogons
SERVER-04 1000 0 AllowLogons
SERVER-05 700 0 AllowLogons
SERVER-06 1200 0 AllowLogons
I need to display only first column (Server Name) and the second one (Server Load) and loop through them, in order to make some logic later, but it seems the powershell doesn't see it as object with properties:
PS> qfarm /load | Select -ExpandProperty "Server Name"
Select-Object : Property "Server Name" cannot be found.
Is there any other possibility, like a table or something?
One way to do this is to build objects out of the command's output. Tested the following:
#requires -version 3
# sample data output from command
$sampleData = #"
Server Name Server Load Load Throttling Load Logon Mode
-------------------- ----------- -------------------- ------------------
SERVER-01 400 0 AllowLogons
SERVER-02 1364 OFF AllowLogons
SERVER-03 1364 OFF AllowLogons
SERVER-04 1000 0 AllowLogons
SERVER-05 700 0 AllowLogons
SERVER-06 1200 0 AllowLogons
"# -split "`n"
$sampleData | Select-Object -Skip 2 | ForEach-Object {
$len = $_.Length
[PSCustomObject] #{
"ServerName" = $_.Substring(0, 22).Trim()
"ServerLoad" = $_.Substring(22, 13).Trim() -as [Int]
"LoadThrottlingLoad" = $_.Substring(35, 22).Trim()
"LogonMode" = $_.Substring(57, $len - 57).Trim()
}
}
In your case, you should be able to replace $sampleData with your qfarm load command; e.g.:
qfarm /load | Select-Object -Skip 2 | ForEach-Object {
...
Of course, this is assuming no blank lines in the output and that my column positions for the start of each item is correct.
PowerShell version 2 equivalent:
#requires -version 2
function Out-Object {
param(
[Collections.Hashtable[]] $hashData
)
$order = #()
$result = #{}
$hashData | ForEach-Object {
$order += ($_.Keys -as [Array])[0]
$result += $_
}
New-Object PSObject -Property $result | Select-Object $order
}
# sample data output from command
$sampleData = #"
Server Name Server Load Load Throttling Load Logon Mode
-------------------- ----------- -------------------- ------------------
SERVER-01 400 0 AllowLogons
SERVER-02 1364 OFF AllowLogons
SERVER-03 1364 OFF AllowLogons
SERVER-04 1000 0 AllowLogons
SERVER-05 700 0 AllowLogons
SERVER-06 1200 0 AllowLogons
"# -split "`n"
$sampleData | Select-Object -Skip 2 | ForEach-Object {
$len = $_.Length
Out-Object `
#{"ServerName" = $_.Substring(0, 22).Trim()},
#{"ServerLoad" = $_.Substring(22, 13).Trim() -as [Int]},
#{"LoadThrottlingLoad" = $_.Substring(35, 22).Trim()},
#{"LogonMode" = $_.Substring(57, $len - 57).Trim()}
}
You can easily convert your table to PowerShell objects using the ConvertFrom-SourceTable cmdlet from the PowerShell Gallery:
$sampleData = ConvertFrom-SourceTable #"
Server Name Server Load Load Throttling Load Logon Mode
-------------------- ----------- -------------------- ------------------
SERVER-01 400 0 AllowLogons
SERVER-02 1364 OFF AllowLogons
SERVER-03 1364 OFF AllowLogons
SERVER-04 1000 0 AllowLogons
SERVER-05 700 0 AllowLogons
SERVER-06 1200 0 AllowLogons
"#
And than select your columns like:
PS C:\> $SampleData | Select-Object "Server Name", "Server Load"
Server Name Server Load
----------- -----------
SERVER-01 400
SERVER-02 1364
SERVER-03 1364
SERVER-04 1000
SERVER-05 700
SERVER-06 1200
For details see: ConvertFrom-SourceTable -?
The ConvertFrom-SourceTable cmdlet is available for download at the PowerShell Gallery and the source code from the GitHub iRon7/ConvertFrom-SourceTable repository.
Command-line utilities return their outputs as a string array. This should work:
qfarm /load | ForEach-Object { $_.Substring(0,33) }
I have answered something very similar to this in the past. I have a larger function for this but a simplified on work on left aligned string table just as you have shown in you example. See the linked answer for more explanation.
function ConvertFrom-LeftAlignedStringData{
param (
[string[]]$data
)
$headerString = $data[0]
$headerElements = $headerString -split "\s{2,}" | Where-Object{$_}
$headerIndexes = $headerElements | ForEach-Object{$headerString.IndexOf($_)}
$results = $data | Select-Object -Skip 2 | ForEach-Object{
$props = #{}
$line = $_
For($indexStep = 0; $indexStep -le $headerIndexes.Count - 1; $indexStep++){
$value = $null # Assume a null value
$valueLength = $headerIndexes[$indexStep + 1] - $headerIndexes[$indexStep]
$valueStart = $headerIndexes[$indexStep]
If(($valueLength -gt 0) -and (($valueStart + $valueLength) -lt $line.Length)){
$value = ($line.Substring($valueStart,$valueLength)).Trim()
} ElseIf ($valueStart -lt $line.Length){
$value = ($line.Substring($valueStart)).Trim()
}
$props.($headerElements[$indexStep]) = $value
}
New-Object -TypeName PsCustomObject -Property $props
}
return $results
}
$qfarmOutput = qfarm /load
ConvertFrom-LeftAlignedStringData $qfarmOutput | select "Server Name","Server Load"
This approach is based on the position of the header fields. Nothing is hardcoded and it is all custom built based on those indexes and field names. Using those $headerIndexes we carve up every line and place the results, if present, into its respective column. There is logic to ensure that we don't try and grab any part of the string that might not exist and treat the last field special.
Results
Server Name Server Load
----------- -----------
SERVER-01 400
SERVER-02 1364
SERVER-03 1364
SERVER-04 1000
SERVER-05 700
SERVER-06 1200

PowerShell Script to set the size of pagefile.sys

How to set the size of Page File on Windows(pagefile.sys) via PowerShell?
This is how we can update the size of pagefile.sys via PowerShell:
# PowerShell Script to set the size of pagefile.sys
$computersys = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges;
$computersys.AutomaticManagedPagefile = $False;
$computersys.Put();
$pagefile = Get-WmiObject -Query "Select * From Win32_PageFileSetting Where Name like '%pagefile.sys'";
$pagefile.InitialSize = <New_Value_For_Size_In_MB>;
$pagefile.MaximumSize = <New_Value_For_Size_In_MB>;
$pagefile.Put();
Execute the script as below:
PS> .\update_pagefile_size.ps1;
HERE is the solution
THIS is to set C VOL page file to 16384MB, static and D VOL page file to System managed:
# PowerShell Script to set the size of pagefile.sys
# update_pagefile_size.ps1
$pagefile = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges
$pagefile.AutomaticManagedPagefile = $false
#$pagefile.put() | Out-Null
Gwmi win32_pagefilesetting | where{$_.caption -like 'C:*'}
$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'C:*'}
$pagefileset.InitialSize = 16384
$pagefileset.MaximumSize = 16384
$pagefileset.Put() | Out-Null
if((Set-WmiInstance -Class Win32_PageFileSetting -Arguments #{name="C:\pagefile.sys";InitialSize = $pagefileset.InitialSize; MaximumSize = $pagefileset.MaximumSize} -EnableAllPrivileges -Verbose) -icontains "already exists"){
$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'C:*'}
$pagefileset.Delete()
$pagefileset.InitialSize = 16384
$pagefileset.MaximumSize = 16384
Set-WmiInstance -Class Win32_PageFileSetting -Arguments #{name="C:\pagefile.sys";InitialSize = $pagefileset.InitialSize; MaximumSize = $pagefileset.MaximumSize} -EnableAllPrivileges
Gwmi win32_pagefilesetting | where{$_.caption -like 'C:*'}
}
$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'D:*'}
$pagefileset.InitialSize = 0
$pagefileset.MaximumSize = 0
$pagefileset.Put() | Out-Null
Gwmi win32_pagefilesetting | where{$_.caption -like 'D:*'}
Set-WmiInstance -Class Win32_PageFileSetting -Arguments #{name="D:\pagefile.sys";InitialSize = 0; MaximumSize = 0} -EnableAllPrivileges | Out-Null
Write-host "Don't forget to reboot"
#shutdown /r /t 120 /c "rebooting to fix pagefile"
Well, to GET the pagefile with Powershell use this function I got from Mike Kanakos: "function-getpagefilessize.ps1", which, for some reason, does not work from the profile as a PS file or PSM file:
Function Get-PageFileInfo {
<#
.Synopsis
Returns info about the page file size of a Windows computer. Defaults to local machine.
.Description
Returns the pagefile size info in MB. Also returns the PageFilePath, PageFileTotalSize, PagefileCurrentUsage,
and PageFilePeakusage. Also returns if computer is using a TempPafeFile and if the machine's pagefile is
managed by O/S (AutoManaged = true) or statically set (AutoManaged = False)
.Example
Get-PageFileInfo -computername SRV01
Returns pagefile info for the computer named SRV01
Computer : SRV01
FilePath : C:\pagefile.sys
AutoManagedPageFile : True
TotalSize (in MB) : 8192
CurrentUsage (in MB) : 60
PeakUsage (in MB) : 203
TempPageFileInUse : False
.Example
Get-PageFileInfo SRV01, SRV02
Returns pagefile info for two computers named SRV01 & DC02.
Computer : SRV01
FilePath : C:\pagefile.sys
AutoManagedPageFile : True
TotalSize (in MB) : 8192
CurrentUsage (in MB) : 60
PeakUsage (in MB) : 203
TempPageFileInUse : False
Computer : SRV02
FilePath : C:\pagefile.sys
AutoManagedPageFile : True
TotalSize (in MB) : 8192
CurrentUsage (in MB) : 0
PeakUsage (in MB) : 0
TempPageFileInUse : False
.Example
Get-PageFileInfo SRV01, SRV02, SRV03 | Format-Table
Returns pagefile info for three computers named SRV01, SRV02 & SRV03 in a table format.
Computer FilePath AutoManagedPageFile TotalSize (in MB) CurrentUsage (in MB) PeakUsage (in MB) TempPageFileInUse
-------- -------- ------------------- ----------------- -------------------- ----------------- -----------------
SRV01 C:\pagefile.sys True 8192 60 203 False
SRV02 C:\pagefile.sys True 13312 0 0 False
SRV03 C:\pagefile.sys True 2432 0 0 False
.Parameter computername
The name of the computer to query. Required field.
.Notes
NAME: Get-PageFileInfo
AUTHOR: Mike Kanakos
Version: v1.1
LASTEDIT: Thursday, August 30, 2018 2:19:18 PM
.Link
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
[string[]]$ComputerName
)
# Main Part of function
Foreach ($computer in $ComputerName)
{
$online= Test-Connection -ComputerName $computer -Count 2 -Quiet
if ($online -eq $true)
{
$PageFileResults = Get-CimInstance -Class Win32_PageFileUsage -ComputerName $Computer | Select-Object *
$CompSysResults = Get-CimInstance win32_computersystem -ComputerName $computer -Namespace 'root\cimv2'
$PageFileStats = [PSCustomObject]#{
Computer = $computer
FilePath = $PageFileResults.Description
AutoManagedPageFile = $CompSysResults.AutomaticManagedPagefile
"TotalSize(in MB)" = $PageFileResults.AllocatedBaseSize
"CurrentUsage(in MB)" = $PageFileResults.CurrentUsage
"PeakUsage(in MB)" = $PageFileResults.PeakUsage
TempPageFileInUse = $PageFileResults.TempPageFile
} #END PSCUSTOMOBJECT
} #END IF
else
{
# Computer is not reachable!
Write-Host "Error: $computer not online" -Foreground white -BackgroundColor Red
} # END ELSE
$PageFileStats
} #END FOREACH
} #END FUNCTION
#AUTHOR: Mike Kanakos#
But setting the page file then runs into ALL kinds of issues. Like, it gets REAL buggy. IF it is set you can change it, if it is not, you must first set to system managed and then set to something, like 16384/16384 on C and System managed on D:.
I am working on the answer myself, because I need this, and I will get back to ya'll when I get it sorted (amongst my long list of other scripts to do)...
But, ITMT, the function will help. Do a ForEach to a list like this:
remove-item -Force volumeletter:\folder\outputfile.txt
$results = (Get-PageFileInfo -Verbose server1.domain,server2.domain |select * |format-table -AutoSize)
$results |out-file volumeletter:\folder\outputfile.txt -Force ascii
OR you load up the Function in ISE, run it to load into memory and then query each server manually from the PS cmd:
Get-PageFileInfo server1.domain
Computer : server1.domain
FilePath : {C:\pagefile.sys, D:\pagefile.sys}
AutoManagedPageFile : False
TotalSize(in MB) : {16384, 768}
CurrentUsage(in MB) : {88, 62}
PeakUsage(in MB) : {120, 84}
TempPageFileInUse : {False, False}
You will see blanks if you are required to use FQDN...
IF you have the standard system managed the function will give you the usage, and that will tell you if you have to set the static sizes:
Get-PageFileInfo server2.domain
Computer : server2.domain
FilePath : C:\pagefile.sys
AutoManagedPageFile : True
TotalSize(in MB) : 7679
CurrentUsage(in MB) : 1763
PeakUsage(in MB) : 4867
TempPageFileInUse : False
For newer versions of PowerShell:
Starting in PowerShell 3.0, the Get-WmiObject cmdlet has been superseded by Get-CimInstance.
$PageFile = Get-CimInstance -ClassName Win32_PageFileSetting -Filter "Name like '%pagefile.sys'"
$PageFile | Remove-CimInstance
$PageFile = New-CimInstance -ClassName Win32_PageFileSetting -Property #{ Name= "C:\pagefile.sys" }
$PageFile | Set-CimInstance -Property #{ InitialSize = 0; MaximumSize = 0 }
Note: you will need administrator privileges to change the pagefile.

Display Disk Size and FreeSpace in GB

Is there one line of code that will display free-size and disk-space of your logical disk in gb instead of mb? I tried doing some research but I couldn't find one liner, I did give this an attempt which was to divide it by 1GB, but that didn't work, how can I accomplish this?
gwmi win32_logicaldisk | Format-Table DeviceId, MediaType,Size,FreeSpace /1GB
Try calculated properties. I would also add [math]::Round() to shorten the values:
gwmi win32_logicaldisk | Format-Table DeviceId, MediaType, #{n="Size";e={[math]::Round($_.Size/1GB,2)}},#{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
n stands for name and e for expression. You could use the full names too, but it's a waste of space if you're writing multiple calculated Properties.
When performing any arithmetical calculation, it should be put in { }.
gwmi win32_logicaldisk | Format-Table DeviceId, MediaType,Size, {$_.FreeSpace /1GB}
You can read more on syntax from Microsoft Powershell Library
I'd like to provide an alternate/updated answer. (As of Powershell 5 at least, probably version 3.)
Just use Get-Volume
https://learn.microsoft.com/en-us/powershell/module/storage/get-volume
Example:
> get-volume
DriveLetter FriendlyName FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining Size
----------- ------------ -------------- --------- ------------ ----------------- ------------- ----
FAT32 Fixed Healthy OK 451 MB 496 MB
C OSDISK NTFS Fixed Healthy OK 65.23 GB 474.3 GB
X Transfer_Shuttle NTFS Fixed Healthy OK 37.65 GB 48.68 GB
I have same issue and I want get KB,MB,GB,TB,PB on Server with Windows Server 2008 to 2016,
then I google many information to build a function:
function ConvertDoubleToBytes([double]$srcDouble){
if([Math]::Floor([Math]::Log($srcDouble,1024)) -eq 0){
$resn = ([Math]::Ceiling($srcDouble/([math]::pow(1024,([Math]::Floor([Math]::Log($srcDouble,1024)))))).ToString() + " Bytes")
} elseif ([Math]::Floor([Math]::Log($srcDouble,1024)) -eq 1){
$resn = ([Math]::Ceiling($srcDouble/([math]::pow(1024,([Math]::Floor([Math]::Log($srcDouble,1024)))))).ToString() + " KB")
} elseif ([Math]::Floor([Math]::Log($srcDouble,1024)) -eq 2){
$resn = ([Math]::Ceiling($srcDouble/([math]::pow(1024,([Math]::Floor([Math]::Log($srcDouble,1024)))))).ToString() + " MB")
} elseif ([Math]::Floor([Math]::Log($srcDouble,1024)) -eq 3){
$resn = ([Math]::Ceiling($srcDouble/([math]::pow(1024,([Math]::Floor([Math]::Log($srcDouble,1024)))))).ToString() + " GB")
} elseif ([Math]::Floor([Math]::Log($srcDouble,1024)) -eq 4){
$resn = ([Math]::Ceiling($srcDouble/([math]::pow(1024,([Math]::Floor([Math]::Log($srcDouble,1024)))))).ToString() + " TB")
} elseif ([Math]::Floor([Math]::Log($srcDouble,1024)) -eq 5){
$resn = ([Math]::Ceiling($srcDouble/([math]::pow(1024,([Math]::Floor([Math]::Log($srcDouble,1024)))))).ToString() + " PB")
}
return $resn
}
And I use it:
Get-WmiObject -query "Select * from win32_logicaldisk " | Select-Object DeviceID,#{n="FreeSpace";e={ConvertDoubleToBytes($([double]::Parse($_.FreeSpace)))}},#{n="Size";e={ConvertDoubleToBytes($([double]::Parse($_.Size)))}},#{n="Useage Percent";e={$([Math]::Ceiling((1-$($([double]::Parse($_.FreeSpace))/$([double]::Parse($_.Size))))*100)).ToString() + " %"}}
Will print like this:
DeviceID FreeSpace Size Useage Percent
-------- --------- ---- --------------
C: 36 GB 100 GB 65 %
D: 294 GB 600 GB 52 %
E:
F: 279 GB 600 GB 54 %
G:
H: 500 GB 500 GB 1 %
This works great.
$disks = get-wmiobject Win32_LogicalDisk -computername $computer -Filter "DriveType = 3"
foreach ($disk in $disks) {
$letter = $disk.deviceID
$volumename = $disk.volumename
$totalspace = [math]::round($disk.size / 1GB, 2)
$freespace = [math]::round($disk.freespace / 1GB, 2)
$usedspace = [math]::round(($disk.size - $disk.freespace) / 1GB, 2)
$disk | Select-Object #{n = "Computer Name"; e = { $computer } }, #{n = "Disk Letter"; e = { $letter } }, #{n = "Volume Name"; e = { $volumename } }, #{n = "Total Space"; e = { ($totalspace).tostring() + " GB" } }, #{n = "Free Space"; e = { ($freespace).tostring() + " GB" } }, #{n = "Used Space"; e = { ($usedspace).tostring() + " GB" } } | FT
}