Share via


The Desktop FilesPsTools Primer

Wes Miller

Download the code for this article: MillerTheDesktopFiles2007_03.exe (150KB)

Until last year, I worked at Winternals Software, which was acquired by Microsoft in July 2006. Winternals sold commercial software, but the company founders, Mark Russinovich and Bryce Cogswell, also owned a separate company called Sysinternals that distributed many tools as freeware. A few of these freeware apps had

even evolved to become components in the Winternals Administrator's Pak. Mark and Bryce also licensed these tools to companies seeking to use them outside of the typical freeware license terms.

One of my favorite tools from the Sysinternals library-OK, it's a whole gaggle of tools-is the PsTools suite now found at microsoft.com/technet/sysinternals/utilities/pstools.mspx. Mark named the tools after the UNIX process listing utility, ps. As mentioned on the download site for the tools, there are built-in Windows® command-line utilities that can perform some of the same functions as these tools. However, in addition to significant unique functionality, a major difference is that the PsTools suite can be used locally or remotely (provided the remote systems are configured correctly, of course). Even better, the process for running them remotely is nearly as simple as running them locally.

The PsTools suite includes several individual applications, listed in Figure 1. As with the rest of the Sysinternals utilities, there is no installer, only applications. Just put them in a folder on your path and go!

Figure 1 PsTools utilities

Tool Description
PsExec Allows you to execute processes in any user context.
PsFile Shows the files opened remotely on a system.
PsGetSid Displays the Windows Security Identifier (SID) of a computer or a user.
PsInfo Lists information about a Windows system.
PsKill Kills processes by name or process ID.
PsList Lists detailed information about running processes.
PsLoggedOn Shows all locally logged on users as well as all remote resource-sharing users.
PsLogList Dumps Windows Event Log records.
PsPasswd Changes user account passwords.
PsService Views and controls Windows services.
PsShutdown Shuts down, reboots, hibernates, or suspends a computer.
PsSuspend Suspends running processes.

Now, you may notice that some of this functionality (especially PsLogList) could be accomplished via Windows Management Instrumentation (WMI) and some complex scripting. But the point of the PsTools suite is that each utility was designed to accomplish a specific task, and do so simply and easily.

I'm going to walk you through each tool and give you a simple example of why and how you might use it. But first, I'll offer a brief introduction into how the tools themselves work and what kind of prerequisites you must have in place in order for them to work.

How Do the Tools Work?

The tools all generally work in the same manner. On the host system, you launch the desired PsTool. Though many can be run locally, you'll find that these tools typically provide their utmost utility when run against a remote system or several systems at once. (PsExec is a specific exception that comes to mind, as you will see in my example below.) Using the command-line argument you provide, the utility copies itself to the remote system's administrative share, which is the same as %SystemRoot% (Windows directory) on the remote system.

Once copied into the remote directory, the application launches itself and installs a Windows service. This Windows service performs the task you requested, using the credentials you provided at launch time. If an end-user UI on the client system is required by the specific tool, this service then launches an additional binary in the user's context. (Remember that services can't throw direct interactive UIs.) The service communicates any necessary information back to the console that launched it. And finally, the service uninstalls itself.

As you can see, the tools are powerful and self-contained. Though they involve multiple binaries and multiple processes, you as a user don't have to worry about it-you simply run the desired tool and it works.

In order to use the tools, you must have the following prerequisites: either Windows NT®, Windows 2000, Windows XP, or Windows Server® 2003 (x86 or x64 versions of Windows are supported, but Itanium versions are not); the default administrative network share enabled on the remote system you are running the tools on (admin$); and the ports for File and Printer Sharing opened on the remote system (whether you are using Windows Firewall, Internet Connection Firewall, or another firewall product).

PsExec

PsExec is my personal favorite among the tools-and probably not for the reason you might expect. For the better part of two years, I have been running as "non-admin" on my systems-I run as a User, not as an Administrator. Instead, I have a short script called run.vbs that I use to run apps as local Administrator (they could just as easily run as any user). Figure 2 shows the content of the script (which is also available on the TechNet Magazine site at technetmagazine.com/code07.aspx). The script assumes the PsTools are in the Path system variable.

Figure 2 Run.vbs

