{"id":53913,"date":"2009-04-22T23:15:00","date_gmt":"2009-04-22T23:15:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2009\/04\/22\/hey-scripting-guy-how-can-i-identify-and-delete-an-instance-of-a-process\/"},"modified":"2009-04-22T23:15:00","modified_gmt":"2009-04-22T23:15:00","slug":"hey-scripting-guy-how-can-i-identify-and-delete-an-instance-of-a-process","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-identify-and-delete-an-instance-of-a-process\/","title":{"rendered":"Hey, Scripting Guy! How Can I Identify and Delete an Instance of a Process?"},"content":{"rendered":"<p><H2><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" height=\"34\" alt=\"Hey, Scripting Guy! Question\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\"> <\/H2>\n<P>Hey, Scripting Guy! I want to do a query for a process, and if the process is running, I want to delete that process. I know I could write a script by using WMI, but is there something native to Windows PowerShell that I can use to find and to delete the process? Next question: what if there is more than one process I have to delete? Can I find those processes and delete them? I remain your humble <A href=\"http:\/\/starwars.wikia.com\/wiki\/Youngling\" target=\"_blank\">youngling<\/A>.<BR><BR>&#8211; RB<\/P><IMG height=\"5\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" border=\"0\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" height=\"34\" alt=\"Hey, Scripting Guy! Answer\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" align=\"left\" border=\"0\"> \n<P>Hi RB,<\/P>\n<P>Yes, the force is strong with this one. We can sense it by the calm aura that pervades the manner of one who possesses such strength. Such power does not have to be flashy, as is exhibited by this creature:<\/P><IMG height=\"375\" alt=\"Image of a shark off Little Cayman\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/april\/hey0422\/hsg-04-22-09-01.jpg\" width=\"500\" border=\"0\"> \n<P>&nbsp;<\/P>\n<P>Windows PowerShell is not flashy, but do not mistake it for a mere replacement for the command prompt. The real power of Windows PowerShell is in the way that we can use one command to feed into another command. Mastering the pipeline unlocks the key to excellent capabilities (kind of like mastering the <A href=\"http:\/\/en.wikipedia.org\/wiki\/Lightsaber\" target=\"_blank\">lightsaber<\/A> is essential for younglings).<\/P>\n<TABLE class=\"dataTable\" id=\"EFD\" cellSpacing=\"0\" cellPadding=\"0\">\n<THEAD><\/THEAD>\n<TBODY>\n<TR class=\"record\" vAlign=\"top\">\n<TD class=\"\">\n<P class=\"lastInCell\">This week we will be looking at the basics of Windows PowerShell. Windows PowerShell is installed by default on Windows 7 and Windows Server 2008 R2. It is an optional installation on Windows Server 2008 and a download for <A href=\"http:\/\/www.microsoft.com\/downloads\/details.aspx?displaylang=en&amp;FamilyID=c6ef4735-c7de-46a2-997a-ea58fdfcba63\">Windows Vista<\/A>, <A href=\"http:\/\/www.microsoft.com\/downloads\/details.aspx?displaylang=en&amp;FamilyID=6ccb7e0d-8f1d-4b97-a397-47bcc8ba3806\">Windows XP<\/A>, and <A href=\"http:\/\/www.microsoft.com\/downloads\/details.aspx?displaylang=en&amp;FamilyID=10ee29af-7c3a-4057-8367-c9c1dab6e2bf\">Windows Server 2003<\/A>. The <A href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/hubs\/msh.mspx\">Windows PowerShell Scripting Hub<\/A> is a good place to get started with Windows PowerShell.<\/P><\/TD><\/TR><\/TBODY><\/TABLE>\n<DIV class=\"dataTableBottomMargin\"><\/DIV>\n<P>We are not sure that telling you to close your eyes and feel the pipeline would do much good. Neither would exhortations to become one with the pipeline. Therefore, we will provide some examples to show by using the Windows PowerShell pipeline. If we want to obtain information about the Notepad process (assuming that Notepad is actually running), we use the <B>Get-Process<\/B> cmdlet:<\/P><PRE class=\"codeSample\">Get-Process Notepad<\/PRE>\n<P>We do not have to specify the <B>\u2013name<\/B> parameter if we do not want to do this, because the <B>\u2013name<\/B> parameter is the default parameter with <B>Get-Process<\/B>. We can type the <B>\u2013name<\/B> parameter and get information about the Notepad process. This is seen&nbsp;here:<\/P><PRE class=\"codeSample\">PS C:\\&gt; Get-Process -name notepad<\/p>\n<p>Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName\n&#8212;&#8212;-  &#8212;&#8212;    &#8212;&#8211;      &#8212;&#8211; &#8212;&#8211;   &#8212;&#8212;     &#8212; &#8212;&#8212;&#8212;&#8211;\n     47       2      976       3512    59     0.10   3960 notepad\n<\/PRE>\n<P>To stop the Notepad process, we use the <B>Stop-Process<\/B> cmdlet. If, however, we are not used to using the <B>\u2013name<\/B> parameter with the <B>Get-Process<\/B>, cmdlet we will receive a shock when we try the same syntax&nbsp;with <B>Stop-Process<\/B>:<\/P><PRE class=\"codeSample\">PS C:\\&gt; Stop-Process notepad\nStop-Process : Cannot bind parameter &#8216;Id&#8217;. Cannot convert value &#8220;notepad&#8221; to ty\npe &#8220;System.Int32&#8221;. Error: &#8220;Input string was not in a correct format.&#8221;\nAt line:1 char:13\n+ Stop-Process &lt;&lt;&lt;&lt;  notepad\n    + CategoryInfo          : InvalidArgument: (:) [Stop-Process], ParameterBi\n   ndingException\n    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerSh\n   ell.Commands.StopProcessCommand\n<\/PRE>\n<P>The reason for the error is that the <B>\u2013name<\/B> parameter occupies the first position for the <B>Get-Process<\/B> cmdlet, and the <B>\u2013id<\/B> parameter is the first position parameter for the <B>Stop-Process<\/B> cmdlet. When we did not use any named parameters, the <B>Stop-Process<\/B> cmdlet looked for a process with the process ID of &#8220;notepad&#8221; which is not an integer, and this caused the error. The <B>\u2013name<\/B> parameter is a named parameter in the <B>Stop-Process<\/B> cmdlet. This means if we want to use the name of a process to stop, we must specify the <B>\u2013name<\/B> parameter. This is seen here:<\/P><PRE class=\"codeSample\">Stop-Process -name notepad<\/PRE>\n<P>To avoid these kinds of errors, you can always use parameters (which is a best practice when you write scripts), or you can use the pipeline. The advantage of using the pipeline is that you do not have to worry about all the parameters. You can use Windows PowerShell to find the process that you are interested in, and pipeline the results of the first command to the second command that will stop the process. This is seen here:<\/P><PRE class=\"codeSample\">Get-Process notepad | Stop-Process<\/PRE>\n<P>A session that starts an instance of Notepad, identifies the Notepad process, and then deletes that process is seen here:<\/P><IMG height=\"158\" alt=\"Image of a Notepad process being started, identified, and deleted\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/april\/hey0422\/hsg-04-22-09-02.jpg\" width=\"500\" border=\"0\"> \n<P>&nbsp;<\/P>\n<P>You can use wildcard characters to identify processes. This technique can be both dangerous and useful. Here is an example of using wildcard characters to simplify finding all the Notepad&nbsp;processes:<\/P><PRE class=\"codeSample\">PS C:\\&gt; Get-Process note*<\/p>\n<p>Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName\n&#8212;&#8212;-  &#8212;&#8212;    &#8212;&#8211;      &#8212;&#8211; &#8212;&#8211;   &#8212;&#8212;     &#8212; &#8212;&#8212;&#8212;&#8211;\n     47       2      976       3464    59     0.05   2056 notepad\n     47       2      976       3488    59     0.09   3292 notepad\n<\/PRE>\n<P>You can then pipeline the result to the <B>Stop-Process<\/B> cmdlet and stop all instances of the Notepad process that are running on the computer:<\/P><PRE class=\"codeSample\">Get-Process note* | Stop-Process<\/PRE>\n<P>An example of working with processes by using wildcard characters is seen here:<\/P><IMG height=\"158\" alt=\"Image of working with processes by using wildcard characters\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/hsg\/2009\/april\/hey0422\/hsg-04-22-09-03.jpg\" width=\"500\" border=\"0\"> \n<P>&nbsp;<\/P>\n<P>Using wildcard characters can be dangerous if you are not careful. An example of such a dangerous command is seen here where we get a list of all the processes that are running on the computer, and pipeline them to the <B>Stop-Process<\/B> cmdlet. This will stop every process that is running on the computer, which for most operating systems will cause the computer to shut down (on Windows Vista and later, this command would have to be run with administrative rights). <\/P><PRE class=\"codeSample\">Get-Process * | Stop-Process<\/PRE>\n<P>Of course, if you want to shutdown the operating system it is best to use the shutdown method from the <B>Win32_OperatingSystem<\/B> WMI class. <\/P>\n<P>Suppose we have several instances of Notepad that are running. One instance has been running for a while and has consumed more CPU time than the other process. We can get this information as seen&nbsp;here:<\/P><PRE class=\"codeSample\">PS C:\\&gt; Get-Process notepad<\/p>\n<p>Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName\n&#8212;&#8212;-  &#8212;&#8212;    &#8212;&#8211;      &#8212;&#8211; &#8212;&#8211;   &#8212;&#8212;     &#8212; &#8212;&#8212;&#8212;&#8211;\n     47       2      976       3452    59     0.10   2688 notepad\n     49       2     1160       3936    60     1.13   3984 notepad\n<\/PRE>\n<P>Whereas we could definitely use the process ID\u20143984 in this example\u2014to stop the process that is using the most CPU time, we may not want to type two separate commands (or perhaps we want to automate the task of stopping a process that is using too much CPU time). To do this, we pipeline the results of the first query to the <B>Where-Object<\/B> cmdlet. We can use the alias for <B>Where-Object<\/B>, which is just <B>Where<\/B>. The alias eliminates some typing that is required for this command without sacrificing any readability. If we were not worrying about readability, we could use <B>gps<\/B> as an alias for the <B>Get-Process<\/B> cmdlet, and we could use <B>?<\/B> as the alias for the <B>Where-Object<\/B>. The short command is shown&nbsp;the <B>Where-Object<\/B>. The short command is shown here:<\/P>\n<P>PS C:\\&gt; gps notepad | ? { $_.cpu -gt 1 }<BR><BR>Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName<BR>&#8212;&#8212;- &#8212;&#8212; &#8212;&#8211; &#8212;&#8211; &#8212;&#8211; &#8212;&#8212; &#8212; &#8212;&#8212;&#8212;&#8211;<BR>47 2 1316 4080 60 1.38 2420 notepad<\/P>\n<P>The way I generally type the command is to spell out <B>Get-Process<\/B> (I use tab completion to spell it out: I only have to type <B>Get-p<\/B> and then I press the TAB key.) The <B>Where-Object<\/B> cmdlet is used to filter the process objects as they come across the pipeline. Each instance of a process with the name of <B>Notepad<\/B> is returned by the <B>Get-Process<\/B> cmdlet. As the process comes across the pipeline, the <B>$_<\/B> automatic variable represents the current process object on the pipeline. This enables us to examine the properties of the process object. We inspect the amount of CPU time that is being used by the process to see whether it exceeds 1. If it does, the filter will enable the process object to continue. In the example seen here we display basic information about the process on the console:<\/P><PRE class=\"codeSample\">PS C:\\&gt; Get-Process notepad | Where { $_.cpu -gt 1 }<\/p>\n<p>Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName\n&#8212;&#8212;-  &#8212;&#8212;    &#8212;&#8211;      &#8212;&#8211; &#8212;&#8211;   &#8212;&#8212;     &#8212; &#8212;&#8212;&#8212;&#8211;\n     49       2     1160       3936    60     1.13   3984 notepad\n<\/PRE>\n<P>If we are not sure which properties are available for us to use in the <B>Where-Object<\/B> filter, we can use the <B>Get-Member<\/B> cmdlet. If we select the properties, we will eliminate the methods. This command is seen here: <\/P><PRE class=\"codeSample\">PS C:\\&gt; Get-Process | Get-Member -MemberType property<\/PRE>\n<P>However, we will also miss the instances of <B>ScriptProperty<\/B> and <B>AliasProperty<\/B>. To make sure we can find the other properties that were added by the Windows PowerShell team, we use a wildcard character in front of the <B>MemberType<\/B> property. The CPU property is one that was added by the Windows PowerShell team. It is a <B>ScriptProperty<\/B>. This is seen&nbsp;This is seen here:<\/P><PRE class=\"codeSample\">PS C:\\&gt; Get-Process | Get-Member -MemberType *property<\/p>\n<p>   TypeName: System.Diagnostics.Process<\/p>\n<p>Name                       MemberType     Definition\n&#8212;-                       &#8212;&#8212;&#8212;-     &#8212;&#8212;&#8212;-\nHandles                    AliasProperty  Handles = Handlecount\nName                       AliasProperty  Name = ProcessName\nNPM                        AliasProperty  NPM = NonpagedSystemMemorySize\nPM                         AliasProperty  PM = PagedMemorySize\nVM                         AliasProperty  VM = VirtualMemorySize\nWS                         AliasProperty  WS = WorkingSet\n__NounName                 NoteProperty   System.String __NounName=Process\nBasePriority               Property       System.Int32 BasePriority {get;}\nContainer                  Property       System.ComponentModel.IContainer C&#8230;\nEnableRaisingEvents        Property       System.Boolean EnableRaisingEvents&#8230;\nExitCode                   Property       System.Int32 ExitCode {get;}\nExitTime                   Property       System.DateTime ExitTime {get;}\nHandle                     Property       System.IntPtr Handle {get;}\nHandleCount                Property       System.Int32 HandleCount {get;}\nHasExited                  Property       System.Boolean HasExited {get;}\nId                         Property       System.Int32 Id {get;}\nMachineName                Property       System.String MachineName {get;}\nMainModule                 Property       System.Diagnostics.ProcessModule M&#8230;\nMainWindowHandle           Property       System.IntPtr MainWindowHandle {get;}\nMainWindowTitle            Property       System.String MainWindowTitle {get;}\nMaxWorkingSet              Property       System.IntPtr MaxWorkingSet {get;s&#8230;\nMinWorkingSet              Property       System.IntPtr MinWorkingSet {get;s&#8230;\nModules                    Property       System.Diagnostics.ProcessModuleCo&#8230;\nNonpagedSystemMemorySize   Property       System.Int32 NonpagedSystemMemoryS&#8230;\nNonpagedSystemMemorySize64 Property       System.Int64 NonpagedSystemMemoryS&#8230;\nPagedMemorySize            Property       System.Int32 PagedMemorySize {get;}\nPagedMemorySize64          Property       System.Int64 PagedMemorySize64 {get;}\nPagedSystemMemorySize      Property       System.Int32 PagedSystemMemorySize&#8230;\nPagedSystemMemorySize64    Property       System.Int64 PagedSystemMemorySize&#8230;\nPeakPagedMemorySize        Property       System.Int32 PeakPagedMemorySize {&#8230;\nPeakPagedMemorySize64      Property       System.Int64 PeakPagedMemorySize64&#8230;\nPeakVirtualMemorySize      Property       System.Int32 PeakVirtualMemorySize&#8230;\nPeakVirtualMemorySize64    Property       System.Int64 PeakVirtualMemorySize&#8230;\nPeakWorkingSet             Property       System.Int32 PeakWorkingSet {get;}\nPeakWorkingSet64           Property       System.Int64 PeakWorkingSet64 {get;}\nPriorityBoostEnabled       Property       System.Boolean PriorityBoostEnable&#8230;\nPriorityClass              Property       System.Diagnostics.ProcessPriority&#8230;\nPrivateMemorySize          Property       System.Int32 PrivateMemorySize {get;}\nPrivateMemorySize64        Property       System.Int64 PrivateMemorySize64 {&#8230;\nPrivilegedProcessorTime    Property       System.TimeSpan PrivilegedProcesso&#8230;\nProcessName                Property       System.String ProcessName {get;}\nProcessorAffinity          Property       System.IntPtr ProcessorAffinity {g&#8230;\nResponding                 Property       System.Boolean Responding {get;}\nSessionId                  Property       System.Int32 SessionId {get;}\nSite                       Property       System.ComponentModel.ISite Site {&#8230;\nStandardError              Property       System.IO.StreamReader StandardErr&#8230;\nStandardInput              Property       System.IO.StreamWriter StandardInp&#8230;\nStandardOutput             Property       System.IO.StreamReader StandardOut&#8230;\nStartInfo                  Property       System.Diagnostics.ProcessStartInf&#8230;\nStartTime                  Property       System.DateTime StartTime {get;}\nSynchronizingObject        Property       System.ComponentModel.ISynchronize&#8230;\nThreads                    Property       System.Diagnostics.ProcessThreadCo&#8230;\nTotalProcessorTime         Property       System.TimeSpan TotalProcessorTime&#8230;\nUserProcessorTime          Property       System.TimeSpan UserProcessorTime &#8230;\nVirtualMemorySize          Property       System.Int32 VirtualMemorySize {get;}\nVirtualMemorySize64        Property       System.Int64 VirtualMemorySize64 {&#8230;\nWorkingSet                 Property       System.Int32 WorkingSet {get;}\nWorkingSet64               Property       System.Int64 WorkingSet64 {get;}\nCompany                    ScriptProperty System.Object Company {get=$this.M&#8230;\nCPU                        ScriptProperty System.Object CPU {get=$this.Total&#8230;\nDescription                ScriptProperty System.Object Description {get=$th&#8230;\nFileVersion                ScriptProperty System.Object FileVersion {get=$th&#8230;\nPath                       ScriptProperty System.Object Path {get=$this.Main&#8230;\nProduct                    ScriptProperty System.Object Product {get=$this.M&#8230;\nProductVersion             ScriptProperty System.Object ProductVersion {get=&#8230;\n<\/PRE>\n<P>As soon as we have the filter working correctly and we see that it is returning the results that we are interested in obtaining, we can just pipeline the resulting process object to the <B>Stop-Process<\/B> cmdlet. This is shown here:<\/P><PRE class=\"codeSample\">PS C:\\&gt; Get-Process notepad | Where { $_.cpu -gt 1 } | Stop-Process<\/PRE>\n<P>The ability to add pipelines together, by feeding the results of one pipeline into another pipeline as shown earlier, is where we obtain the real power of Windows PowerShell. It is a new concept for people who have a Windows background, but is something that people have done for years in other consoles. The big difference is that we pass objects through the pipeline, and not merely text. Join us tomorrow as we continue our Windows PowerShell Basics Week. Until then, peace. <\/P>\n<P>&nbsp;<\/P>\n<P><B>Ed Wilson and Craig Liebendorfer, Scripting Guys<\/B><\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I want to do a query for a process, and if the process is running, I want to delete that process. I know I could write a script by using WMI, but is there something native to Windows PowerShell that I can use to find and to delete the process? Next question: [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[51,3,4,45],"class_list":["post-53913","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-getting-started","tag-scripting-guy","tag-scripting-techniques","tag-windows-powershell"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! I want to do a query for a process, and if the process is running, I want to delete that process. I know I could write a script by using WMI, but is there something native to Windows PowerShell that I can use to find and to delete the process? Next question: [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/53913","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=53913"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/53913\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=53913"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=53913"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=53913"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}