Skip to main content

Beginning PowerShell from Step1 to Step1 (Part II)

                   
Part of I of Beginning PowerShell from Step1 to Step1, it discusses on how to store variables on PowerShell, how to use For Loop statement and how to process conditional statements using the switch command.

Learning PowerShell by actually doing it; is easier to learn and you will be able to appreciate how the platform will be able to help ease your life as an IT guy in your daily life at work.

On this Part II of Beginning PowerShell, will use PowerShell to run or invoke a command line. As the title speaks of its content, Beginning PowerShell this are just simple scripts to follow. 

And of course if PowerShell will always be your companion at work, as days pass by complex ideas or scripts will come along. But as the odds say, a long journey starts with a single step.

So a good foundation, a simple start can lead a long, long way

Here’s the goal:  A PowerShell script that will execute a command line, check for a specific process; if the process is found terminate the process.

So how it can be done?

- 1. Run a command line using PowerShell
- 2. Check the output of the command line
- 3. If the process is present or found on the output
- 4. Run again a command line to terminate the process

Sound simple right?

Note: PowerShell has a cmdlet “Get-Process” to check for processes running on the system.

But to explore on how to use command line on PowerShell, a command line will be used to get the processes running on the system.

Tasklist.exe is a command line that is used to get running process on the system.

To run a command line or invoke a command PowerShell, Invoke-Command cmdlet will be used.

The cmdlet name will give you an idea on its usage “Invoke-Command”. It will basically invoke a command line as its input.

Open PowerShell and type:

Get-Help Invoke-Command –Examples

It has a long list, to keep it simple.

It’s Invoke-Command Parameters_Needed_To_Run_The_Command

Use tasklist.exe, in PowerShell as a parameter of the Cmdlet Invoke-Command.

Declare a variable, type the command line as it is being type or executed using the command line.


Before running the command, open a Notepad and just keep it running while the script is executed.

#===============================

#xCmdString holds the Tasklist command and redirect the output to a text file on d drive
#command line is enclosed in curly braces { command-line }

$xCmdString = {Tasklist  > d:\xprocess.txt}

Invoke-Command $xCmdString

#===============================


Running the two liner script above will get the current running processes on the system and store the output on a text file on d drive, on the file “xprocess.txt”.

Goal number 1, Run a command line using PowerShell (Checked=Done)



A file was created that has the list of current running processes.

To check the file using PowerShell, Get-Content command will come to the rescue.

Type: Get-Help Get-Content –Examples to find more about this cmdlet


#$xFileOutPath holds the path and file name of the file that will be used by Get-Content


#For Get-Content command to work, path and of course a file name is needed
# A variable will be needed to store the value or the output of Get-Content to be used on another process


#=========================================

$xFileOutPath = “d:\xprocess.txt”
$xImportVariable = Get-Content $xFileOutPath
#$xImportVariable will hold all the values of Get-Content

#=========================================

Open xprocess.txt file and it contains lot of data, to find or check the data, and the process that needs to be terminated. 


The file has to be read or process line by line and compare each line to a variable.

For the sake of simplicity, will look for “Notepad.exe” process and close it.

To read the file line by line for loop statement is needed.

$xFileOutPath = “d:\xprocess.txt”
$xImportVariable = Get-Content $xFileOutPath


The full path and the file name can be directly passed to Get-Content command.

To read the content of d:\xprocess.txt, this code snippet below will do it.


#=========================================

$xImportVariable = Get-Content “D:\xprocess.txt”

#$Line can be any variable name
ForEach ($Line In $xImportVariable)
{

#Just read the file line by line to just to check the contents of xprocess.txt and display each line to the console
       write-host $Line
}

#=========================================               
   
Goal number 2, Check the output of the command line (Checked=Done)


To check “Notepad.exe” or any string from the file, “.Contains” parameter will make it quite simple to find the string.

Check out this link from Technet to dig further:
http://technet.microsoft.com/en-us/library/ee692804.aspx

$xFindString = $Line.Contains("notepad.exe")

Command above as it is read literally, will check “notepad.exe” from the variable $Line and put the value to $xFindString.



Code snippet to read each line and search for a specified string:              
#=========================================                   

$xImportVariable = Get-Content “D:\xprocess.txt”

#$Line can be any variable name
ForEach ($Line In $xImportVariable)
{ #For Loop Begin
#Just read the file line by line to just to check the contents of xprocess.txt
       write-host $Line      
#Read each line to check for notepad.exe    
#$xFindString will hold a Boolean value of either true or false  
       $xFindString = $Line.Contains("notepad.exe")
      
#use if then else to evaluate
       if ($xFindString –eq  $True)
       {
         write-Host "String Found"
       } 
           else
       {   
         Write-Host " String Not Found"
       }                  
      
} #For Loop End

#=========================================                
   
Goal number3, If the process is present or found on the output (Checked=Done)

Sample output generated by the code snippet above.

This line is the output of      “write-host $Line”:      
chrome.exe                    3556 Console                    1     74,596 K

This line is generated by  if then else statement:
 String Not Found

This line is the output of      “write-host $Line”:      
notepad.exe                   2560 Console                    1      7,040 K

This line is generated by if then else statement:
String Found


The 3 goals 1 to 3 have been done.
- 1. Run a command line using PowerShell
- 2. Check the output of the command line
- 3. If the process is present or found on the output
- 4. Run again a command line to terminate the process


Down to 1 step and case is closed.


In order to check the steps or the processes Write-Host is a friendly command, to view the output.

Goal number 4 is to run a command line and terminate the process.

Taskkill.exe is a command line to terminate a process.