SET WshShell = WScript.CreateObject("WScript.Shell")
SET WshSysEnv = WshShell.Environment("SYSTEM")
SET FSO = CreateObject("Scripting.FileSystemObject")
IF WScript.Arguments.Count <> 0 Then
    FOR EACH arg IN WScript.Arguments
        iArgCount = iArgCount + 1
        strCmdArg = (arg)
        strCmdArray = Split(strCmdArg, " ", 2, 1)
        IF iArgCount = 1 THEN
        strExe = strCmdArray(0)
        ELSEIF iArgCount = 2 THEN
        strRun = strCmdArray(0)
        ELSE
        strParams = strParams&" "&strCmdArray(0)
        END IF
    NEXT
END IF
'/t:0A && title ***** Admin ***** 
        strExt = LCase(Right(strExe, 3))

IF strExt <> "exe" AND strExt <> "bat" AND strExt <> "cmd" THEN
WshShell.Run "psexec.exe -d -i -e -u COMPUTERNAME\USER -p PASSWORD  cmd /c start "&strExe&"
    "&strRun&" "&strParams, 0, FALSE
ELSE
WshShell.Run "psexec.exe -d -i -e -u COMPUTERNAME\USER -p PASSWORD "&strExe&" "&strRun&"
    "&strParams, 0, FALSE
END IF

    SET WshShell = NOTHING
    SET WshSysEnv = NOTHING
    SET FSO = NOTHING

This simple script is one example of using PsExec with functionality that Mark added as we worked on our Protection Manager product at Winternals: the ability for a limited user to provide more privileged credentials to launch PsExec locally. The more common use of PsExec, of course, is to run it remotely-for example, to run a utility that doesn't provide its own remoting, scripting, or automation framework. A couple of key features of PsExec include the ability to copy a binary to remote systems that is to be executed, as well as the ability to dictate processor affinity. One other handy feature of PsExec is the ability to script it against many machines simultaneously by providing a script file.

Here is simplified usage for PsExec:

PsExec \\computer -u username -p password command

You can expand on this using the switches shown in Figure 3.

Figure 3 PsExec switches

