Powershell and command

Powershell and command DEFAULT

What is a PowerShell command (cmdlet)?

  • 2 minutes to read

Commands for PowerShell are known as cmdlets (pronounced command-lets). In addition to cmdlets, PowerShell allows you to run any command available on your system.

What is a cmdlet?

Cmdlets are native PowerShell commands, not stand-alone executables. Cmdlets are collected into PowerShell modules that can be loaded on demand. Cmdlets can be written in any compiled .NET language or in the PowerShell scripting language itself.

Cmdlet names

PowerShell uses a Verb-Noun name pair to name cmdlets. For example, the cmdlet included in PowerShell is used to get all the cmdlets that are registered in the command shell. The verb identifies the action that the cmdlet performs, and the noun identifies the resource on which the cmdlet performs its action.

Next steps

To learn more about PowerShell and how to find other cmdlets, see the PowerShell Bits tutorial Discover PowerShell.

For more information about creating your own cmdlets, see the following resources:

Script-based cmdlets

Compiled cmdlets (PowerShell SDK docs)

Sours: https://docs.microsoft.com/en-us/powershell/scripting/powershell-commands

Windows PowerShell vs. CMD: What&#;s The Difference?

Back in the day, booting the then-cutting-edge IBM from the floppy brought you to a green text screen with a cursor blinking at the familiar C:\> prompt. Hacking boot.ini and config.sys to get my games to run was my first introduction to programming.

Eventually that C:\> got replaced with a pretty GUI and boot from hard disk. That command prompt (CMD) still lived on for decades. Only recently did CMD get an upgrade, or replacement, with PowerShell, the shell application Microsoft introduced with Windows 7.

Get the Free PowerShell and Active Directory Essentials Video Course

I'd recommend this for both new and advanced PowerShell users. Building an AD tool is a great learning experience.

CMD served us well for a good long time, but PowerShell is like going straight from steam engines to autonomous battery powered cars.

Windows Command Prompt

Windows Command Prompt &#; also known as CMD – is the original shell for the Microsoft DOS operating system. CMD was the default shell until Windows 10 build when Microsoft made PowerShell the default option. CMD is one of the last remnants of the original MS-DOS operating system that Microsoft replaced

Windows PowerShell

powershell cmdlets positives

Windows PowerShell is the new Microsoft shell that combines the old CMD functionality with a new scripting/cmdlet instruction set with built-in system administration functionality. PowerShell cmdlets allow users and administrators to automate complicated tasks with reusable scripts. System administrators save significant time by automating administration tasks with PowerShell.

PowerShell vs. CMD

PowerShell vs. CMD is like comparing apples to kumquats. They are completely different, despite the illusion that the ‘dir’ command works the same way in both interfaces.

PowerShell uses cmdlets, which are self-contained programming objects that expose the underlying administration options inside of Windows. Before PowerShell, sysadmins navigated the GUI to find these options, and there was no way to reuse the workflow of clicking through the menus to change options on a large scale.

PowerShell uses pipes to chain together cmdlets and share input/output data the same way as other shells, like bash in linux. Pipes allow users to create complex scripts that pass parameters and data from one cmdlet to another. Users can create reusable scripts to automate or make mass changes with variable data – a list of servers, for example.

One of the (many) neat functions of PowerShell is the ability to create aliases for different cmdlets. Aliases allow a user to configure their own names for different cmdlets or scripts, which makes it more straightforward for a user to switch back and forth between different shells: ‘ls’ is a linux bash command that displays directory objects, like the ‘dir’ command. In PowerShell, both ‘ls’ and ‘dir’ are an alias for the cmdlet ‘Get-ChildItem.’

what powershell uses

When to Use PowerShell

For systems administrators and other IT functions, PowerShell is the way to go. There isn’t any command left in CMD that isn’t in PowerShell, and PowerShell includes cmdlets for any administration function you could need. Third-party software vendors are extending PowerShell with custom cmdlets, like the NetApp PowerShell Toolkit that manages Data ONTAP.

PowerShell knowledge can be a differentiator for employment or even a job requirement, so it’s a worthwhile skill to invest in.

To get started on your PowerShell journey, check out this tutorial for the basics – and learn how to automate Active Directory tasks with our free PowerShell course by Adam Bertram, a Microsoft PowerShell MVP (pro-tip: use the code ‘blog’).

Jeff Petters

Jeff Petters

Jeff has been working on computers since his Dad brought home an IBM PC with dual disk drives. Researching and writing about data security is his dream job.

Sours: https://www.varonis.com/blog/powershell-vs-cmd/
  1. Eufy floodlight
  2. Vmware gaming
  3. Cummins isx liner problems
  4. Garden trough planters

Windows PowerShell is the new command-line shell, which is more powerful and scriptable than Command Prompt. In my three years of experience of using it, I found it really useful, especially if you are into automating or scripting tasks. However, most of us either do not know about it or do not prefer using it in place of the old command-line shell.

In this post, I am going to share useful yet straightforward commands (with examples) of Windows PowerShell. You can use these commands to accomplish numerous tasks — from getting help to starting processes. Shall we begin?

Note: Windows PowerShell is built with backward compatibility in mind, and thus supports many commands of the Command Prompt. That said, you can continue using the old commands in its new, colorful interface.

Read Also:Tips and Tools to Automate Repetitive Tasks on Windows 10

Get-Help [help]

If you are new to PowerShell, you may run into troubles; and in such situations, Get-Help becomes your savior. It provides necessary information about cmdlets, commands, functions, scripts, and workflows of the PowerShell.

Moreover, it’s easy: you need to type followed by the command, of which, you seek the details. For example, you can get information about “Get-Process” using .

How to use Get-Help

Get-Command [gcm]

Windows PowerShell allows discovering its commands and features using Get-Command. It displays the list of commands of a specific feature or for a specific purpose based on your search parameter.

You only need to type followed by your search query in the PowerShell. For example, displays commands with “-service” in its name. Please remember to use the asterisks on both sides of your query because it is a wild card that helps to search for the unknown.

How to use Get-Command

Invoke-Command [icm]

When you wish to run a command or a script of PowerShell — locally or remotely on single or multiple computer(s) — “Invoke-Command” is your friend. It is easy-to-use and helps you to batch-control computers.

You must type followed by the command or the script with its complete path. For example, you can run a command “Get-EventLog” using or on a remote computer “Server01” using .

How to use Invoke-Command

Invoke-Expression [iex]

Invoke-Expression runs another command or expression. If you are providing an expression or a string as its input, this command first evaluates it, then runs it, but also works only locally, unlike the previous command.

You must type followed by a command or an expression. For instance, you can assign a variable “$Command” with a string telling the command “Get-Process”. When you run , “Get-Process” gets run as a command on your local computer.

How to use Invoke-Expression

Invoke-WebRequest [iwr]

You can download, log in, and scrape for information on websites and web services while working on Windows PowerShell using the Invoke-WebRequest.

You must use it like followed by its parameters. For example, you can get the links on a given web page by using the command as .

How to use Invoke-WebRequest

Set-ExecutionPolicy

Although creating and executing scripts (having extension “ps1”) in Windows PowerShell is possible; however, there are restrictions for security purposes. But you can switch the security level using the Set-ExecutionPolicy command.

You can type followed by one of the four security levels — Restricted, Remote Signed, All Signed, or Unrestricted to use the command. For example, you can assign the restricted policy status using .

How to use Set-ExecutionPolicy

Get-Item [gi]

If you are looking for information on an item at any given location, say a file on your hard disk, Get-Item is the best way to acquire it in Windows PowerShell. You must know that it does not get the contents of the item, such as files and sub-directories in a given directory unless explicitly specified by you.

You must type followed by a path or a string along with its parameters if any. For example, you can get all the items (files or folders) beginning with “M” in the current directory using . Along with content of directories, it can also get the content of registry keys.

How to use Get-Item

Copy-Item [copy]

If you need to copy files and directories on your storage disk or registry entries and keys in the registry, you can use Copy-Item. It functions similar to the “cp” command we have in the Command Prompt, but it is much better.

You can make use of command to copy and rename items in the same command as well — give a new name as the destination. For instance, you can copy and rename “Services.htm” to “MyServices.txt” using .

Remove-Item [del]

If you wish to delete items such as files, folders, functions, and registry keys and variables, Remove-Item is the command for you. What I found interesting is, it provides parameters to include and exclude items.

You can make use of command to delete items from specific locations using parameters. For example, you can delete the file “MyServices.txt” with the command .

Get-Content [cat]

When you need to view the content of a text file at a specific location, you open and read it in a code/text editor like Notepad++. In Windows PowerShell, you can use Get-Content to retrieve the content without opening the file.

For example, you can retrieve 50 lines of content of “Services.htm”, then you can use .

Set-Content [sc]

You can save text to files using Set-Content, similar to the “echo” command of the Bash Shell. In combination with the Get-Content, you can also retrieve the content of one file and copy it into another file using this command.

For example, you can type to write or replace the content of a file with new content. Moreover, you can club it with the previous command’s example to save its output into a new file named “Sample.txt” using .

How to use Set-Content

Get-Variable [gv]

If you are looking to use variables in Windows PowerShell, Get-Variable command helps you to visualize the values of variables. It shows them in a tabular form and allows including, excluding, and using wildcards.

You can use this command by typing followed by its options and parameters. For example, you can retrieve the value for a variable named “desc” using the following code: .

Set-Variable [set]

You can assign or change/reset the value of a variable using the command Set-Variable. As a shortcut, you can also set a simple variable using the format ${ $VarName = VarValue }$, like .

You can use the command followed by its parameters to set a variable. For instance, we can set the value for a variable named “desc” using the command .

How to use Set-Variable

Get-Process [gps]

We usually use Task Manager to find the running processes on our computer. In Windows PowerShell, anyone can use Get-Process to get the list of currently running processes, which you can further process as well.

You can write the command as along with your search query. For example, if you need information about the processes with “explore” in their name, you can type (note the asterisks).

Start-Process [saps]

Windows PowerShell makes it easy to start one or more processes on your computer. I found this command is handy in scripting apps since it is one of the must-have commands you will need for automating a task.

You can type followed by its parameters to use the command. For instance, you can start Notepad by typing in the Windows PowerShell.

How to use Start-Process

Stop-Process [kill]

You can stop specific or all instances of a process running on your computer using its name or PID (Process ID), thanks to the command Stop-Process. What makes it compelling is, you can detect a process is stopped or not and you can even stop the processes not owned or started by the current user.

You can type the command followed by its parameters to stop the given processes. For example, you can stop all the processes of Notepad using the command .

Get-Service [gsv]