In PowerShell “Stop-Process” cmdlet is used to terminate a process.

Anyway to use command line in PowerShell, this command  Taskkill /IM “notepad.exe” will be used to terminate the notepad.exe process or processes.

#=========================================                   

$xCmdStopProcess = {Taskkill /IM “notepad.exe”}

$xFileOutPath = “d:\xprocess.txt”

$xImportVariable = Get-Content $xFileOutPath

                                               
#$Line can be any variable name

ForEach ($Line In $xImportVariable)
{ #For Loop Begin

#Just read the file line by line to just to check the contents of xprocess.txt
       #write-host $Line                                 

#Read each line to check for notepad.exe    

#$xFindString will hold a Boolean value of either true or false  
       $xFindString = $Line.Contains("notepad.exe")
      
#use if then else to evaluate
       if ($xFindString –eq  $True)

       {

        #will  run the command line taskkill stop all notepad processes
       Invoke-Command $xCmdStopProcess

        #Exit command still exit or quit PowerShell
        #Exit the script Job is Done
        Exit
         #write-Host "String Found"
       } 

         #else statement is not needed since nothing will be done if false is found
         # else
         #{   
         # Write-Host " String Not Found"
         #}               
      
} #For Loop End

#=========================================                   

Goal number 4, Run again a command line to terminate the process (Checked=Done)

To wrap things out, this is the final script.

A script that will terminate all the running processes specified on the variable using command line via PowerShell.

#=========================================                   

#Get the running processes and save to txt file
$xCmdString = {Tasklist  > d:\xprocess.txt}

Invoke-Command $xCmdString


$xCmdStopProcess = {Taskkill /IM “notepad.exe”}

#Get the content of the text file
$xFileOutPath = “d:\xprocess.txt”
$xImportVariable = Get-Content $xFileOutPath
                                               

#Read each line and find the string or the process to terminate
ForEach ($Line In $xImportVariable)

{ #For Loop Begin


#Read each line to check for notepad.exe    
#$xFindString will hold a Boolean value of either true or false  

       $xFindString = $Line.Contains("notepad.exe")
      
#use if then else to evaluate

      if ($xFindString –eq  $True)
       {

        #will  run the command line taskkill stop all notepad processes
        Invoke-Command $xCmdStopProcess

        #Exit command still exit or quit PowerShell
        #Exit the script Job is Done

        Exit

       } 
     
} #For Loop End

#=========================================                    

Sample output generated by the final script:
SUCCESS: Sent termination signal to the process "notepad.exe" with PID 4548.
SUCCESS: Sent termination signal to the process "notepad.exe" with PID 2560.
SUCCESS: Sent termination signal to the process "notepad.exe" with PID 3944.
SUCCESS: Sent termination signal to the process "notepad.exe" with PID 5940.
SUCCESS: Sent termination signal to the process "notepad.exe" with PID 3496.
SUCCESS: Sent termination signal to the process "notepad.exe" with PID 6360.

#=========================================

Try this command parameter on how to lock a computer via PowerShell:

    $xCmdString = {rundll32.exe user32.dll,LockWorkStation}


    Invoke-Command $xCmdString

It will lock the workstation where the PowerShell is executed.




Learning PowerShell is fun!


Hope it helps!! Cheers!! 

Click on the PowerShell label below for more scripts..

Comments

Popular posts from this blog

Notepad++ convert multiple lines to a single line and vice versa

Notepad++ is an awesome text editing tool, it can accept regex to process the text data. If the data is in a “.csv” format or comma separated values which is basically just a text file that can either be opened using a text editor, excel or even word. Notepad++ can process the contents of the file using regex. Example if the data has multiple rows or lines, and what is needed is to convert the whole lines of data into a single line. Notepad++ can easily do it using regex. However, if the data is on a single line and it needs to be converted into multiple lines or rows then regex can also be used for this case. Here’s an example on how to convert multiple rows or lines into a single line. Example data: Multiple rows, just a sample data. Press Ctrl+H, and  on "Find what" type: [\r\n]+ and on "Replace with" type with: , (white space) --white space is needed if need to have a space in between the data. See image below, "Regular Expression" must be se

WMIC get computer name

WMIC get computer model, manufacturer, computer name and  username. WMIC is a command-line tool and that can generate information about computer model, its manufacturer, its username and other informations depending on the parameters provided. Why would you need a command line tool if there’s a GUI to check? If you have 20 or 100 computers, or even more. It’s quite a big task just checking the GUI to check the computer model and username. If you have remote computers, you need to delegate someone in the remote office or location to check. Or you can just write a batch file or script to automate the task. Here’s the code below on how get computer model, manufacturer and the username. Open an elevated command prompt and type:     wmic computersystem get "Model","Manufacturer", "Name", "UserName" Just copy and paste the code above, the word “computersystem” does not need to be change to a computer name. A

How to check office version from command line

The are quite a few ways to check office version it can be done via registry, PowerShell or VBScript and of course, good old command line can also do it. Checking Windows office version whether it is Office 2010, Office, 2013, Office 2016 or other version is quite important to check compatibility of documents; or just a part of software inventory. For PowerShell this simple snippet can check the office version: $ol = New-Object -ComObject Excel.Application $ol . Version The command line option will tell you where’s the path located; the result will also tell whether office is 32-bit, 64-bit and of course the version of the office as well. Here’s the command that will check the office version and which program directory the file is located which will tell whether it’s 32-bit or 64-bit. Command to search for Excel.exe: DIR C:\ /s excel.exe | find   /i "Directory of"  Above command assumes that program files is on  C: drive. Sample Outpu