Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

PowerShell 2

More PowerShell

1
What else can we run in PowerShell?
We looked at using cmdlets and aliases in PowerShell, but there are
other types of commands we can run:
• Math

• external commands/programs
• Attrib, ipconfig, ping, netstat, format, shutdown

2
Useful cmdlets for File/Folder Management
Get-Location (Present Working Directory, just like “pwd” in Linux)
(Aliases: gl, pwd)

Get-ChildItem (Gets a directory listing like “ls” from Linux)


(Aliases: gci, ls)

New-Item (Creates a new directory or file)(Aliases: ni, md, mkdir)

Remove-Item (Removes a directory or file)


(Aliases: rm, rd, rmdir, ri, del, erase)

https://docs.microsoft.com/en-us/powershell/scripting/samples/working-with-files-and-
folders?view=powershell-5.1

Examples:
Create a new file (ni):
PS C:\ New-Item -Path . -Name "file1.txt" -ItemType
"file"
PS C:\ New-Item -Path . -Name "file2.txt" -ItemType
"file" -Value "This is a text string."
Create a new directory (md, mkdir, ni):
PS C:\> New-Item -Path "c:\" -Name “newdir" -ItemType
"directory“
PS C:\> New-Item -ItemType "directory" -Path "c:\ps-
test\scripts"
Display file contents (cat, type, gc):
PS C:\> Get-Content file.txt
Delete a file (del, rm, erase, ri):
PS C:\> Remove-Item C:\Test\file.txt
PS C:\> Remove-Item C:\Test\*.*

3
PS C:\> Remove-Item * -Include *.doc -Exclude *1*
Remove a directory (rm, rd, rmdir, ri):
PS C:\> Remove-Item “D:\temp\Test Folder 1”
PS C:\> Remove-Item “D:\temp\Test Folder 1” -Recurse

3
Useful cmdlets for File/Folder Management
Copy-Item (Copy an item to another destination) (Aliases: cp, copy, ci)

Move-Item (Move an item from one place to another) (Aliases: mi,


move, mv)

Get-Content (Displays the contents of a file) (Aliases: cat, gc)

Examples:
Copy a file (cp, copy, cpi):
PS C:\> Copy-Item source.txt dest.txt
Move a file (mv, move, mi):
PS C:\> Move-Item source.txt dest.txt

4
Parameters
Denoted by a dash –

Allows a cmdlet to be modified to be more specific

Most cmdlets have a set of parameters, to find out which parameters


can be used with certain cmdlets, use Google or online PowerShell
help.
There is also context-sensitive help in PowerShell ISE.

5
Example of New-Item with Parameters
Ex 1: Creating a new directory named newdir at a specific location.

New-Item is the cmdlet to create a new directory or file.


-Path is a parameter of New-Item to specify where the file/directory will be created
-Name allows you to specify the name of the new file/directory.
-ItemType specifies whether the new item is a directory or file.

6
Example of Remove-Item with Parameters
Ex 2: Removing the newdir folder that was just created.

Remove-Item removes a file or folder.


-Path allows you to specify the path of the directory or file.

7
Working with Files and Folders
File Management:
Copying a file
PS C:\> Copy-Item source.txt dest.txt

Moving a file
PS C:\> Move-Item source.txt dest.txt

***(very similar to Linux)***

8
Working with Files and Folders continued
File Management:
Display file contents (cat, type, gc):
PS C:\> Get-Content file.txt

9
Syntax
• Computers can only understand user inputs if they are given correctly.
• It is basically the “grammar” and “sentence structure” for computing
languages.
• If a command is typed incorrectly or in the wrong order, the machine
will usually produce error messages.

Example: “You and me go to the store.” (“Grammar”)


Grammatically that is incorrect, however, we as humans understand what the other person
is trying to communicate. But for computers, inputting “You and me” will not be considered
correct because the computer or command interpreter has the limited ability to perform
commands that it knows. It is not intuitive. It does not know what you intend to do, only
what you tell it to do using commands it understands.

10
Syntax Examples in Powershell
Correct Syntax Incorrect Syntax Reason
Get-Command Get-Comand Typo, bad “grammar”
GeT-HeLp Get- Help Extra space between the
#Note: Powershell is not dash and “Help”.
case sensitive

GET-SERVICE Service-get Bad “sentence structure”

11
Using PowerShell to Manage Services on Our
Server
To obtain a list of all services running on your computer:
PS C:\> Get-Service
To get the status of a specific service by name:
PS C:\> Get-Service –Name Spooler
To get a list of services by name, using a wildcard:
PS C:\> Get-Service –Name Sp*

https://docs.microsoft.com/en-us/powershell/scripting/samples/managing-
services?view=powershell-5.1