When you need information on specific services (running or stopped) on your computer, you can use Get-Service. It displays the services installed in your system and provides options to filter and include and exclude them.

If you wish to use this command, you can type followed by its parameters. For example, type the following to get the services “running” on your system.

How to use Get-Service

Start-Service [sasv]

If you wish to start a service on your computer, Start-Service command can help you do the same from Windows PowerShell. I found it is powerful enough to start a service even if that service is disabled on your computer.

You need to specify the name of the service while using the command . For instance, starts the service “Windows Search” on your local computer.

Stop-Service [spsv]

If you wish to stop services running on your computer, Stop-Service command will prove helpful. You need to specify the name of the service along with . For instance, type to stop the service “Windows Search” on your computer.

How to use Stop-Service

ConvertTo-HTML

PowerShell can provide amazing information about your system. However, it is mostly presented in an indigestible format, but you can use ConvertTo-HTML to create and format a report to analyze it or send it to someone.

You can use along with the output of another command using piping. For example displays the list of all the services and their status in the form of a web report, which is stored in the file “Services.htm”.

How to use ConvertTo-HTML
Sours: https://www.hongkiat.com/blog/windows-powershell-commands/
PowerShell For Beginners Full Course - PowerShell Beginner tutorial Full Course

PowerShell Commands

Get-ChildItemdir, gci, ls

Gets the files and folders in a file system drive.

Cmdlet

Invoke-Commandicm

Runs commands on local and remote computers.

Cmdlet

Import-Moduleipmo

Adds modules to the current session.

Cmdlet

Export-Csvepcsv

Converts objects into a series of comma-separated (CSV) strings and saves the strings in a CSV file.

Cmdlet

Write-Host

Writes customized output to a host.

Cmdlet

Get-WmiObjectgwmi

Gets instances of WMI classes or information about the available classes.

Cmdlet

Get-Contentcat, gc, type

Gets the contents of a file.

Cmdlet

Get-Date

Gets the current date and time.

Cmdlet

Invoke-WebRequestcurl, iwr, wget

Gets content from a web page on the Internet.

Cmdlet

Start-Processsaps, start

Starts one or more processes on the local computer.

Cmdlet

Copy-Itemcopy, cp, cpi

Copies an item from one location to another.

Cmdlet

Set-ExecutionPolicy

Changes the user preference for the Windows PowerShell execution policy.

Cmdlet

Out-File

Sends output to a file.

Cmdlet

Where-Object?, where

Selects objects from a collection based on their property values.

Cmdlet

Import-Csvipcsv

Creates table-like custom objects from the items in a CSV file.

Cmdlet

Send-MailMessage

Sends an email message.

Cmdlet

New-Object

Creates an instance of a Microsoft .NET Framework or COM object.

Cmdlet

Select-Stringsls

Finds text in strings and files.

Cmdlet

Remove-Itemdel, erase, rd, ri, rm, rmdir

Deletes files and folders.

Cmdlet

Select-Objectselect

Selects objects or object properties.

Cmdlet

Test-Path

Determines whether all elements of a file or directory path exist.

Cmdlet

Invoke-RestMethodirm

Sends an HTTP or HTTPS request to a RESTful web service.

Cmdlet

Install-Package

Installs one or more software packages.

Cmdlet

ForEach-Object%, foreach

Performs an operation against each item in a collection of input objects.

Cmdlet

Write-Outputecho, write

Sends the specified objects to the next command in the pipeline. If the command is the last command in thepipeline, the objects are displayed in the console.

Cmdlet

Get-Processgps, ps

Gets the processes that are running on the local computer or a remote computer.

Cmdlet

Get-Servicegsv

Gets the services on a local or remote computer.

Cmdlet

Format-Tableft

Formats the output as a table.

Cmdlet

Test-Connection

Sends ICMP echo request packets ("pings") to one or more computers.

Cmdlet

New-Itemni

Creates a new item.

Cmdlet

Get-EventLog

Gets the events in an event log, or a list of the event logs, on the local or remote computers.

Cmdlet

Get-WinEvent

Gets events from event logs and event tracing log files on local and remote computers.

Cmdlet

Install-Module

Downloads one or more modules from an online gallery, and installs them on the local computer.

Function

Enter-PSSessionetsn

Starts an interactive session with a remote computer.

Cmdlet

Get-Credential

Gets a credential object based on a user name and password.

Cmdlet

Read-Host

Reads a line of input from the console.

Cmdlet

Get-AppxPackage

Gets a list of the app packages that are installed in a user profile.

Cmdlet

Get-Acl

Gets the security descriptor for a resource, such as a file or registry key.

Cmdlet

Get-Help

Displays information about Windows PowerShell commands and concepts.

Cmdlet

Start-Jobsajb

Starts a Windows PowerShell background job.

Cmdlet

Add-PSSnapin

Adds one or more Windows PowerShell snap-ins to the current session.

Cmdlet

New-PSSessionnsn

Creates a persistent connection to a local or remote computer.

Cmdlet

Invoke-Expressioniex

Runs commands or expressions on the local computer.

Cmdlet

Add-Contentac

Appends content, such as words or data, to a file.

Cmdlet

New-PSDrivemount, ndr

Creates temporary and persistent mapped network drives.

Cmdlet

Move-Itemmi, move, mv

Moves an item from one location to another.

Cmdlet

Get-Itemgi

Gets files and folders.

Cmdlet

Compare-Objectcompare, diff

Compares two sets of objects.

Cmdlet

Sort-Objectsort

Sorts objects by property values.

Cmdlet

Test-NetConnection

Displays diagnostic information for a connection.

Function

Set-Acl

Changes the security descriptor of a specified item, such as a file or a registry key.

Cmdlet

Set-Contentsc

Replaces the contents of a file with contents that you specify.

Cmdlet

Start-Transcript

Creates a record of all or part of a Windows PowerShell session to a text file.

Cmdlet

Get-HotFix

Gets the hotfixes that have been applied to the local and remote computers.

Cmdlet

Get-ItemPropertygp

Gets the properties of a specified item.

Cmdlet

Add-Member

Adds custom properties and methods to an instance of a Windows PowerShell object.

Cmdlet

Remove-AppxPackage

Removes an app package from a user account.

Cmdlet

Rename-Itemren, rni

Renames an item in a Windows PowerShell provider namespace.

Cmdlet

Add-Type

Adds a.NET Framework type (a class) to a Windows PowerShell session.

Cmdlet

Get-Membergm

Gets the properties and methods of objects.

Cmdlet

ConvertTo-SecureString

Converts encrypted standard strings to secure strings. It can also convert plain text to secure strings. It isused with ConvertFrom-SecureString and Read-Host.

Cmdlet

New-SelfSignedCertificate

Creates a new self-signed certificate for testing purposes.

Cmdlet

Start-Sleepsleep

Suspends the activity in a script or session for the specified period of time.

Cmdlet

Restart-Computer

Restarts ("reboots") the operating system on local and remote computers.

Cmdlet

Out-GridViewogv

Sends output to an interactive table in a separate window.

Cmdlet

Format-Listfl

Formats the output as a list of properties in which each property appears on a new line.

Cmdlet

Set-ItemPropertysp

Creates or changes the value of a property of an item.

Cmdlet

Measure-Objectmeasure

Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such asfiles of text.

Cmdlet

Split-Path

Returns the specified part of a path.

Cmdlet

Get-Counter

Gets performance counter data from local and remote computers.

Cmdlet

Get-CimInstance

Gets the CIM instances of a class from a CIM server.

Cmdlet

Add-Computer

Add the local computer to a domain or workgroup.

Cmdlet

Add-AppxPackage

Adds a signed app package to a user account.

Cmdlet

ConvertTo-Html

Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser.

Cmdlet

Import-StartLayout

Imports the layout of the Start into a mounted Windows image.

Cmdlet

Set-Locationcd, chdir, sl

Sets the current working location to a specified location.

Cmdlet

Get-NetAdapter

Gets the basic network adapter properties.

Function

Export-StartLayout

Exports the layout of the Start screen.

Cmdlet

Enable-PSRemoting

Configures the computer to receive remote commands.

Cmdlet

Get-Commandgcm

Gets all commands.

Cmdlet

Get-ExecutionPolicy

Gets the execution policies for the current session.

Cmdlet

Join-Path

Combines a path and a child path into a single path.

Cmdlet

Import-PSSessionipsn

Imports commands from another session into the current session.

Cmdlet

Get-FileHash

Computes the hash value for a file by using a specified hash algorithm.

Function

Write-Error

Writes an object to the error stream.

Cmdlet

Stop-Servicespsv

Stops one or more running services.

Cmdlet

Stop-Processkill, spps

Stops one or more running processes.

Cmdlet

Start-Servicesasv

Starts one or more stopped services.

Cmdlet

Unblock-File

Unblocks files that were downloaded from the Internet.

Cmdlet

Get-Disk

Gets one or more disks visible to the operating system.

Function

Get-Modulegmo

Gets the modules that have been imported or that can be imported into the current session.

Cmdlet

ConvertTo-Json

Converts an object to a JSON-formatted string.

Cmdlet

New-WebServiceProxy

Creates a Web service proxy object that lets you use and manage the Web service in Windows PowerShell.

Cmdlet

Reset-ComputerMachinePassword

Resets the machine account password for the computer.

Cmdlet

Get-ScheduledTask

Gets the task definition object of a scheduled task that is registered on the local computer.

Function

Write-EventLog

Writes an event to an event log.

Cmdlet

Set-Service

Starts, stops, and suspends a service, and changes its properties.

Cmdlet

Out-String

Sends objects to the host as a series of strings.

Cmdlet

Get-Printer

Retrieves a list of printers installed on a computer.

Function

Out-Null

Deletes output instead of sending it down the pipeline.

Cmdlet

Resolve-DnsName

undefined

Cmdlet

Get-WindowsUpdateLog

Merges Windows Update .etl files into a single log file.

Function

Restart-Service

Stops and then starts one or more services.

Cmdlet

Set-Variableset, sv

Sets the value of a variable. Creates the variable if one with the requested name does not exist.

Cmdlet

Compress-Archive

Creates an archive, or zipped file, from specified files and folders.

Function

ConvertFrom-Json

Converts a JSON-formatted string to a custom object.

Cmdlet

New-SmbShare

Creates an SMB share.

Function

Set-Itemsi

Changes the value of an item to the value specified in the command.

Cmdlet

Update-Help

Downloads and installs the newest help files on your computer.

Cmdlet

Group-Objectgroup

Groups objects that contain the same value for specified properties.

Cmdlet

Start-BitsTransfer

Creates a BITS transfer job.

Cmdlet

Get-Certificate

