PowerShell : Useful Commands

A collection of commands and scripts I’ve found useful when working with Windows PowerShell.

Enable Scripts

By default scripting is disabled. You need to choose what type of scripts to accept:

  • Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  • AllSigned - Only scripts signed by a trusted publisher can be run.
  • RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  • Unrestricted - No restrictions; all Windows PowerShell scripts can be run.

For example.

PS C:\> Set-ExecutionPolicy Unrestricted

Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic. Do you want to change the execution
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y
PS C:\>

Sending Emails

A simple example of sending an email from Windows PowerShell.

$smtpServer = "smtp.example.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "me@example.com"
$msg.ReplyTo = "me@example.com"
$msg.subject = "Test Mail"
$msg.body = "This is a test mail."

Check if a process is running

Check is a process is running based on the executable name.

if(get-process | ?{$_.path -eq "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"}){
  # The process is running, so do something.
  Write-Host "FireFox is running!"

Check is a process is running based on the process name.

if(get-process firefox){
  # The process is running, so do something.
  Write-Host "FireFox is running!"

Kill a running process

Identify process of interest.

PS C:\> get-process firefox

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    276      44   110232      94772   315     1.39   3176 firefox

PS C:\>

Kill the process by name.

PS C:\> stop-process -name firefox -force

Kill the process by ID.

PS C:\> stop-process -id 3176 -force

Scheduling PowerShell scripts

Scheduling PowerShell scripts is similar to scheduling regular batch files. When using the Scheduled tasks dialog, remember to set the following parameters in the action.

  • Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  • Add arguments: C:\myscript.ps1

For more information see:

Back to the Top.