12
Using PowerShell to Manage Services on Our
Server continued
To stop a running service:
PS C:\> Stop-Service –Name Spooler
To start a stopped service:
PS C:\> Start-Service –Name Spooler
To manage services on a REMOTE computer, use ComputerName
option:
PS C:\> Get-Service –ComputerName Server01

https://docs.microsoft.com/en-us/powershell/scripting/samples/managing-
services?view=powershell-5.1

13
Allows you to test commands
Risk without accidentally causing
damage to your server.
Mitigation
Parameters: What do you think the
-whatif, following command would do
-confirm to your server?
PS C:\ > Get-Service | Stop-Service

Sometimes you need to test a command or function to see if it works, but it could
potentially cause harm to your computer. Risk mitigation parameters, like –whatif and –
confirm can help you test commands without actually running them.

If you run this command in a production environment, it will stop all services on the server,
essentially making it inoperable. The only way to recover from this command would be to
restart your computer.

-whatif and –confirm can be used with commands to see how they run, without actually
running them.

Using a testing environment is the safest way to test commands and scripts.

14
Using -whatif

The WhatIf switch instructs the command to which it is applied to run but only to display
the objects that would be affected by running the command and what changes would be
made to those objects. It does NOT execute the commands.

15
Using -confirm

The Confirm switch instructs the command to which it is applied to stop processing before
any changes are made. The command then prompts you to acknowledge each action
before it continues. When you use the Confirm switch, you can step through changes to
objects to make sure that changes are made only to the specific objects that you want to
change. This functionality is useful when you apply changes to many objects and want
precise control over the operation of the Shell. A confirmation prompt is displayed for each
object before the Shell modifies the object.

16
Shutting Down and Restarting Your Server
To shutdown the computer:
PS C:\> Stop-Computer
To restart the computer:
PS C:\> Restart-Computer
To force an immediate restart of the computer:
PS C:\> Restart-Computer -Force

https://docs.microsoft.com/en-us/powershell/scripting/samples/changing-computer-
state?view=powershell-5.1

17
• A script is a text file that contains a list of commands
to be executed in sequence
• PowerShell scripts have a .PS1 extension

PowerShell • It can be created in any text editor, but PowerShell


ISE has many powerful features
Scripting • Debugging and error checking, and Intellisense
which gives you available options as you type.
Basics • You cannot run a PowerShell script by double-
clicking it
• It must be run with PowerShell
• Execution Policy must be set to allow scripts to
run

The Windows PowerShell ISE


08/13/2018
2 minutes to read
Contributors
https://docs.microsoft.com/en-us/powershell/scripting/components/ise/introducing-the-
windows-powershell-ise?view=powershell-6
The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for
Windows PowerShell. In the ISE, you can run commands and write, test, and debug scripts
in a single Windows-based graphic user interface. The ISE provides multiline editing, tab
completion, syntax coloring, selective execution, context-sensitive help, and support for
right-to-left languages. Menu items and keyboard shortcuts are mapped to many of the
same tasks that you would do in the Windows PowerShell console. For example, when you
debug a script in the ISE, you can right-click on a line of code in the edit pane to set a
breakpoint.

18
Using PowerShell ISE

https://docs.microsoft.com/en-us/powershell/scripting/components/ise/exploring-the-
windows-powershell-ise?view=powershell-6

19
How to run PowerShell Scripts

Run Scripts from the File Explorer by right-clicking the file and selecting Run with
PowerShell from the menu.
Run Scripts from the PowerShell command window by typing the script name. When you
run a PowerShell script, you always must include the path.
Run Scripts from PowerShell ISE by clicking the green arrow.

20
You may need to edit the Execution Policy if you
get Security Warnings when running scripts

PowerShell does not trust scripts from remote


locations by default
Execution
Policy PowerShell only trusts scripts created on the
local machine by default

The Execution Policy determines which scripts


must be digitally signed before they are allowed
to run

https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=
powershell-6

21
• Unrestricted – Allow all scripts
• RemoteSigned – Allow local scripts and remote signed
Execution Policy scripts.
Options • AllSigned – Allow only signed scripts (local or remote).
• Restricted – No scripts will run.

You should never use Unrestricted in a production environment, however it is very useful
for testing.

22
Using Variables to Store Objects
• PowerShell allows you create named objects known as variables
• You can store all types of values in PowerShell variables
• Typically used to store the results of commands and to store elements
that are used in commands and expressions, such as names, paths,
settings, and values.
• Variables are represented by text strings that begin with a dollar sign
($), such as $a, $process, or $my_var
• To use a variable in a command or expression, type the variable
name, preceded by the dollar sign ($)