Submits a certificate request to an enrollment server and installs the response or retrieves a certificate for apreviously submitted request.

Cmdlet

Register-ScheduledTask

Registers a scheduled task definition on a local computer.

Function

Tee-Objecttee

Saves command output in a file or variable and also sends it down the pipeline.

Cmdlet

Test-ComputerSecureChannel

Tests and repairs the secure channel between the local computer and its domain.

Cmdlet

Measure-Command

Measures the time it takes to run script blocks and cmdlets.

Cmdlet

ConvertFrom-SecureString

Converts a secure string to an encrypted standard string.

Cmdlet

Get-Jobgjb

Gets Windows PowerShell background jobs that are running in the current session.

Cmdlet

Export-Clixml

Creates an XML-based representation of an object or objects and stores it in a file.

Cmdlet

ConvertTo-Csv

Converts objects into a series of comma-separated value (CSV) variable-length strings.

Cmdlet

Remove-AppxProvisionedPackage

Removes an app package (.appx) from a Windows image.

Cmdlet

New-ItemProperty

Creates a new property for an item and sets its value.

Cmdlet

Get-PhysicalDisk

Gets a list of all PhysicalDisk objects visible across any available Storage Management Providers, or optionally afiltered list.

Function

Set-TimeZone

Sets the system time zone to a specified time zone.

Cmdlet

Get-Package

Returns a list of all software packages that have been installed by using Package Management.

Cmdlet

Get-SmbShare

Retrieves the SMB shares on the computer.

Function

Get-Variablegv

Gets the variables in the current console.

Cmdlet

Add-Printer

Adds a printer to the specified computer.

Function

Resolve-Pathrvpa

Resolves the wildcard characters in a path, and displays the path contents.

Cmdlet

Select-Xml

Finds text in an XML string or document.

Cmdlet

Get-Random

Gets a random number, or selects objects randomly from a collection.

Cmdlet

Get-PSDrivegdr

Gets drives in the current session.

Cmdlet

Expand-Archive

Extracts files from a specified archive (zipped) file.

Function

Receive-Jobrcjb

Gets the results of the Windows PowerShell background jobs in the current session.

Cmdlet

New-NetFirewallRule

Creates a new inbound or outbound firewall rule and adds the rule to the target computer.

Function

New-NetIPAddress

Creates and configures an IP address.

Function

Get-NetIPAddress

Gets the IP address configuration.

Function

Register-ObjectEvent

Subscribes to the events that are generated by a Microsoft .NET Framework object.

Cmdlet

Get-SmbConnection

Retrieves the connections established from the SMB client to the SMB servers.

Function

New-TimeSpan

Creates a TimeSpan object.

Cmdlet

Enable-WindowsOptionalFeature

Enables a feature in a Windows image.

Cmdlet

Set-NetConnectionProfile

Changes the network category of a connection profile.

Function

New-ScheduledTaskTrigger

Creates a scheduled task trigger object.

Function

Rename-Computer

Renames a computer.

Cmdlet

Get-Event

Gets the events in the event queue.

Cmdlet

Test-WSMan

Tests whether the WinRM service is running on a local or remote computer.

Cmdlet

Get-AppxProvisionedPackage

Gets information about app packages (.appx) in an image that will be installed for each new user.

Cmdlet

Wait-Process

Waits for the processes to be stopped before accepting more input.

Cmdlet

Wait-Jobwjb

Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the sessionare completed.

Cmdlet

Write-Debug

Writes a debug message to the console.

Cmdlet

Import-Certificate

Imports one or more certificates into a certificate store.

Cmdlet

New-EventLog

Creates a new event log and a new event source on a local or remote computer.

Cmdlet

Get-Host

Gets an object that represents the current host program.

Cmdlet

Invoke-WmiMethod

Calls WMI methods.

Cmdlet

Update-Script

Updates a script.

Function

New-Service

Creates a new Windows service.

Cmdlet

ConvertFrom-Csv

Converts object properties in comma-separated value (CSV) format into CSV versions of the original objects.

Cmdlet

Invoke-Itemii

Performs the default action on the specified item.

Cmdlet

Enable-WSManCredSSP

Enables CredSSP authentication on a computer.

Cmdlet

Get-Uniquegu

Returns unique items from a sorted list.

Cmdlet

Find-Package

Finds software packages in available package sources.

Cmdlet

Out-Hostoh

Sends output to the command line.

Cmdlet

Format-Volume

Formats one or more existing volumes or a new volume on an existing partition.

Function

Format-Customfc

Uses a customized view to format the output.

Cmdlet

Get-SmbServerConfiguration

Retrieves the SMB server configuration.

Function

Mount-DiskImage

Mounts a previously created disk image (virtual hard disk or ISO), making it appear as a normal disk.

Function

Clear-Hostclear, cls

Clears the display in the host program.

Function

Start-DscConfiguration

Applies configuration to nodes.

Cmdlet

Get-SmbOpenFile

Retrieves basic information about the files that are open on behalf of the clients of the SMB server.

Function

Add-VpnConnection

Adds a VPN connection to the Connection Manager phone book.

Function

Set-DnsClientServerAddress

Sets DNS server addresses associated with the TCP/IP properties on an interface.

Function

Export-ModuleMember

Specifies the module members that are exported.

Cmdlet

Get-PSSessiongsn

Gets the Windows PowerShell sessions on local and remote computers.

Cmdlet

Get-PSSnapin

Gets the Windows PowerShell snap-ins on the computer.

Cmdlet

Get-NetConnectionProfile

Gets a connection profile.

Function

Get-NetFirewallRule

Retrieves firewall rules from the target computer.

Function

Push-Locationpushd

Adds the current location to the top of a location stack.

Cmdlet

Get-Volume

Gets the specified Volume object, or all Volume objects if no filter is provided.

Function

New-NetLbfoTeam

Creates a new NIC team.

Function

Get-NetTCPConnection

Gets TCP connections.

Function

Stop-Computer

Stops (shuts down) local and remote computers.

Cmdlet

Set-StrictMode

Establishes and enforces coding rules in expressions, scripts, and script blocks.

Cmdlet

Set-NetFirewallRule

Modifies existing firewall rules.

Function

Add-AppxProvisionedPackage

Adds an app package (.appx) that will install for each new user to a Windows image.

Cmdlet

Enable-BitLocker

Enables encryption for a BitLocker volume.

Function

Get-Locationgl, pwd

Gets information about the current working location or a location stack.

Cmdlet

Set-NetIPInterface

Modifies an IP interface.

Function

New-VirtualDisk

Creates a new virtual disk in the specified storage pool.

Function

Remove-PSSessionrsn

Closes one or more Windows PowerShell sessions (PSSessions).

Cmdlet

Set-NetIPAddress

Modifies the configuration of an IP address.

Function

Register-ScheduledJob

Creates a scheduled job.

Cmdlet

Set-SmbServerConfiguration

Sets the SMB Service configuration.

Function

New-Partition

Creates a new partition on an existing Disk object.

Function

Remove-PSDriverdr

Deletes temporary Windows PowerShell drives and disconnects mapped network drives.

Cmdlet

Remove-Variablerv

Deletes a variable and its value.

Cmdlet

Get-WindowsOptionalFeature

Gets information about optional features in a Windows image.

Cmdlet

Import-Clixml

Imports a CLIXML file and creates corresponding objects in Windows PowerShell.

Cmdlet

Import-PfxCertificate

Imports certificates and private keys from a Personal Information Exchange (PFX) file to the destination store.

Cmdlet

Uninstall-Package

Uninstalls one or more software packages.

Cmdlet

Set-AuthenticodeSignature

Adds an Authenticode signature to a Windows PowerShell script or other file.

Cmdlet

Set-NetAdapter

Sets the basic network adapter properties.

Function

Set-Aliassal

Creates or changes an alias for a cmdlet or other command element in the current Windows PowerShell session.

Cmdlet

Set-WmiInstance

Creates or updates an instance of an existing Windows Management Instrumentation (WMI) class.

Cmdlet

Disable-WindowsOptionalFeature

Disables a feature in a Windows image.

Cmdlet

Update-Module

Downloads and installs the newest version of specified modules from an online gallery to the local computer.

Function

New-LocalUser

Creates a local user account.

Cmdlet

Mount-WindowsImage

Mounts a Windows image in a WIM or VHD file to a directory on the local computer.

Cmdlet

Get-ItemPropertyValuegpv

Gets the value for one or more properties of a specified item.

Cmdlet

New-Aliasnal

Creates a new alias.

Cmdlet

New-JobTrigger

Creates a job trigger for a scheduled job.

Cmdlet

Get-Historyghy, h, history

Gets a list of the commands entered during the current session.

Cmdlet

New-CimSession

Creates a CIM session.

Cmdlet

Get-LocalGroup

Gets the local security groups.

Cmdlet

ConvertTo-Xml

Creates an XML-based representation of an object.

Cmdlet

New-PSSessionOption

Creates an object that contains advanced options for a PSSession.

Cmdlet

Add-WindowsCapability

Installs a Windows capability package on the specified operating system image.

Cmdlet

New-Variablenv

Creates a new variable.

Cmdlet

Convert-Pathcvpa

Converts a path from a Windows PowerShell path to a Windows PowerShell provider path.

Cmdlet

Get-LocalGroupMember

Gets members from a local group.

Cmdlet

Add-WindowsPackage

Adds a single .cab or .msu file to a Windows image.

Cmdlet

Invoke-CimMethod

Invokes a method of a CIM class.

Cmdlet

ConvertFrom-StringCFS

Extracts and parses structured properties from string content.

Cmdlet

Export-Certificate

Exports a certificate from a certificate store into a file.

Cmdlet

Unregister-ScheduledTask

Unregisters a scheduled task.

Function

ConvertFrom-StringData

Converts a string containing one or more key and value pairs to a hash table.

Cmdlet

Install-PackageProvider

Installs one or more Package Management package providers.

Cmdlet

Get-LocalUser

Gets local user accounts.

Cmdlet

Clear-Contentclc

Deletes the contents of an item, but does not delete the item.

Cmdlet

Remove-Modulermo

Removes modules from the current session.

Cmdlet

Get-VpnConnection

Retrieves the specified VPN connection profile information.

Function

Export-PfxCertificate

Exports a certificate or a PFXData object to a Personal Information Exchange (PFX) file.

Cmdlet

Get-NetIPConfiguration

Gets IP network configuration.

Function

Export-WindowsDriver

Exports all third-party drivers from a Windows image to a destination folder.

Cmdlet

Grant-SmbShareAccess

Adds an allow ACE for a trustee to the security descriptor of the SMB share.

Function

Initialize-Disk

