?
Solved

Powershell script to check where the Windows Server Paging File Location is on remote servers and export to .CSV

Posted on 2016-08-02
7
Medium Priority
?
126 Views
1 Endorsement
Last Modified: 2016-08-28
Powershell script to check where the Windows Server Paging File Location is on remote servers and export to .CSV
Project is to get a list of those servers that have the page file located on C:\ and other drives etc.  

IE:
Server C:
             D:
             E:
1
Comment
Question by:mjm21
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 19

Expert Comment

by:Jeremy Weisinger
ID: 41739119
0
 
LVL 13

Assisted Solution

by:Dustin Saunders
Dustin Saunders earned 800 total points (awarded by participants)
ID: 41739297
That above will get pagefiles, but not output to a CSV.  Here I've completed the script to give you that function.  Just change the top 2 lines with the location of the servers you want to check and the place where you want the CSV to go.  In the servers.txt file, on each line put in the name of the server you want to check.

$serverFile = "C:\test\servers.txt"
$outputFile = "C:\test\pagefiles.csv"

#region ==============================================================================================================================================
#<copyright file="PageFileLocation.ps1">
#Author : mysticmukesh@gmail.com
#</copyright>
#----------------------------------------------------------------------------------------------------------------------------------------------
#Revision History
#================
#Date                Author        Comments
#----------------------------------------------------------------------------------------------------------------------------------------------
#03-July-2015        Mukesh-kumar         Initial version
#08-June-2016		 Mukesh-Kumar         Added parameter : serverlist 
#===============================================================================================================================================
<#

.SYNOPSIS

Retrieves  page file location information from  local or remote computers.

.DESCRIPTION

The script uses .Net RegistryKey class and its OpenRemoteBaseKey method to retrieve the information.

Each computer is contacted sequentially, not in parallel.

.EXAMPLE

Run it from the location where the script is stored.

PS C:\Users\Administrator\Downloads> .\PageFileLocation.ps1

ServerName                                                  PageFileLocation
----------                                                  ----------------
Server1                                                     C:\pagefile.sys

.EXAMPLE 

Read computer names from a file (one name per line) and retrieve their page file loction.

Get-PageFileLocation -serverlist (Get-Content C:\server.txt)

ServerName                              PageFileLocation
----------                              ----------------
PRASADMU23                              C:\pagefile.sys
NOTFOUND                                The network path was not found.

#>
#endregion
function Get-PageFileLocation()
{	
	[CmdLetBinding ()]
	param(
		[Parameter(Mandatory=$False)]
		[String[]]$serverlist
	)
	#Get the list of servers
#	$serverlist=get-content "C:\servers.txt" -ErrorAction SilentlyContinue
	if($serverlist -eq $null)
	{
		$serverlist=hostname
	}
	$a=@()
	#Regular Expression to extract the page file location from the registry key
	$Regex="^\\.{3}(.*)"
	$Object=New-Object PSObject 
	$Object1=New-Object PSObject 
	foreach ($server in $serverlist)
	{
		try
		{
			#Open the registry on multiple remote computers
			$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$server )
			$RegKeyPath= "SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management"
			$pageFileKey=$reg.OpenSubKey($RegKeyPath)
			$pageFileLocation=$pageFileKey.GetValue("ExistingPageFiles")
			if("$pageFileLocation" -match $Regex)
			{
				$pageFileLocation=$Matches[1]
				$Object | add-member Noteproperty ServerName $server -Force
				$Object | add-member Noteproperty PageFileLocation $pageFileLocation -Force
				$a+=$Object
			}
		}	
		Catch [Exception] # To capture the non reachable servers
		{
			[string]$ExcepMsg=$_.Exception.Message
			$Object1 | add-member Noteproperty ServerName $server -Force
			$Object1 | add-member Noteproperty PageFileLocation $ExcepMsg -Force
			$a+=$Object1
		}
	}
	Write-Output $a
}

Get-PageFileLocation -serverlist (Get-Content $serverFile) | Export-Csv $outputFile -NoTypeInformation

Open in new window

0
 
LVL 85

Accepted Solution

by:
oBdA earned 1200 total points (awarded by participants)
ID: 41740354
Here's a version that uses WMI and generates a more detailed output; you can optionally ...
* use -FailFast to ping machines before trying to query them,
* pass a Credentials object,
* pass a file to export the results to
If no export file is given, the results will end up in the pipeline and can be processed further as usual.
Pipeline input is supported, so you can do something like
Get-ADComputer -Filter * | .\Get-PageFileLocationByWmi.ps1 -FailFast | Format-Table -AutoSize

Open in new window