https://docs.microsoft.com/en-us/powershell/scripting/learn/using-variables-to-store-
objects?view=powershell-6

https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_variables?view=powershel
l-6

23
Using Variables to Store Objects
To determine the value of an existing variable, type the variable name:
PS C:\> $Profile
*We used the $Profile variable in the last lesson.

https://docs.microsoft.com/en-us/powershell/scripting/learn/using-variables-to-store-
objects?view=powershell-6

24
My First Script

# - indicates a comment
It is good practice to put information about the script at the beginning of the file.
Providing comments to explain what is happening in the script or to label sections of the
script is common practice.
In this script there are a couple of commands we have not seen yet:
Read-Host writes text to the screen to prompt the user for input.
Write-Host writes text to the screen. In our example we are using our user-defined
variables $date and $myname along with the environment variable $env.COMPUTERNAME
to display customized text to the screen.

25
Working with Output: The Pipeline
• In PowerShell, the vertical bar ( | ) is the pipe symbol. This tells
PowerShell that you want to take the output of one command and
pass it as the input (or pipe it) to the next command; similar to the
pipe in cmd.exe and Linux, but a major difference is that instead
passing text between commands, you are passing complete objects.

https://docs.microsoft.com/en-us/powershell/scripting/learn/understanding-the-
powershell-pipeline?view=powershell-5.1

Understanding pipelines
08/22/2018
3 minutes to read
Contributors
Pipelines act like a series of connected segments of pipe. Items moving along the pipeline
pass through each segment. To create a pipeline in PowerShell, you connect commands
together with the pipe operator "|". The output of each command is used as input to the
next command.
The notation used for pipelines is similar to the notation used in other shells. At first
glance, it may not be apparent how pipelines are different in PowerShell. Although you see
text on the screen, PowerShell pipes objects, not text, between commands.
The PowerShell pipeline
Pipelines are arguably the most valuable concept used in command-line interfaces. When
used properly, pipelines reduce the effort of using complex commands and make it easier
to see the flow of work for the commands. Each command in a pipeline (called a pipeline
element) passes its output to the next command in the pipeline, item-by-item. Commands
don't have to handle more than one item at a time. The result is reduced resource

26
consumption and the ability to begin getting the output immediately.
For example, if you use the Out-Host cmdlet to force a page-by-page display of output from
another command, the output looks just like the normal text displayed on the screen, broken
up into pages.

26
Functions

• Look like a cmdlet and are run the same way from the prompt
• Typically contains complex sets of cmdlets and options that perform
multiple tasks (mini-script)
• There are built-in functions, and we can create our own

27
Create your own function:

28
A collection of cmdlets for a particular
function or application

Some are pre-loaded and some need to


be “imported”

Modules Cmdlets within a module are available


to use once they have been imported

Modules are available for applications


and Windows Roles and Features
• VMWare, Azure, Office365, Hyper-V, Windows
Update, Active Directory

https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_modules?view=powershell
-6

29
To see all available modules on the system:

30
Import a module and list commands:

Once the module has been imported into your PowerShell session, all of the cmdlets in that
module are available to you.

31
Creating a Persistent PowerShell Environment
• You can use the profile as a logon script to customize the
environment. You can add commands, aliases, functions, variables,
snap-ins, modules, and Windows PowerShell drives. You can also add
other session-specific elements to your profile so they are available in
every session without having to import or re-create them.
• In the previous lesson, $Profile was used to set aliases for every
PowerShell session
• Edit $Profile to include functions and imported modules

https://docs.microsoft.com/en-
us/powershell/module/microsoft.powershell.core/about/about_profiles?view=powershell-
5.1

32
Editing $PROFILE
to Include
Functions and
Modules

33
The PowerShell Community
• There is a huge PowerShell community that shares scripts
• You likely never have to write a script from scratch because someone
has already written the script you need, or something you can modify

https://devblogs.microsoft.com/scripting/

TechNet – Script Resources for IT Professionals


• Has over 6000 PowerShell scripts
• https://gallery.technet.microsoft.com/scriptcenter

34
What have we learned?
• The PowerShell pipeline allows you to take the output of one cmdlet
and feed (pipe) it into another.
• Functions contain complex sets of cmdlets and options that perform
multiple tasks (mini-script)
• A module is a package that contains PowerShell commands related to
a particular function or application.
• You can customize your PowerShell environment with a profile.
• Use PowerShell ISE to write, debug and run scripts.

35
Works Cited:
• https://en.wikipedia.org/wiki/PowerShell
• https://docs.microsoft.com/en-
us/powershell/scripting/overview?view=powershell-6

36

You might also like