Ready to Start Your Career?

Poweshell Scripts: Useful Features

Divya Bora's profile image

By: Divya Bora

July 15, 2021

windows powershell

Windows Powershell is an object-oriented automation engine and scripting language designed mainly for IT professionals and system administrators to control and automate Windows administration and other applications. It also provides new concepts to enhance the knowledge and scripts within the Windows command prompt. It is a perfect combination of flexible scripting, command-line speed, and a powerful GUI-based admin tool. It helps one to solve problems with efficiency eliminating manual labor hours.

Powershell provides a well-integrated command-line experience for the operating system and allows complete access to all types in the .NET framework. Powershell is more secure than running VBScript or other scripting language and is trusted by system administrators. It is an easier way to manipulate server and workstation components.

FEATURES OF POWERSHELL

A few features of Powershell are:

  • Background Job: The whole concept of background jobs running scripts and cmdlets asynchronously on a remote or local machine without addicting the user interface or interacting with the console was introduced by Windows Powershell.

  • Tab Expansion: the user can use the Tab key to complete the cmdlets, parameter names, and properties. It's an implementation of auto-completion.

  • Constrained runspaces: This means that a set of constraints, such as the ability to access and execute scripts, cmdlets, and language elements will allow the user to create Powershell runspaces.

  • Windows Powershell Web access: allows the execution of PowerShell cmdlets from any browser. It is available for desktops, tablets, and mobile devices.

  • Transactions: users can indicate which command is a part of the transaction and allows others to either roll back or commit a transaction.

  • Network file transfer: support provides for prioritized and asynchronous file transfer between machines through Background Intelligent Transfer Service(BITS).

  • Steppable pipeline: scripts can be split into blocks and given the option to call the begin(), process(), and end() methods of script block to control the execution sequence.

  • Script debugging: users can examine the script, function, expressions, or command while it's running. Also, it includes the set of cmdlets that allow to set and manage breakpoints and view the call stack.

  • Error Handling: Just like .NET language, Powershell also provides error handling mechanism through the Try{ }, Catch{ } and Finally{ } blocks.

  • Windows Powershell Workflow: enables the user to perform effort and time-consuming, complex tasks across multiple devices at various locations.

  • Windows Powershell Integrated Scripting Environment(ISE): includes features like tab completion, selective execution, multiline editing, syntax coloring, context-sensitive help, and right to left language support.

  • Scheduled jobs: This feature is similar to background jobs, but the only difference is that background jobs need to be started manually, unlike scheduled jobs.

  • Powershell remoting: This allows the execution of cmdlets on remote systems to manage a group of remote computers from a single machine.

USEFUL POWERSHELL COMMANDS

Cmdlets, also known as Command let, is a lightweight command used in the Windows-based Powershell environment to gather information regarding various formats, configuring security, and basic reporting. Here are some basic PowerShell commands that will be useful:

1. Get-Command It is an easy way to use a reference cmdlet to display all the commands available for use in the current session. The syntax for the command is:

get-command

2. Get-Help This provides quick access to the required information about all the available commands. The syntax for the command is:

Get-Help [[-Name] ] [-Path ] [-Category <String[]>] [-Component <String[]>]

3. Set-Execution Policy Microsoft disabled scripting in the Powershell environment to prevent the execution of malicious scripts. To be able to write and execute scripts, developers use the Set-ExecutionPolicy. The syntax for the command is:

Get-ExecutionPolicy

The four types of security levels are:

  • a) Restricted: commands can be entered interactively only as it blocks scripts from running. It is the default security level.

  • b) Unrestricted: all the scripts are permitted to run as all the restrictions are removed from the execution policy.

  • c) All Signed: scripts are only permitted to run if a trustworthy publisher signs them.

  • d) Remote Signed: locally created scripts are permitted to run, and remotely created scripts are permitted to run only if a reputable publisher signs them.

4. Get-Service It provides information about the services that are installed on the system. The syntax for the command is:

Get-Service

5. ConvertTo-HTML The command extracts data for multiple purposes. First, we pipe the output from another command to the ConvertTo-HTML command and then use the -Property switch to specify the desired output properties required in the HTML file. We also need to provide the file name. The syntax for the command is:

get-xyz | convertto-html > xyz.htm invoke-item xyz.htm

6. Get-EventLog It is used to parse the machine's event logs and has various parameters like Verbose, Debug, ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable, -OutBuffer, and -OutVariable. The -Log switch follows the name of the log file to view a specific log. The syntax for the command is:

Get-EventLog -Log "Application"

7. Get-Process & Stop-Process Get-Process gets a list of all the currently running processes on the machine. It is useful to identify the problematic process. Stop-Process stops the frozen or non-responding processes. The syntax for the command is:

Stop-Process -processname notepad

This command will terminate all the currently running instances of Notepad.

Stop-Process -processname note*

This command will terminate all instances of Notepad and other processes beginning with the word "note."

8. Clear-History & Add-History This clears entries from the command history and can also be useful to delete specific commands also. The syntax for the command is:

Clear-History -Command help, *command

This command will delete commands that include "help" or end with "command."

Add-History adds entries to a session, and the syntax for the command is:

Add-History

9. Where-Object It enables the user to take a dataset and pass it further down to their pipeline for filtering. The syntax for the command is:

Get-Service | Where-Object {$_.Status -eq ‘Running’}

This command will display the list of services whose status is running.

10. Set-AuthenticodeSignature This adds an Authenticode signature to the script or file to secure the work in production and to prevent its modification. The syntax for the command is:

Set-AuthenticodeSignature xyzscript.ps1 @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] -IncludeChain “All” -TimestampServer “http://timestamp.verisign.com/scripts/tiemstamp.dll”

11. ForEach-Object It operates against every object mentioned in the specified group of input objects. The syntax of the command is:

Get-Process | ForEach-Object {Write-Host $_.name -foregroundcolor red}

This command displays a list of all the process names in red color.

12. Clear-Content Clear-Content deletes the content of an item. The syntax of the command is:

Clear-Content C:\Temp\Testing.txt

This command will delete the content of the "Testing.txt" file and retain the file.

Clear-Content -path * -filter *.TXT -force

In this case, It will clear the contents of all the files with the specified file extension, i.e., TXT files.

13. Checkpoint-Computer It sets a restore point on the machine while making major changes or running a dangerous experiment. Only one restore point is made every 24 hours, and on running the command again, it returns to the previous point. The syntax of the command is:

Checkpoint-Computer -Description “Checkpoint 1” -RestorePointType “Modify_Settings” Get-ComputerRestorePoint | format-list

14. Compare-Object This compares two objects directly and generates a report about the differences between the two sets. The syntax of the command is:

cd c:\temp $obj1 = "A", "B", "C", "D" $obj2 = "D", "E", "F", "G" Compare-Object $obj1 $obj2

15. ConvertFrom-StringData ConvertFrom-StringData converts a string that may contain one or more value pairs to a hash table. The syntax for the command is:

$settings = $TextData | ConvertFrom-StringData

In addition, it enables others to edit the settings without working in the script code directly.

16. ConvertTo-SecureString This converts an encrypted standard string to a secure string and converts plain text to a secure string. The syntax for the command is:

ConvertTo-SecureString [-String] SomeString

17. ConvertTo-XML It creates an XML-based representation of an object which is also known as serialization. The Given expression should write objects to the pipeline. The syntax for the command is:

Get-Date | ConvertTo-XML

This command converts the current data(which is a DateTime object) to XML format.

18. New-AppLockerPolicy This uses a list of file information and other rule creation options to create a new AppLocker policy. These five cmdlets help the user to interact with AppLocker:

  • a) New-AppLockerPolicy: creates a new AppLockerPolicy.
  • b) Set-AppLockerPolicy: setsAppLockerPolicy for a specified group policy object.
  • c) Test-AppLockerPolicy: determines that a user or group of users only performs actions based on the policy.
  • d) Get-AppLockerPolicy: gathers the required information from a list of files or event logs that creates AppLocker rules.
  • e) Get-AppLockerFileInformation: retrieves a local, domain, or effective AppLocker policy.

19. New-ItemProperty New-ItemProperty creates and sets the value of a new property of an item, for example, registry values or data. The syntax for the command is:

New-ItemProperty -Path “C:\temp\MonthlyExpenses” -Name “MayExpense” -value 1220

This command will set the specified value with the entry name as "MayExpense" in the "MonthlyExpense" file.

20. New-Object It creates an instance of a Microsoft .NET Framework or Component Object Model(COM) object. The syntax of the command is:

New-Object -TypeName System.Version -ArgumentList “1.2.3.4”

This command will create a "System.Version" object using the "1.2.3.4" string as the constructor.

Intro to Powershell Scripting will provide a complete overview of Powershell scripting and is specifically designed to strengthen the basics of Powershell for a beginner. For hands-on training, Advanced Powershell will be a perfect start.

REFERENCES

https://nsfocusglobal.com/Attack-and-Defense-Around-PowerShell-Event-Logging(Image 1) https://www.guru99.com/powershell-tutorial.html https://www.javatpoint.com/features-of-powershell https://stackify.com/powershell-commands-every-developer-should-know/ https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/?view=powershell-7.1

Schedule Demo
Build your Cybersecurity or IT Career
Accelerate in your role, earn new certifications, and develop cutting-edge skills using the fastest growing catalog in the industry