Initializes a RAW disk for first time use, enabling the disk to be formatted and used to store data.

Function

Get-NetIPInterface

Gets an IP interface.

Function

Get-PfxCertificate

Gets information about .pfx certificate files on the computer.

Cmdlet

Invoke-Pester

Invokes Pester to run all tests (files containing *.Tests.ps1) recursively under the Path

Function

Add-OdbcDsn

Adds an ODBC DSN.

Function

Format-Widefw

Formats objects as a wide table that displays only one property of each object.

Cmdlet

Get-Partition

Returns a list of all partition objects visible on all disks, or optionally a filtered list using specifiedparameters.

Function

Set-Disk

Takes a Disk object or unique disk identifiers and a set of attributes, and updates the physical disk on thesystem.

Function

Get-ScheduledJob

Gets scheduled jobs on the local computer.

Cmdlet

Get-PnpDevice

Returns information about PnP devices.

Function

Get-Tpm

Gets an object that contains information about a TPM.

Cmdlet

Disable-NetAdapterBinding

Disables a binding to a network adapter.

Function

Get-PSRepository

Gets PowerShell repositories.

Function

Out-Default

Sends the output to the default formatter and to the default output cmdlet.

Cmdlet

Add-PrinterDriver

Installs a printer driver on the specified computer.

Function

Set-WinUserLanguageList

Sets the language list and associated properties for the current user account.

Cmdlet

Get-ScheduledTaskInfo

Gets run-time information for a scheduled task.

Function

Enable-NetFirewallRule

Enables a previously disabled firewall rule.

Function

Out-Printerlp

Sends output to a printer.

Cmdlet

Add-PrinterPort

Installs a printer port on the specified computer.

Function

Set-WinSystemLocale

Sets the system locale (the language for non-Unicode programs) for the current computer.

Cmdlet

Find-Module

Finds modules from an online gallery that match specified criteria.

Function

Get-NetAdapterVmq
Sours: https://www.pdq.com/powershell/

And command powershell

PowerShell

Windows PowerShell is a task-based command-line shell and scripting language designed especially for system administration. Built on the .NET Framework, Windows PowerShell helps IT professionals and power users control and automate the administration of the Windows operating system and applications that run on Windows.

Using PowerShell.exe

The PowerShell.exe command-line tool starts a Windows PowerShell session in a Command Prompt window. When you use PowerShell.exe, you can use its optional parameters to customize the session. For example, you can start a session that uses a particular execution policy or one that excludes a Windows PowerShell profile. Otherwise, the session is the same as any session that is started in the Windows PowerShell console.

  • To start a Windows PowerShell session in a Command Prompt window, type . A PS prefix is added to the command prompt to indicate that you are in a Windows PowerShell session.

  • To start a session with a particular execution policy, use the ExecutionPolicy parameter, and type:

  • To start a Windows PowerShell session without your Windows PowerShell profiles, use the NoProfile parameter, and type:

  • To start a session , use the ExecutionPolicy parameter, and type:

  • To see the PowerShell.exe help file, type:

  • To end a Windows PowerShell session in a Command Prompt window, type . The typical command prompt returns.

Additional References

Feedback

View all page feedback

Sours: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/powershell
Windows PowerShell/Command Line for Beginners (Tutorial)

Many developers love PowerShell, and for good reason: it adds power, functionality, and flexibility to the Windows Command Prompt, where many of us spend a good deal of time. It does, however, come with a bit of a learning curve, but once you&#;ve mastered the essential commands you need to know, it&#;s productivity on steroids.

PowerShell commands are known as cmdlets, and these cmdlets are the driving force behind its functional capabilities. From commands that improve the overall Windows experience to commands useful for development work, there are dozens of important commands developers should know. We&#;ve put together this list to serve as a handy reference guide for those who are just beginning to tap into the power of PowerShell as well as those who want to level-up their PowerShell experience, including:

In addition to cmdlets, there are dozens of parameters and methods that help you get the most out of your scripts. The WhatIf parameter is particularly useful for testing PowerShell scripts without actually running them (@pluralsight). There are typically several parameters and methods available for each command. The commands listed below are a good starting point for any developer, but to fully realize the benefits, you should master parameters and other methods as well.


New call-to-action

Basic PowerShell Cmdlets

These basic PowerShell commands are helpful for getting information in various formats, configuring security, and basic reporting.

1. Get-Command

Get-Command is an easy-to-use reference cmdlet that brings up all the commands available for use in your current session.

Simply type in this command:

get-command

The output will look something like this (@MS_ITPro):