Switch Description
-a Specifies processor affinity.
-c Indicates whether the application should be copied to the remote system.
-d Specifies not to wait for the process to finish before exiting (it won't wait for a success or failure message).
-e Loads using the specified account's profile.
-f Copies the application even if it exists on the remote system. Ensures that you are running the current (or a specific) version.
-i Runs the application interactively on the remote system (required if you want an end user to see any user interface from the application).
-l Runs the application as a limited user. Removes the Administrators group token and strips process privileges to the level they would be for a member of the Users group. Handy to run high-risk Internet-facing applications with minimal privileges.
-n Specifies the timeout to wait before failing to connect to remote computers.
-priority Runs the process at the specified priority. That is, specifies how Windows should set the process priority for a given task (-low, -belownormal, -abovenormal, -high or -realtime ).
-s Runs the process using the System account (handy to run Regedit to access privileged registry keys).
-v Copies the application only if the one being copied is newer.
-x Displays UI on the Winlogon secure desktop-only works on the local system.
@file Runs the command on all computers specified in the text file.

PsFile

PsFile is a more narrowly focused tool than PsExec. Specifically, it is used to check what files are open, and by whom, on the remote system. This can be useful if you want to track which files are open before rebooting a server. If you need to find out which user has locked the file, perhaps preventing editing or deletion, you can notify them manually, or close it via PsFile. Usage for PsFile is below:

PsFile \\computer -u username -p password 

This simply returns a list of the open file handles on the remote system. Beyond the standard usage, you can also add an Id parameter to the statement, specifying the name of the file you want to either find information about or close. You can also include the -c switch, which closes the file you identified with the Id parameter.

PsGetSid

PsGetSid is also a very focused tool. It will tell you the Security Identifier (SID) of a computer, user, or group. This can be useful if you want to ensure that the systems in your domain don't have duplicate SIDs, or you simply want to verify the SIDs of all users or groups on a system. Usage of PsGetSid is as follows:

PsGetSid \\computer -u username -p password account

Note that account can specify a user, computer, or group. While PSGetSid's syntax is simple, a couple of additional parameters are also available. The SID parameter specifies the account (group or computer) given a specified SID, and @file runs the command on all computers listed in the specified text file.

PsInfo

PsInfo is used to provide detailed system information. This obviously would be the most useful when scripted against multiple remote systems, with the output sent to a file (such as an Excel® and database-friendly CSV file). Note that this utility operates via an important concept that is different from most of the other tools: if you don't provide a computer name, PsInfo will, by default, attempt to query all computers in the domain. PsInfo's usage is as follows:

PsInfo  \\computer -u username -p password 

While the syntax is simple, additional switches and parameters are also available as shown in Figure 4

Figure 4 PsInfo Switches

Switch Description
-h Shows all Windows updates.
-s Shows all applications installed on the system.
-d Shows disk/volume information for the system.
-c Outputs the results in CSV format.
-t Specifies another delimiter for the CSV file other than the default value of \t.
Filter Shows only data that matches a given filter.
@file Runs the command on all computers listed in the specified text file.

PsKill

PsKill is a great utility for terminating processes on either a local or remote system. The usage is very simple, and it allows you to rapidly kill a process along with all of its child processes. PsKill's usage is much like the other tools I've discussed:

PsKill -t \\computer -u username -p password process id | process name

Note that you can specify either the process id or the process name you want to kill.

PsList

I don't use PsList much because I'm such a Process Explorer fan (see microsoft.com/technet/sysinternals/ProcessesAndThreads/ProcessExplorer.mspx for more information.) But since there isn't a remotable version of Process Explorer, PsList becomes a reasonable facsimile for some of the key functionality provided by Process Explorer. In effect, PsList is a remotable list of one or more processes running on a remote system.

Usage for PsList is pretty simple:

PsList \\computer -u username -p password account

As with the other tools, the account parameter can specify a user, computer, or group. Additional parameters are shown in Figure 5.

Figure 5 PsList Switches

Switch Description
-t Shows information at the thread level.
-m Provides detailed memory information for each process.
-x Shows process, memory, and thread information.
-t Shows information as a process tree (think Process Explorer tree view).
-s [n] Runs in task manager mode for the specified number of seconds. This allows for a relatively real-time display of remote process information.
-r [n] Specifies how frequently (in seconds) to refresh when running in task manager mode.
name Shows information about processes that begin with the name specified.
-e Matches the process name exactly.
pid Displays information about a specific process.

PsList is powerful, yet easy to use-and without using Remote Desktop allows you to see the remote processes in enormous detail. With this information you could move on to PsKill or PsSuspend if, for example, you had a process that had to be reined in.

PsLoggedOn

The premise behind PsLoggedOn is self-explanatory. The utility shows you who is logged onto a system. This can be either local (interactive) logons or network share logons. Similar to PsFile, this capability can be useful to determine who is using a server that you may need to perform maintenance on. Usage is very simple:

PsLoggedOn \\computer

PsLoggedOn has only two optional parameters: -l only shows local logons (not network logons), and -x excludes the logon time.

While basic, PsLoggedOn allows you to easily see information for which you would generally have to dig in a couple of Windows locations.

PsLogList

One of the most generally useful utilities, PsLogList, is a tool for dumping the Windows event logs into a text format that can then be used by log readers, databases, or whatever else your heart desires. The main advantage is that it converts the event log entries from their binary format into something that can be easily transformed or automated. (Of course in Windows Vista™, event logs are natively available as XML, but that's another topic for another day.)

Usage of PsLogList is:

PsLogList \\computer -u username -p password

A number of additional switches and parameters are also available as shown in Figure 6.

Figure 6 PsLogList switches

Switch Description
-a Dumps only events after the specified date.
-b Dumps only events before the specified date.
-c Clears the event log permanently after dumping the desired output.
-d Displays only information for the specified number of days.
-e Excludes events with the specified event ID (up to 10 can be specified).
-f Filters event types (warning, error, and so on).
-g Exports the event log out as an EVT file-requires the -c switch.
-h Displays only information for the specified number of hours.
-l Dumps from the specified EVT file.
-m Displays only information for the specified number of minutes.
-n Displays only the specified number of most recent events.
-o Shows only events from a given source (-o SRService for the Windows System Restore Service, for example).
-q Excludes events from a given source (opposite of -o).
-r Reverses order-dump log events from least recent to most recent.
-s Lists records on each line in delimited fields.
-t Specifies something other than a comma as a delimiter for the -s output.
-w Waits for new events to be populated and dump in real-time. This is only applicable on the local system.
-x Dumps extended data from event logs.
eventlog Specifies which event log to dump. System is the default.
@file Runs the command on all computers specified in the text file.

Windows event logs can be an incredibly powerful diagnostic tool, but the trick is getting the data out to the point it can be manipulated or consolidated. PsLogList performs that trick.

PsPasswd

PsPasswd is a simple yet powerful utility designed with some of the same power as Net.exe, but with remotability and automation in mind.

PsPasswd  \\computer -u username -p password Username Newpassword

You can specify a computer, no computer (the local system), or if you specify the computer as \\* the utility will run against all computers in the current domain. PsPasswd has only one additional parameter available: @file runs the command on all computers specified in the text file. Again, it's a very basic utility that provides enormous multi-system power.

PsService

PsService allows you to view and edit Service Control Manager (SCM) information on one or more systems on your network, and you can even search for a given service name on systems on your network.

PsService \\computer -u username -p password command options

When you run PsService, command represents one of the commands listed in Figure 7, and options specifies an attribute to apply to a given command. If no additional command switches are provided, PsService will provide a full dump of SCM information.

Figure 7 PsService commands

Command Description
query Queries a given service.
config Queries the configuration information for a given service.
setconfig Sets the configuration information for a given service.
start Starts a service.
stop Stops a service.
restart Restarts (stops and starts) a service.
pause Pauses a service.
cont Resumes a paused service.
depend Shows which services depend on the given service.
find Looks in your network for a given instance of the service.
security Provides the security information for a given service.

You can thus think of PsService as a powerful, remotable command-line version of Services.msc-but one that also allows you to look across the network for services (perhaps potentially dangerous ones) and set configuration information.

PsShutdown

PsShutdown is another one of my favorites. While some would say that Microsoft includes a tool that handles this task (shutdown.exe), it's really not the same. The key difference is in the power of PsShutdown: namely, it can shut down or restart a remote system. In addition, it has the ability to put a system into either standby or hibernate mode (not just shutdown or restart), lock a system, and restart a system after displaying a message to the user for a given amount of time.

PsShutdown \\computer -u username -p password

A number of additional parameters are also available for use with PsShutdown, as shown in Figure 8.

Figure 8 PsShutdown switches

Switch Description
-a Aborts an already in-progress shutdown initiated by PsShutdown.
-c Allows an interactive user to abort the shutdown.
-d Suspends the computer (standby).
-e Shutdown reason codes. I recommend looking on the Microsoft Web site for assistance with these, as they can be problematic to use with both PsShutdown and the built-in shutdown.exe. See msdn2.microsoft.com/en-us/library/aa376885.aspx for more information.
-f Forces all running applications to terminate.
-h Hibernates the computer.
-k Powers off the computer (reboots if power off isn't supported).
-l Locks the computer.
-m Specifies the message to display to any interactive users.
-n Specifies the timeout to wait before failing to connect to remote computers.
-o Logs off the console user.
-r Reboots the computer.
-s Shuts down, but doesn't power off.
-t Time to count down before running shutdown command or the specific time to power off.
-v Displays the message to the users until shutdown.
@file Runs the command on all computers specified in the text file.

You can see that PsShutdown is a very powerful, highly configurable system power control utility that is still relatively easy to use.

PsSuspend

PsSuspend is a handy utility if you want to get a rogue process under control temporarily, or if you simply want to get a high-CPU usage process spun down temporarily without losing any data or application context.

PsSuspend \\computer -u username -p password process ID

You can get the process ID using PsList. Once you've suspended a process, you can use the -r switch to resume it. Note that the concept of suspending and resuming a process is also implemented by Process Explorer, though that works only locally. Obviously, PsSuspend can suspend and resume processes remotely as well as locally, giving it the edge over the built-in implementation in Process Explorer.

Conclusion

I find the PsTools suite to be an invaluable set of utilities. Along with the rest of the Sysinternals utilities (namely Regmon, Filemon, Process Explorer, and now Process Monitor), PsTools are the first programs I put in my path when I reinstall Windows on any of my systems. I hope this column familiarized you with the PsTools if you weren't before, and if you were, I hope you have gleaned some additional knowledge about the tools. Many thanks to Mark Russinovich, of course, for providing these tools for free for all these years and for assisting me with the content for this column.

Wes Miller is a Development Manager at Pluck (www.pluck.com) in Austin, Texas. Previously, Wes worked at Winternals Software in Austin, and at Microsoft as a Program Manager and Product Manager for Windows. Wes can be reached at technet@getwired.com.

© 2008 Microsoft Corporation and CMP Media, LLC. All rights reserved; reproduction in part or in whole without permission is prohibited.