[CmdletBinding()]
Param(
	[Parameter(ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Position=0)]
	[Alias('ComputerName')][String[]]$Name = @($ENV:ComputerName),
	[Switch]$FailFast,
	[System.Management.Automation.PSCredential]$Credential,
	[String]$ExportCsv
)
Begin {
	$Results = @()
	$ResultProperties = 'Computername', 'SystemManaged', 'Name', 'InitialSize', 'MaximumSize', 'AllocatedBaseSize', 'CurrentUsage', 'PeakUsage', 'Exception'
	$WmiArgs = @{'Namespace' = 'root\cimv2'; 'ErrorAction' = 'Stop'}
	$Collect = @{}
	$Ping = New-Object -TypeName System.Net.NetworkInformation.Ping
	Function Set-ResultProperties($Hashtable, $Computername, $SystemManaged, $Name, $InitialSize, $MaximumSize, $AllocatedBaseSize, $CurrentUsage, $PeakUsage, $Exception) {
		If (-not $Hashtable.ContainsKey($Name)) {
			$Hashtable[$Name] = '' | Select-Object -Property $ResultProperties
		}
		ForEach ($Property In ($PSBoundParameters.Keys | Where-Object {$_ -ne 'Hashtable'})) {
			$Hashtable[$Name].$Property = $PSBoundParameters[$Property]
		}
	}
}
Process {
	ForEach ($Computer In $Name) {
		Try {
			$Collect.Clear()
			Write-Host -Object "Processing $($Computer) ... " -Foregroundcolor White -NoNewline
			If ($FailFast -and (($Ping.Send($Computer, 1000)).Status -ne "Success") -and (($Ping.Send($Computer, 500)).Status -ne "Success")) {
				Throw "Offline"
			}
			$WmiArgs['ComputerName'] = $Computer
			If ($Credential -and ($Computer.Split('.')[0] -ne $ENV:ComputerName)) {
				$WmiArgs['Credential'] = $Credential
			}
			$SystemManaged = (Get-WmiObject -Query "Select AutomaticManagedPagefile From Win32_ComputerSystem" @WmiArgs).AutomaticManagedPagefile -eq $True
			Get-WmiObject -Query "Select AllocatedBaseSize, CurrentUsage, Name, PeakUsage From Win32_PageFileUsage" @WmiArgs | ForEach-Object {
				Set-ResultProperties -Hashtable $Collect -Name $_.Name -ComputerName $Computer -SystemManaged $SystemManaged -AllocatedBaseSize $_.AllocatedBaseSize -CurrentUsage $_.CurrentUsage -PeakUsage $_.PeakUsage
			}
			If (-not $SystemManaged) {
				Get-WmiObject -Query 'Select InitialSize, MaximumSize, Name From Win32_PageFileSetting' @WmiArgs | ForEach-Object {
					Set-ResultProperties -Hashtable $Collect -Name $_.Name -ComputerName $Computer -SystemManaged $SystemManaged -InitialSize $_.InitialSize -MaximumSize $_.MaximumSize
				}
			}
			Write-Host -Object "OK" -Foregroundcolor Green
		} Catch {
			Set-ResultProperties -Hashtable $Collect -Name '' -ComputerName $Computer -Exception $_.Exception.Message
			Write-Host -Object "ERROR: $($_.Exception.Message)" -Foregroundcolor Red
		}
		ForEach ($Key In $Collect.Keys) {
			$Results += $Collect[$Key]
		}
	}
}
End {
	If ([string]::IsNullOrEmpty($ExportCsv)) {
		$Results | Sort-Object -Property ComputerName, Name
	} Else {
		$Results | Sort-Object -Property ComputerName, Name | Export-Csv -Path $ExportCsv -NoTypeInformation
	}
}

Open in new window

1
Ransomware Attacks Keeping You Up at Night?

Will your organization be ransomware's next victim?  The good news is that these attacks are predicable and therefore preventable. Learn more about how you can  stop a ransomware attacks before encryption takes place with our Ransomware Prevention Kit!

 

Author Comment

by:mjm21
ID: 41740726
Jeremy / Justin:  When running the script the results show only one server out of the pulled list of for example 10 servers.  Permissions are correct.  Any thoughts?

oBDA: Where in your script will it know how to pull from a list of servers from a .txt file?

Thanks all!
0
 
LVL 85

Expert Comment

by:oBdA
ID: 41740756
The script itself doesn't support it, but you can pass it any string array, like the AD example above:
Get-Content -Path C:\Temp\servers.txt | .\Get-PageFileLocationByWmi.ps1 -FailFast -ExportCsv C:\Temp\Pagefiles.csv

Open in new window

Or like this:
.\Get-PageFileLocationByWmi.ps1 -ComputerName (Get-Content -Path C:\Temp\servers.txt) -FailFast

Open in new window

0
 

Author Comment

by:mjm21
ID: 41748920
Thanks! Appreciate all your efforts!
0
 
LVL 13

Expert Comment

by:Dustin Saunders
ID: 41773567
Asker appears to have gotten a working answer.  Suggested awarding points to the custom code contributions weighted for oBdA spending more time responding.
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
I was prompted to write this article after the recent World-Wide Ransomware outbreak. For years now, System Administrators around the world have used the excuse of "Waiting a Bit" before applying Security Patch Updates. This type of reasoning to me …
This tutorial will walk an individual through the steps necessary to install and configure the Windows Server Backup Utility. Directly connect an external storage device such as a USB drive, or CD\DVD burner: If the device is a USB drive, ensure i…
This tutorial will show how to configure a single USB drive with a separate folder for each day of the week. This will allow each of the backups to be kept separate preventing the previous day’s backup from being overwritten. The USB drive must be s…
Suggested Courses

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question