CommandType Name Definition Cmdlet Add-Content Add-Content [-Path] <String[ Cmdlet Add-History Add-History [[-InputObject] Cmdlet Add-Member Add-Member [-MemberType]

2. Get-Help

The Get-Help command is essential for anyone using PowerShell, providing quick access to the information you need to run and work with all of the available commands.

If you wanted some examples, for instance, you&#;d enter the following (@jp_jofre):

Get-Help [[-Name] <String>] [-Path <String>] [-Category <String[]>] [-Component <String[]>] [-Functionality <String[]>] [-Role <String[]>] [-Examples] [<CommonParameters>]

3. Set-ExecutionPolicy

Microsoft disables scripting by default to prevent malicious scripts from executing in the PowerShell environment. Developers want to be able to write and execute scripts, however, so the Set-ExecutionPolicy command enables you to control the level of security surrounding PowerShell scripts. You can set one of four security levels:

  • Restricted: This is the default security level which blocks PowerShell scripts from running. In this security level, you can only enter commands interactively.
  • All Signed: This security level allows scripts to run only if they are signed by a trustworthy publisher.
  • Remote Signed: In this security level, any PowerShell scripts that were created locally are permitted to run. Scripts created remotely are permitted to run only if they&#;ve been signed by a reputable publisher.
  • Unrestricted: As its name suggests, the unrestricted security level permits all scripts to run by removing all restrictions from the execution policy.

Similarly, if you&#;re working in an unfamiliar environment, you can easily find out what the current execution policy is using this command:

Get-ExecutionPolicy

Check out this thread on SuperUser for more information on configuring the execution policy in PowerShell. (@StackExchange)

4. Get-Service

It&#;s also helpful to know what services are installed on the system. You can easily access this information with the following command:

Get-Service

The output will look something like the following (@MS_ITPro):

Status Name DisplayName Running AdobeActiveFile Adobe Active File Monitor V4 Stopped Alerter Alerter Running ALG Application Layer Gateway Service Stopped AppMgmt Application Management Running ASChannel Local Communication Channel

If you need to know if a specific service is installed, you can append the -Name switch and the name of the service, and Windows will show the state of the service. Additionally, you can leverage filtering capabilities to return a specific subset of currently installed services. The following example will result in an output of data from the Get-Service command that&#;s been piped to the Where-Object cmdlet, which then filters out everything other than the services that have been stopped:

Get-Service | Where-Object {$_.status -eq "stopped"}

Check out this post for some additional examples of Get-Service in action.

5. ConvertTo-HTML

If you need to extract data that you can use in a report or send to someone else, the ConvertTo-HTML is one simple way to do so. To use it, pipe the output from another command to the ConvertTo-HTML command and use the -Property switch to specify which output properties you want in the HTML file. You&#;ll also need to provide a file name.

For example, the following code creates an HTML page that lists the PowerShell aliases in the current console:

PS C:\> get-alias | convertto-html > aliases.htm PS C:\> invoke-item aliases.htm

Bonus: The

Export-CSV

cmdlet functions in much the same way, but exports data to a .CSV file rather than HTML. Use

Select-Object

to specify which properties you want to be included in the output.

Check out this article from 4sysops for more information on using ConvertTo-HTML effectively (@adbertram).

6. Get-EventLog

You can actually use PowerShell to parse your machine&#;s event logs using the Get-EventLog cmdlet. There are several parameters available. Use the -Log switch followed by the name of the log file to view a specific log. You&#;d use the following command, for example, to view the Application log:

Get-EventLog -Log "Application"

Check out a few more examples of Get-EventLog in action in this post (@nextofwindows). Other common parameters include (@SS64):

  • -Verbose
  • -Debug
  • -ErrorAction
  • -ErrorVariable
  • -WarningAction
  • -WarningVariable
  • -OutBuffer
  • -OutVariable

7. Get-Process

Much like getting a list of available services, it&#;s often useful to be able to get a quick list of all the currently running processes. The Get-Process command puts this information at your fingertips.

Bonus: Use Stop-Process to stop processes that are frozen or is no longer responding. If you&#;re not sure what process is holding you up, use Get-Process to quickly identify the problematic process. Once you have the name or process ID, use Stop-Process to terminate it.

Here&#;s an example. Run this command to terminate all currently running instances of Notepad (@MS_ITPro):

Stop-Process -processname notepad

You can use wildcard characters, too, such as the following example which terminates all instances of Notepad as well as any other processes beginning with note:

Stop-Process -processname note*

Check out this post for more information on killing processes with PowerShell (@howtogeek):

8. Clear-History

What if you want to clear the entries from your command history? Easy – use the Clear-History cmdlet. You can also use it to delete only specific commands. For example, the following command would delete commands that include &#;help&#; or end in &#;command&#; (@MS_ITPro):

PS C:\> Clear-History -Command *help*, *command

If you want to add entries to a session, use:

Add-History

Check out this post for some useful information on clearing the history and pre-loading the history with a list of certain commands (@MS_ITPro).

9. Where-Object

Where-Object is one of the most important cmdlets to know, as it enables you to take a dataset and pass it further down your pipeline for filtering (@jonathanmedd):

Get-Service | Where-Object {$_.Status -eq 'Running'} Status Name DisplayName Running AdobeARMservice Adobe Acrobat Update Service Running AppHostSvc Application Host Helper Service Running Appinfo Application Information Running AudioEndpointBu Windows Audio Endpoint Builder Running Audiosrv Windows Audio Running BFE Base Filtering Engine Running BITS Background Intelligent Transfer Ser Running BrokerInfrastru Background Tasks Infrastructure Ser Running Browser Computer Browser Running CDPSvc Connected Devices Platform Service

 Set-AuthenticodeSignature

If you want to keep your work secure in production and prevent modification, use Set-AuthenticodeSignature to add an Authenticode signature to a script or file.

> Set-AuthenticodeSignature somescript.ps1 @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] -IncludeChain "All" -TimestampServer "http://timestamp.verisign.com/scripts/timstamp.dll"

PowerShell Commands for Getting Things Done

When it comes to productivity, PowerShell can help you get things done with the following commands.

 ForEach-Object

The ForEach-Object cmdlet performs an operation against every item in a specified group of input objects. While many cmdlets work with every object in a collection anyway, you&#;ll need ForEach-Object for those situations in which you want to make other modifications or apply specific formatting to all objects in a collection.

Here&#;s an example (@MS_ITPro). If you want to display a list of process names and want those names to render in cyan, you might try the following:

Get-Process | Write-Host $_.name -foregroundcolor cyan

But the above will produce the following error:

At line:1 char + get-process | write-host <<<< $_.name -foregroundcolor cyan Write-Host : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

Because the Write-Host cmdlet doesn&#;t understand what you want to do with the data that&#;s sent over the pipeline.

So, using the ForEach-Object cmdlet solves this problem:

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

Check out this tutorial for more information on ForEach-Object and working with loops (@tomsitpro).

 Clear-Content

If you want to delete the contents of an item but retain the item itself, you&#;ll use the Clear-Content cmdlet:

Clear-Content C:\Temp\TestFile.txt

You can also use this command to clear the contents of all files with a specified file extension. The following code would clear the contents of all files with the .txt extension, for instance:

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

You can also use wildcard characters. Plus, you can clear the contents of any type of file, from .txt files to .doc, .xls, and more.

Check out this post for more details.

 Checkpoint-Computer

If you&#;re making major changes or running a risky experiment, you can set a restore point on your machine with the Checkpoint-Computer cmdlet.

Note that you can only create a restore point using this cmdlet once every 24 hours. If you run the command again, it will keep the previous restore point:

PS C:\> Checkpoint-Computer -Description "My 2nd checkpoint" -RestorePointType "Modify_Settings" PS C:\> Get-ComputerRestorePoint | format-list __GENUS : 2 __CLASS : SystemRestore __SUPERCLASS : __DYNASTY : SystemRestore __RELPATH : SystemRestore.SequenceNumber=59 __PROPERTY_COUNT : 5 __DERIVATION : {} __SERVER : CLIENT2 __NAMESPACE : root\default __PATH : \\CLIENT2\root\default:SystemRestore.SequenceNumber=59 CreationTime : Description : My 2nd checkpoint EventType : RestorePointType : 12 SequenceNumber : 59

Check out this article from MCP Mag for more (@MCPmag).

Compare-Object

It&#;s often useful to be able to compare two objects directly. You can do this using Compare-Object, which generates a report on the differences between two sets such as (@Marcam):

PS G:\lee\tools> cd c:\temp PS C:\temp> $set1 = "A","B","C" PS C:\temp> $set2 = "C","D","E" PS C:\temp> Compare-Object $set1 $set2 InputObject SideIndicator D => E => A <= B <=

 ConvertFrom-StringData

Use ConvertFrom-StringData to convert a string containing one or more value pairs to a hash table. Here&#;s an example of what the command looks like:

$settings = $TextData | ConvertFrom-StringData

This command is useful in a variety of situations, such as when you want to save the settings for a PowerShell script to enable others to edit the settings without working in the script code directly.

ConvertTo-SecureString

Convert an encrypted standard string to a secure string or plain text to a secure string using ConvertTo-SecureString. This cmdlet is used in conjunction with ConvertFrom-SecureString and Read-Host (@AdmArsenal):

ConvertTo-SecureString [-String] SomeString ConvertTo-SecureString [-String] SomeString [-SecureKey SecureString] ConvertTo-SecureString [-String] SomeString [-Key Byte[]] ConvertTo-SecureString [-String] SomeString [-AsPlainText] [-Force]

ConvertTo-XML

Use the ConvertTo-XML cmdlet to create an XML-based representation of an object. This is also called serialization, and it&#;s a useful process for saving data for later re-use. Note that it&#;s important that your expression writes objects to the pipeline. Anything using Write-Host won&#;t write to the pipeline and therefore can&#;t be serialized. Here&#;s an example of ConvertTo-XML in action (@PetriFeed):

Get-Service wuauserv -ComputerName chi-dc04,chi-p50,chi-core01 | Export-Clixml -Path c:\work\wu.xml

The specific cmdlet used in the above example, Export-Clixml, is suitable for most purposes. It converts the output of a PowerShell expression to XML and saves it to a file.

 New-AppLockerPolicy

New-AppLockerPolicy creates a new AppLocker policy from a list of file information and other rule creation options. In total, there are five cmdlets that enable you to interact with AppLocker, including (@RootUsers_):

  • Get-AppLockerFileInformation: Gets the required information for creating AppLocker rules from a list of files or the event log.
  • Get-AppLockerPolicy: Used to retrieve a local, effective, or a domain AppLocker policy.
  • New-AppLockerPolicy: As mentioned, this cmdlet is used for creating new AppLocker policies.
  • Set-AppLockerPolicy: Sets the AppLocker policy for a specified group policy object.
  • Test-AppLockerPolicy: Used to determine if a user or group of users will be able to perform certain actions based on the policy.

 New-ItemProperty

New-ItemProperty creates a new property for an item and sets its value. You can use it to create and change registry values and data (properties of a registry key), for instance.

Check out this tutorial from mnaoumov.NET for some useful workarounds using this cmdlet (@mnaoumov).

 New-Object

To create an instance of a Microsoft .NET Framework or Component Object Model (COM) object, use the New-Object cmdlet.

Here&#;s an example that creates a new object using New-Object, stores it in a variable, then pipes it to Add-Member, which will then add properties or methods specified in the object created (@gngrninja):

$ourObject = New-Object -TypeName psobject $ourObject | Add-Member -MemberType NoteProperty -Name ComputerName -Value $computerInfo.Name $ourObject | Add-Member -MemberType NoteProperty -Name OS -Value $osInfo.Caption $ourObject | Add-Member -MemberType NoteProperty -Name 'OS Version' -Value $("$($osInfo.Version) Build $($osInfo.BuildNumber)") $ourObject | Add-Member -MemberType NoteProperty -Name Domain -Value $computerInfo.Domain $ourObject | Add-Member -MemberType NoteProperty -Name Workgroup -Value $computerInfo.Workgroup $ourObject | Add-Member -MemberType NoteProperty -Name DomainJoined -Value $computerInfo.Workgroup $ourObject | Add-Member -MemberType NoteProperty -Name Disks -Value $diskInfo $ourObject | Add-Member -MemberType NoteProperty -Name AdminPasswordStatus -Value $adminPasswordStatus $ourObject | Add-Member -MemberType NoteProperty -Name ThermalState -Value $thermalState

 New-WebServiceProxy

New-WebServiceProxy creates a web service proxy object that enables you to use and manage the web service from within PowerShell. This cmdlet is a beautiful thing for developers – it makes it unnecessary to write a lot of complex code to try to accomplish something in PowerShell when you can simply call another service that already makes it possible.

Here&#;s an example:

$url = http://<webapp>.azurewebsites.net/CreateSite.asmx $proxy = New-WebServiceProxy $url $spAccount = "<username>" $spPassword = Read-Host -Prompt "Enter password" –AsSecureString $projectGuid = "" $createOneNote = $false

Now, you can run the following to view a list of all available methods:

$proxy | gm -memberType Method

 New-WSManInstance

Similarly to New-WebServiceProxy, New-WSManInstance creates a new instance of a management resource.

New-WSManInstance winrm/config/Listener -SelectorSet @{Address="*";Transport="HTTPS"} -ValueSet @{Hostname="Test01";CertificateThumbprint="01F7EB07ADCE6ABF5"}

Check out this tutorial for a complete step-by-step example of how to get the information you need to execute this script successfully (@jonathanmedd).

 New-WSManSessionOption

New-WSManSessionOption creates a new management session hash table that&#;s used as input parameters to other WS-Management cmdlets including:

  • Get-WSManInstance
  • Set-WSManInstance
  • Invoke-WSManAction
  • Connect-WSMan

Here&#;s the syntax (@SAPIENTech):

New-WSManSessionOption [-NoEncryption] [-OperationTimeout] [-ProxyAccessType] [-ProxyAuthentication] [-ProxyCredential] [-SkipCACheck] [-SkipCNCheck] [-SkipRevocationCheck] [-SPNPort] [-UseUTF16] [<CommonParameters>]

Select-Object

The Select-Object cmdlet selects the specified properties of a single object or group of objects. Additionally, it can select unique objects from an array or a specified number of objects from the beginning or end of an array.

PS > Get-Process | Sort-Object name -Descending | Select-Object -Index 0,1,2,3,4

This tutorial provides more information about the various ways you can use Select-Object (@infosectactico).

There are other cmdlets with similar functions including:

  • Select-String: Finds text in strings or files.
  • Select-XML: Finds text in an XML string or document.

 Set-Alias

Set-Alias is a great command for enhancing productivity. It allows you to set an alias for a cmdlet or other command element in the current session (similar to a keyboard shortcut) so you can work faster.

The following example sets Notepad to np in the current session using Set-Alias (@powershellatoms):

New-Alias np c:\windows\system32\notepad.exe

Note that you can also customize your PowerShell profile with the aliases you use most often (@howtogeek).

 Set-StrictMode

Set-StrictMode establishes and enforces coding rules in scripts, script blocks, and expressions. It&#;s a useful command for enforcing code quality and preventing you from slacking off and writing sloppy code when it&#;s a.m. and you haven&#;t had any sleep in two days (@adbertram).

To use it, there are two parameters to consider: -Off and -Version, and -Version has three possible values:

  • Version  Prevents you from using variables that haven&#;t been initialized (such as Option Explicit in VBScript)
  • Version Prevents you from using variables that have not been initialized and also prevents the calling of non-existent properties on objects, prevents you from calling a function like a method, and prohibits the creation of variables without a name.
  • Version Latest: This option selects the latest StrictMode version available and uses it. This is a good option because it means that the latest StrictMode version is used regardless of the version of PowerShell you&#;re using.

Wait-Job

Wait-Job suppresses the command prompt until background jobs running in the current session are complete. Wait-Job doesn&#;t show the output from jobs, however, but it can be used in conjunction with Receive-Job. Multithreading is possible in PowerShell thanks to -Jobs.

### Start-MultiThread.ps1 ### $Computers = @("Computer1","Computer2","Computer3") #Start all jobs ForEach($Computer in $Computers){ Start-Job -FilePath c:ScriptGet-OperatingSystem.ps1 -ArgumentList $Computer } #Wait for all jobs Get-Job | Wait-Job #Get all job results Get-Job | Receive-Job | Out-GridView 1 2 3 4 5 6 7 8 9 10 11 12 13 ### Start-MultiThread.ps1 ### $Computers = @("Computer1","Computer2","Computer3") #Start all jobs ForEach($Computer in $Computers){ Start-Job -FilePath c:ScriptGet-OperatingSystem.ps1 -ArgumentList $Computer } #Wait for all jobs Get-Job | Wait-Job #Get all job results Get-Job | Receive-Job | Out-GridView

Write-Progress

Who doesn&#;t love a status bar? Monitor your progress using Write-Progress, which displays a progress bar within a Windows PowerShell command window.

Here&#;s an example that gives you a full progress bar and runtime strings (@credera):

$TotalSteps = 4 $Step = 1 $StepText = "Setting Initial Variables" $StatusText = '"Step $($Step.ToString().PadLeft($TotalSteps.Count.ToString().Length)) of $TotalSteps | $StepText"' $StatusBlock = [ScriptBlock]::Create($StatusText) $Task = "Creating Progress Bar Script Block for Groups" Write-Progress -Id $Id -Activity $Activity -Status (&amp; $StatusBlock) -CurrentOperation $Task -PercentComplete ($Step / $TotalSteps * )

Cmdlets for Performance Monitoring, Testing, and Debugging

There are also a variety of cmdlets useful for developers for troubleshooting, testing, debugging, and monitoring purposes. Here are a few you need to know.

Debug-Process

Developers love debugging! Well, we like it even more when there are no bugs to eliminate, but sadly that&#;s not always the case. With PowerShell, you can debug a process using the Debug-Process cmdlet.

You can also debug jobs using Debug-Job (@MS_ITPro). And, you can set breakpoints or use the Wait-Debugger cmdlet:

PS C:\> $job = Start-Job -ScriptBlock { Set-PSBreakpoint C:\DebugDemos\MyJobDemo1.ps1 -Line 8; C:\DebugDemos\MyJobDemo1.ps1 } PS C:\> $job PS C:\> Debug-Job $job

 Disable-PSBreakpoint

If you have at one time set breakpoints but want to eliminate them, do so easily using Disable-PSBreakpoint, which disables breakpoints in the current console. Here&#;s the syntax (@ActiveXperts):

Disable-PSBreakpoint [-Breakpoint] [-PassThru] [-Confirm] [-WhatIf] [] Disable-PSBreakpoint [-Id] [-PassThru] [-Confirm] [-WhatIf] []

Alternatively, if you want to enable breakpoints in the current console, use Enable-PSBreakpoint.

Get-Counter

Get-Counter gets real-time performance counter data from the performance monitoring instrumentation in Windows OS. It&#;s used to get performance data from local or remote computers at specific sample intervals that you specify.

In this example, you&#;ll get a counter set with a sample interval for a specified maximum sample (@MS_ITPro):

PS C:\> Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 3

In the example below, this command gets specific counter data from multiple computers:

The first command saves the **Disk Reads/sec** counter path in the $DiskReads variable. PS C:\> $DiskReads = "\LogicalDisk(C:)\Disk Reads/sec" The second command uses a pipeline operator (|) to send the counter path in the $DiskReads variable to the **Get-Counter** cmdlet. The command uses the **MaxSamples** parameter to limit the output to 10 samples. PS C:\> $DiskReads | Get-Counter -Computer Server01, Server02 -MaxSamples 10

 Export-Counter

Export-Counter exports PerformanceCounterSampleSet objects as counter log files. Two properties are available:

  • CounterSamples: Gets and sets the data for the counters.
  • Timestamp: Gets and sets the date and time when the sample data was collected.

And several methods, all of which are inherited from Object:

  • Equals(Object)
  • Finalize()
  • GetHashCode()
  • GetType()
  • MemberwiseClone()
  • ToString()

For example, the following command uses Get-Counter to collect Processor Time data and exports it to a .blg file using Export-Counter (@TechGenix):

Get-Counter "\Processor(*)\% Processor Time" | Export-Counter -Path C:\Temp\PerfData.blg

 Test-Path

Test-Path lets you verify whether items exist in a specified path. For instance, if you&#;re planning to use another command on a specified file, you may need to verify that the file exists to avoid throwing an error.

Test-Path C:\Scripts\Archive

If the folder exists, it will return True; if it doesn&#;t, it will return False.

It can also work with the paths used by other PowerShell providers. For instance, if you need to know if your computer has an environment variable called username,  you could use the following:

Test-Path Env:\username

Test-Path works with variables, certificates, aliases, and functions. Check out this post from TechNet for more details (@MS_ITPro).

 Get-WinEvent

Look at Windows event logs using Get-WinEvent. For a list of available logs, use:

Get-WinEvent -ListLog *

Then, to review the details of a specific log, replace * with the name (pipe the output to format-list to view all the details):

Get-WinEvent -ListLog $logname | fl *

You can also view all the events in a log by using:

Get-WinEvent -LogName System

Check out this tutorial for more details (@rakheshster).

Invoke-TroubleshootingPack

Troubleshooting packs are collections of PowerShell scripts and assemblies that help you troubleshoot, diagnose, and repair common system problems (@ITNinjaSite). Find troubleshooting packs at:

C:\Windows\Diagnostics\System

You can run this script to get a list of all the troubleshooting packs available on the current system (@TechGenix):

Get-ChildItem C:\Windows\Diagnostic\System

Then, from an elevated PowerShell window, run a troubleshooting pack using this command:

Invoke-TroubleshootingPack (Get-TroubleshootingPack C:\Windows\diagnostics\system\networking)

 Measure-Command

If you want to time operations in PowerShell, Measure-Command is a must-know cmdlet. It measures how long a script or scriptblock to run. Here&#;s an example (@ToddKlindt):

Measure-Command { Mount-SPContentDatabase –Name wss_content_portal –WebApplication http://portal.contoso.com }

The output is a TimeSpan object, so it contains properties such as Hour, Minute, Second, etc., and it&#;s easy to tailor the output to your preferences.

Measure-Object

You might also want to know how large a given object is. Use Measure-Object to calculate the numeric properties of any object, including characters, words, and lines in a string object, such as files of text.

Just specify the name and the type of measurement to perform, along with parameters such as (@WindowsITPro):

  • -Sum: adds values
  • -Average: calculates the average value
  • -Minimum: finds the minimum value
  • -Maximum: finds the maximum value

The following command sums the VirtualMemorySize property values for all process objects:

Get-Process | measure VirtualMemorySize -Sum

New-Event

New-Event is used to create a new event. A related cmdlet is New-EventLog, which creates a new event log as well as a new event source on a local or remote computer. If you have an automation engine supported by PowerShell, it&#;s a good practice to set up an event log (by creating a custom Event Log Type) that logs all messages sent by PowerShell. This is one example where you can implement Custom Logging in Event Viewer.

Start by creating a new Event Log LogName (@BundaloVladimir):

New-EventLog -LogName Troubleshooting_Log -Source FalloutApp

Then, to send messages to your new event log, run the following using the Write-Log cmdlet:

Write-EventLog -log Troubleshooting_Log -source FalloutApp -EntryType Information -eventID 10 -Message "FalloutApp has been successfully installed"

Receive-Job

If you need to get the results of Windows PowerShell background jobs in the current session, use Receive-Job. This is usually used after using Start-Job to begin a job when you need to view the specific results.

Receive-Job -Name HighMemProcess

Check out this helpful tutorial on using Receive-Job and what to do if there are seemingly no results (@proxb).

 Register-EngineEvent

This cmdlet is used to subscribe to the events generated by the Windows PowerShell engine and the New-Event cmdlet. For example, the following command subscribes to an event when the current PowerShell session exits and saves information (such as date and time) to a log file (@jonathanmedd):

Register-EngineEvent PowerShell.Exiting -Action {"PowerShell exited at " + (Get-Date) | Out-File c:\log.txt -Append}

 Register-ObjectEvent

Register-ObjectEvent is similar to Register-EngineEvent, but rather than subscribe to events generated by the PowerShell engine and New-Event, it subscribes to the events generated by a Microsoft .NET Framework Object.

Here&#;s an example (@NetworkWorld):

Register-ObjectEvent -InputObject $MyObject -EventName OnTransferProgress -SourceIdentifier Scp.OnTransferProgress ` -Action {$Global:MCDPtotalBytes = $args[3]; $Global:MCDPtransferredBytes = $args[2]} Register-ObjectEvent -InputObject $MyObject -EventName OnTransferEnd ` -SourceIdentifier Scp.OnTransferEnd -Action {$Global:MCDPGetDone = $True}

There are other Register- cmdlets that you may find useful including:

  • Register-PSSessionConfiguration: Creates and registers a new session configuration.
  • Register-WmiEvent: This cmdlet subscribes to a WMI event.

 Remove-Event

When you want to remove an event, use the Remove-Event cmdlet. If you need to remove an entire event log, you&#;d use Remove-EventLog, which deletes an event log or unregisters an event source.

Alternatively, Unregister-Event cancels an event subscription but does not delete an event from the event queue (@SS64).

 Set-PSDebug

This cmdlet turns script debugging features on and off. It also sets the trace level and toggles StrictMode.

By using Set-PSDebug at the top of your script file just after the param() statement (if any), you can prevent errors with scripts that PowerShell doesn&#;t provide adequate information about for troubleshooting purposes. Here&#;s an example (@r_keith_hill):

Set-PSDebug -Strict $Suceeded = test-path C:\ProjectX\Src\BuiltComponents\Release\app.exe if ($Succeded) { "yeah" } else { "doh" } PS C:\Temp> .\foo.ps1 The variable $Succeded cannot be retrieved because it has not been set yet. At C:\Temp\foo.ps char + if ($Succeded) <<<< {

 Start-Sleep

If you need to suspend the activity in a script or session, use Start-Sleep, which halts the activity for a specified time period.

Start-Sleep -Seconds xxx Start-Sleep -Milliseconds xxx

If you need to pause one or more running services, you&#;d use Suspend-Service.

 Tee-Object

If you&#;re analyzing performance or code quality, it&#;s useful to be able to view the output of a command. Tee-Object stores the command output in a file or variable and also displays it in the console if it&#;s the last variable in the pipeline. If it&#;s not the last variable in the pipeline, Tee-Object sends it down the pipeline.

Here&#;s the syntax:

Tee-Object [-FilePath] <string> [-InputObject <psobject>] [<CommonParameters>] Tee-Object -Variable <string> [-InputObject <psobject>] [<CommonParameters>]

 Test-AppLockerPolicy

Test-AppLockerPolicy evaluates whether input files are permitted to run for a specific user based on the specified AppLocker policy.

Test-AppLockerPolicy [-PolicyObject] -Path [-User ] [-Filter >] [] Test-AppLockerPolicy [-XMLPolicy] -Path [-User ] [-Filter ] [ arameters>]

This tutorial offers more details about the available parameters and examples of Test-AppLockerPolicy in action (@powershellhelp).

Test-ComputerSecureChannel

This cmdlet tests and repairs the connection between a local computer and its domain. Without this command, the usual solution was previously to remove a computer from its domain and then reconnect it in order to reestablish the relationship. Test-ComputerSecureChannel makes it possible to reestablish the connection in less time (@WindowsITPro).

When signed on as a local administrator, simply run the following:

Test-ComputerSecureChannel –credential WINDOWSITPRO\Administrator –Repair

You can use Test-Connection to send Internet Control Message Protocol (ICMP) echo request packets (pings) to one or more computers.

Test-Path

Use Test-Path to determine whether all elements of a path exist. Essentially, it helps you handle errors before they occur. In its simplest form, it returns True or False (@MCPmag):

PS C:\> test-path c:\ True PS C:\> test-path z:\foo False

 Trace-Command

Trace-Command configures and starts the trace of a specified command or expression. To use it, you&#;ll also need to use Get-TraceSource in order to look for particular names using wildcard characters:

PS&gt; Get-TraceSource -Name *param*

You can filter the output to match the description to the pattern you&#;re after. Once you&#;ve identified the possible trace name, you&#;ll use Trace-Command to get the answers you need. Here&#;s an example:

[CmdletBinding(DefaultParameterSetName = 'Host')] param ( # ScriptBlock that will be traced. [Parameter( ValueFromPipeline = $true, Mandatory = $true, HelpMessage = 'Expression to be traced' )] [ScriptBlock]$Expression, # Name of the Trace Source(s) to be traced. [Parameter( Mandatory = $true, HelpMessage = 'Name of trace, see Get-TraceSource for valid values' )] [ValidateScript({ Get-TraceSource -Name $_ -ErrorAction Stop })] [string[]]$Name, # Option to leave only trace information # without actual expression results. [switch]$Quiet, # Path to file. If specified - trace will be sent to file instead of host. [Parameter(ParameterSetName = 'File')] [ValidateScript({ Test-Path $_ -IsValid })] [string]$FilePath ) begin { if ($FilePath) { # assume we want to overwrite trace file $PSBoundParameters.Force = $true } else { $PSBoundParameters.PSHost = $true } if ($Quiet) { $Out = Get-Command Out-Null $PSBoundParameters.Remove('Quiet') | Out-Null } else { $Out = Get-Command Out-Default } } process { Trace-Command @PSBoundParameters | &amp; $Out } } PS&gt; New-Alias -Name tre -Value Trace-Expression PS&gt; Export-ModuleMember -Function * -Alias *

Check out this post for more details on playing detective with Trace-Command (@PowerShellMag).

 Write-Debug

Write-Debug writes a debug message to the console. When you write this in a function or script, it doesn&#;t do anything by default; the messages essentially lay in wait until you either modify your $DebugPreference or activate the -debug switch when calling a function or script. When $DebugPreference is set to &#;inquire&#; or the -debug switch is activated, the message creates a breakpoint, giving you an easy way to pop into debug mode.

Take this example (@RJasonMorgan):

function Get-FilewithDebug { [cmdletbinding()] Param ( [parameter(Mandatory)] [string]$path ) Write-Verbose "Starting script" Write-Debug "`$path is: $path" $return = Get-ChildItem -Path $path -Filter *.exe -Recurse -Force Write-Debug "`$return has $($return.count) items" $return }

The example above produces the following when run with -debug:

[C:\git] > Get-FilewithDebug -path C:\Users\jmorg_\ -Debug DEBUG: $path is: C:\Users\jmorg_\ Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"):

What PowerShell commands do you use most often in your development work? Share your go-to cmdlets with us in the comments below. Another essential tool to add to your dev toolkit is Stackify Prefix, a dynamic code profiler that is simple, free, and efficient.

Featured Image Copyright: enotmaks / RF Stock Photo

About Alexandra Altvater

  • What to Do About Java Memory Leaks: Tools, Fixes, and More- September 3,
  • What is Load Testing? How It Works, Tools, Tutorials, and More- February 5,
  • Americaneagle.com and ROC Commerce stay ahead with Retrace- September 25,
  • Stackify’s New Pricing: Everything you need to know- September 9,
  • INNOVATORS VS COVID 19 Matt Watson, the CEO at Stackify, advises Entrepreneurs to focus on the things that make them happy, regardless if work is a giant dumpster fire- September 2,
Sours: https://stackify.com/powershell-commands-every-developer-should-know/

Now discussing:

Windows PowerShell Commands Cheat Sheet

PowerShell Cheat Sheet

When it comes to running commands on Windows, PowerShell has become somewhat of an ace in the hole. For years enthusiasts were limited to the confines of the Windows command line but in , PowerShell emerged as a powerful alternative.

What is Windows PowerShell?

PowerShell is an interactive Command-Line Interface (CLI) and automation engine designed by Microsoft to help design system configurations and automate administrative tasks.

This tool has its own command-line with a unique programming language similar to Perl. Initially, PowerShell was designed to manage objects on users’ computers.

Today PowerShell offers users an extensive environment where they can execute and automate system management tasks. The user can access resources from Active Directory to Exchange Server through one program. At its core, PowerShell allows the user to access:

  • Command Prompt
  • PowerShell Commands
  • .NET Framework API
  • Windows Management Instrumentation
  • Windows Component Object Model

As PowerShell has become an open-source application, Linux and Unix-based users can now access this versatile platform. PowerShell’s is mainly used to help users automate administrative jobs. Rather than performing tedious and repetitive tasks, the user can simply create scripts and issue commands, and PowerShell will complete them automatically. The user can customize hundreds of commands, called cmdlets.

Microsoft PowerShellDownload PowerShell - Latest Stable Release

PowerShell Commands List

Here are 25 basic PowerShell commands:
Command nameAliasDescription
Set-Locationcd, chdir, slSets the current working location to a specified location.
Get-Contentcat, gc, typeGets the content of the item at the specified location.
Add-ContentacAdds content to the specified items, such as adding words to a file.
Set-ContentscWrites or replaces the content in an item with new content.
Copy-Itemcopy, cp, cpiCopies an item from one location to another.
Remove-Itemdel, erase, rd, ri, rm, rmdirDeletes the specified items.
Move-Itemmi, move, mvMoves an item from one location to another.
Set-ItemsiChanges the value of an item to the value specified in the command.
New-ItemniCreates a new item.
Start-JobsajbStarts a Windows PowerShell background job.
Compare-Objectcompare, difCompares two sets of objects.
Group-ObjectgroupGroups objects that contain the same value for specified properties.
Invoke-WebRequestcurl, iwr, wgetGets content from a web page on the Internet.
Measure-ObjectmeasureCalculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files …
Resolve-PathrvpaResolves the wildcard characters in a path, and displays the path contents.
Resume-JobrujbRestarts a suspended job
Set-Variableset, svSets the value of a variable. Creates the variable if one with the requested name does not exist.
Show-CommandshcmCreates Windows PowerShell commands in a graphical command window.
Sort-ObjectsortSorts objects by property values.
Start-ServicesasvStarts one or more stopped services.
Start-Processsaps, startStarts one or more processes on the local computer.
Suspend-JobsujbTemporarily stops workflow jobs.
Wait-JobwjbSuppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are …
Where-Object?, whereSelects objects from a collection based on their property values.
Write-Outputecho, writeSends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline,…

PowerShell cheat sheet (PDF)

Here is our PDF version of the PowerShell Cheat Sheet. Click on the image below to open the PDF in a separate browser tab that you can save and use as a quick reference.

Comparitech-Powershell-cheatsheet

How to Use Windows PowerShell

PowerShell is ideal for corporate administrators who run complex management operations over large corporate networks. Rather than collating information about hundreds of different servers and services manually (which would take a long time), you can simply run a script on PowerShell to automatically feed information back to you.

Generally speaking, PowerShell is most beneficial to users who have prior experience with command lines. To use PowerShell, you can run a variety of cmdlets, scripts, executables, and .NET classes. For the purposes of this article, we’re mainly going to focus on cmdlets and scripts to help you come to grips with the fundamentals.

Udemy has a number of top-rated courses on PowerShell that you might find useful.

PowerShell vs Command Prompt

For many users, PowerShell is a better alternative to Command Prompt. The reason is that it simply has more horsepower. One of the biggest differences is that PowerShell uses cmdlets rather than commands. Cmdlets place registry management and Windows Management Instrumentation within the administrative reach of users. In contrast, Command Prompt is confined to much more simple commands.

There is some crossover in syntax between the two platforms as PowerShell will accept some command prompt commands like . However, these are known as aliases rather than cmdlets. Another key difference is that PowerShell is centered on objects. Every piece of data output from a cmdlet is an object rather than text. This makes it easier for the user to navigate their way around complex data. The inclusion of the .NET framework also enables PowerShell scripts to use .NET interfaces. In short, PowerShell is Command Prompt on steroids.

Loading Up PowerShell

Before we delve into the basics of using PowerShell, you first need to access the main interface. If you are a Windows 10 user then you will already have access to PowerShell 5. Windows users have access to PowerShell 4, but if you’re on Windows 7, you’re going to need to install it within a .NET framework. Across all operating systems, PowerShell offers two distinct interfaces.

The more advanced is the Integrated Scripting Environment, which acts as a comprehensive GUI for experienced users. The basic alternative is the PowerShell console, which provides a command-line for the user to input their commands. Beginners are advised to stick with the latter until they learn the fundamentals of PowerShell.

In order to start PowerShell on Windows 10, you need to be an Administrator. Log in as an administrator, click Start, and scroll through your apps until you locate Windows PowerShell. Right-click and select Run as Administrator. On Windows , simply search for PowerShell in your Systemfolder. Similarly, on Windows 7 the default directory for PowerShell is the Accessories folder after you’ve installed the program.

What are the different ways I can run PowerShell as an Administrator?

  1. Press WIN + R, type in powershell, press Ctrl+Shift+Enter. Click OK to run as Administrator.
  2. Type powershell into the Taskbar search field. Select Run as Administrator from the list of options in the right panel of the results list.
  3. Open the Command Prompt, type powershell, and hit Enter. Type start-process PowerShell -verb runas and press Enter.
  4. Also in the Command Prompt, type runas /netonly /user:RemoteDomain\Administrator powershell (substitute a URL or hostname for RemoteDomain)

A note on option 4 in this list:

The /netonly option of runas applies a user account to remote targets. So, in this case, you want to run PowerShell as Administrator on a computer that is identified by RemoteDomain. The Administrator account is active on that remote device and not on the local machine, so, when prompted, give the password for the Administrator account when prompted, not the password for the Administrator account on the local computer.

How to Run cmdlets

how to run cmdlets powershell

In a nutshell, a cmdlet is a single-function command. You input cmdlets into the command line just as you would with a traditional command or utility. Cmdlets are the main way to interact with the CLI.

In PowerShell, most cmdlets are written in C# and comprised of instructions designed to perform a function that returns a .NET object.

Over cmdlets can be used in PowerShell. Windows PowerShell command prompt isn’t case-sensitive, so these commands can be typed in either upper or lower case. The main cmdlets are listed below:

  • Get-Location &#; Get the current directory
  • Set-Location &#; Get the current directory
  • Move-item &#; Move a file to a new location
  • Copy-item &#; Copy a file to a new location
  • Rename &#; item Rename an existing file
  • New-item &#; Create a new file

For a full list of commands available to you, use the  cmdlet. In the command line you would enter the following:

It is important to note that Microsoft restricts users from using custom PowerShell cmdlets in its default settings. In order to use PowerShell cmdlets, you need to change the ExecutionPolicy from Restricted to RemoteSigned. Remote Signed will allow you to run your own scripts but will stop unsigned scripts from other users.

To change your Execution policy, type in the following PowerShell command:

To change to RemoteSigned, type the following command:

Make sure you’re on an Administrator account so that you have permission to set a new execution policy.

How to Run PowerShell Scripts

how to run scripts powershell

Script-based processes and commands are part of the foundation of PowerShell’s versatility. In PowerShell, a script is essentially a text file with a ps1 extension in its filename. To create a new script you can simply open the Windows notepad, type your commands, and save with ‘.ps1’ at the end of the name.

To run a script, enter its folder and filename into the PowerShell window :

Once you’ve done this, your selected script will run.

Looking to create your own PowerShell scripts? Nearly 5k students have taken this Udemy course on Advanced Scripting with PowerShell.

Overlap with Windows Commands

When you’re new to PowerShell it can feel overwhelming to try and learn a whole new library of commands. However, what most new users don’t realize is that the syntax used on Windows command-line overlaps with PowerShell. This is made easier by the fact that PowerShell isn’t case sensitive.

Much like Command Prompt, on PowerShell the cd command still changes directories, and dir still provides a list of files within the selected folder. As such, it’s important to remember you aren’t necessarily starting from scratch. Taking this on board will help to decrease the learning curve you face when using PowerShell and decrease the number of new commands that you have to learn.

That being said, it is important to note that these aren’t considered complete PowerShell commands so much as they are aliases (Powershell’s name for Windows command prompt commands). So even though you can try some of Command Prompt’s commands in PowerShell, you should learn as much as you can about the new ones. Nonetheless, Command Prompt experience can definitely help new users to come to grips with PowerShell and hit the ground running.

Backing Up an SQL Database with PowerShell

powershell SQL

Many people use PowerShell to back up SQL databases. The command-line interface can conduct full database backups, file backups, and transaction log backups. There are many ways to backup a database in PowerShell, but one of the simplest is to use the command. For example:

This will create a database backup of a database with the name ‘Databasecentral’ (or the name of your chosen database’.

To back up a transaction log, you would input:

This will create a transaction log of the selected database.

The Essential PowerShell Commands

Using aliases will only get you so far on PowerShell, so it’s important to commit to learning everything you can about PowerShell’s native commands. We touched on some of these above, but we’re going to break down the main ones in much more detail below.

Get-Help

This command should be at the very top of any new user’s list when it comes to PowerShell. The Get-Help command can be used to literally get help with any other PowerShell command. For example, if you know the name of a command, but you don’t know what it does or how to use it, the Get-Help command provides the full command syntax.

For example, if you wanted to see how Get-Process works, you would type:

As touched on earlier in this guide, Microsoft has a restricted execution policy that prevents scripting on PowerShell unless you change it. When setting the execution policy, you have four options to choose from:

  • Restricted &#; The default execution policy that stops scripts from running.
  • All Signed &#; Will run scripts if they are signed by a trusted publisher
  • Remote Signed &#; Allows scripts to run which have been created locally
  • Unrestricted &#; A policy with no restrictions on running scripts

If you’re using PowerShell, you may not always work on a server that you’re familiar with. Running the command Get-Execution Policy will allow you to see which policy is active on the server before running a new script. If you then see the server in question operating under a restricted policy, you can then implement the Set-ExecutionPolicy command to change it.

Get-Service

One of the most important commands is , which provides the user with a list of all services installed on the system, both running and stopped. This cmdlet can be directed by using specific service names or objects.

For example, if you were to type , you would be shown a list of all services on your computer, their statuses, and display names.

To use this command to retrieve specific services, type:   to retrieve all services that begin with WMI.

If you wanted to restrict output to active services on your computer, input the following command:

ConvertTo-HTML

When using PowerShell, you might want to generate a report about the information you’ve seen. One of the best ways to do this is by using the ConvertTo-HTML command. This cmdlet allows you to build reports with tables and color, which can help to visualize complex data. Simply choose an object and add it to the command. For example, you could type:

This returns a mass of information, so it’s a good idea to limit it to a file with the Out-File command. A better alternative command is:

This will then generate an HTML file in table form. For example:

powershell html table

You can then add your own colors and borders to refine its presentation.

Export-CSV (and Get-Service)

No less important for increasing visibility is the Export-CSV command. It allows you to export PowerShell data into a CSV file. Essentially, this command creates a CSV file compiling all of the objects you’ve selected in PowerShell. Every object has its own line or row within the CSV file. This command is primarily used to create spreadsheets and share data with external programs.

To use this command, you would type:

It’s important to remember not to format objects before running the Export-CSV command. This is because formatting objects results in only the formatted properties being placed into the CSV file rather than the original objects themselves. In the event that you want to send specific properties of an object to a CSV file, you would use the Select-Object cmdlet.

To use the Select-Objectcmdlet, type:

Get-Process

If you want to view all processes currently running on your system, the Get-Process command is very important. To get a list of all active processes on your computer, type:

Notice that if you don’t specify any parameters, you’ll get a breakdown of every active process on your computer. To pick a specific process, narrow the results down by process name or process ID and combine that with the Format-Listcmdlet, which displays all available properties. For example:

This provides you with comprehensive oversight of all active processes.

Get-EventLog

get eventlog security cmdlet

If you ever want to access your computer’s event logs (or logs on remote computers) while using PowerShell, then you’re going to need the Get-EventLog command. This cmdlet only works on classic event logs, so you’ll need the Get-WinEvent command for logs later than Windows Vista.

To run the event log command, type:

This will show all event logs on your computer.

One of the most common reasons users look at event logs is to see errors. If you want to see error events in your log, simply type:

If you want to get event logs from multiple computers, specify which devices you want to view (listed below as “Server1” and “Server2”). For example:

Parameters you can use to search event logs include:

  • After &#; User specifies a date and time and the cmdlet will locate events that occurred after
  • AsBaseObject &#; Provides a System.Diagnostics.EventLogEntry for each event
  • AsString &#; Returns the output as strings
  • Before &#; User specifies a date and time and the cmdlet will locate events that occurred before
  • ComputerName &#; Used to refer to a remote computer
  • EntryType &#; Specifies the entry type of events (Error, Failure Audit, Success Audit, Information, Warning)
  • Index &#; Specifies index values the cmdlet finds events from
  • List &#; Provides a list of event logs
  • UserName &#; Specifies usernames associated with a given event

 Stop-Process

powershell stop-process

When using PowerShell, it’s not uncommon to experience a process freezing up. Whenever this happens, you can use Get-Process to retrieve the name of the process experiencing difficulties and then stop it with the Stop-Process command. Generally, you terminate a process by its name. For example:

In this example, the user has terminated Notepad by using the command.

PowerShell: A powerful command-line interface

Although making the transition to PowerShell can seem quite complex, it’s command-line interface operates much the same as any other. It may have its own unique cmdlets, but a wealth of online resources can help you with any administrative task you can think of. To get the most out of PowerShell, you simply need to get used to the multitude of commands available to you.

As a new user, it is easy to become daunted by PowerShell’s plus cmdlets. Make sure you start out with the command line interface before graduating to the full-blown GUI. Regardless of whether you’re new to PowerShell or command-line interfaces, more than enough information is available online to help you make the most of this powerful tool.

PowerShell Commands FAQs

How do I navigate in Windows PowerShell?

The most important navigation actions you need to know for PowerShell is how to get into it and how to get out again. The easiest way to access the PowerShell environment is to type PowerShell in the search field of your taskbar. PowerShell runs in its own window, so you can close it down just by clicking on the X in the top right corner of the window’s frame. The proper way to close the window is to type exit and the command prompt. The standard navigation commands of the Command Prompt work in PowerShell so use cd to change directory. Enter a drive letter followed by a colon (eg. D:) to switch to another drive.

Is Windows PowerShell the same as Command Prompt?

PowerShell is an advancement on Command Prompt because its shell scripting capabilities include better programming constructs than those available for batch jobs in Command Prompt. All of the Command Prompt commands are available in PowerShell but then PowerShell has extra commands and utilities, called cmdlets. Think of PowerShell as Command Prompt +.

How do I learn bash scripting?

Bash scripting is a Unix shell script. As Linux is an adaptation of Unix, a shell script written for Linux is often called a Bash script. There are a lot of online tutorials on how to create a Bash script. In order to avoid confusion, try not to refer to a PowerShell script as a Bash script.

How can I make Command Prompt default instead of PowerShell?

When you press WIN + X, you now get a PowerShell window instead of the old Command Prompt. To stick with Command Prompt, go to the Start menu and click on Settings. In the Settings menu, select Personalization. Select Taskbar in the left-hand menu of the Personalization Settings Window. In the main panel of that window, look for Replace Command Prompt with Windows PowerShell in the menu when I right-click the Start button or press Windows key+X. Set that to Off.

What are the different ways I can run PowerShell as an Administrator?

  1. Press WIN + R, type in powershell, press Ctrl+Shift+Enter. Click OK to run as Administrator.
  2. Type powershell into the Taskbar search field. Select Run as Administrator from the list of options in the right panel of the results list.
  3. Open the Command Prompt, type powershell, and hit Enter. Type start-process PowerShell -verb runas and press Enter.

How to run PowerShell commands?

You can run PowerShell commands from a Command Prompt window by using the format: powershell -command " <PowerShellCode> " but put your PowerShell command inside the quotes instead of <PowerShellCode>. If your PowerShell command requires a value in quotes, use single quotes in there instead of double-quotes. The surrounding quotes in the execution example here should remain as double-quotes.

Sours: https://www.comparitech.com/net-admin/powershell-cheat-sheet/


2752 2753 2754 2755 2756