You are on page 1of 53

PowerShell:

Simple and Effective Strategies to Execute


PowerShell Programming
Table of Contents
Introduction
Chapter One: Using Your Script Desired State Configuration Resource
Chapter Two: Managing Your Windows Firewall Through PowerShell
Chapter Three: Working with WMI in PowerShell
Chapter Four: Using the PS ScriptAnalyzer to Analyze PowerShell Scripts
Chapter Five: Working with Regular Expressions in PowerShell
Chapter Six: Understanding the Functions Used in PowerShell
Chapter Seven: Building a Better PowerShell Parameter Validation
Chapter Eight: Using Trello and PowerShell
Chapter Nine: Transferring Files with Shared Permissions
Chapter Ten: Creating Your First Chocolatey NuGet Package
Chapter Eleven: Integrating Ansible and DSC to PowerShell
Chapter Twelve: Exploring the Abstract Syntax Tree that Works with
PowerShell
Chapter Thirteen: Working with JSON Data in PowerShell
Chapter Fourteen: Automating SQL Server Deployments with DSC
Chapter Fifteen: PowerShell Cmdlets that are Essential for Managing the
Active Directory
Conclusion
Copyright 2017 by ____DANIEL JONES__________________ - All rights reserved.

The following eBook below is reproduced with the goal of providing


information that is as accurate and reliable as possible. Regardless, purchasing
this eBook can be seen as consent to the fact that both the publisher and the
author of this book are in no way experts on the topics discussed within and
that any recommendations or suggestions that are made herein are for
entertainment purposes only. Professionals should be consulted as needed
prior to undertaking any of the action endorsed herein.

This declaration is deemed fair and valid by both the American Bar
Association and the Committee of Publishers Association and is legally
binding throughout the United States.

Furthermore, the transmission, duplication or reproduction of any of the


following work including specific information will be considered an illegal
act irrespective of if it is done electronically or in print. This extends to
creating a secondary or tertiary copy of the work or a recorded copy and is
only allowed with express written consent from the Publisher. All additional
rights reserved.

The information in the following pages are broadly considered to be truthful


and accurate accounts of facts and as such, any inattention, use or misuse of the
information in question by the reader will render any resulting actions solely
under their purview. There are no scenarios in which the publisher or the
original author of this work can be in any fashion deemed liable for any
hardship or damages that may befall them after undertaking information
described herein.

Additionally, the information in the following pages are intended only for
informational purposes and should thus be thought of as universal. As befitting
its nature, it is presented without assurance regarding its prolonged validity or
interim quality. Trademarks that are mentioned are done without written
consent and can in no way be considered an endorsement from the trademark
holder.
Introduction
Congratulations on downloading PowerShell and thank you for doing so.

The following chapters will discuss strategies that you are going to be able to
use in order to execute your PowerShell programming. PowerShell is a
program that is going to assist you. Implementing this is going to be especially
useful if you are working in IT or administration, therefore, it is vital that you
know just what to do in order to make the program work for you.

There are plenty of books on this subject on the market, thanks again for
choosing this one! Every effort was made to ensure it is full of as much useful
information as possible. Please enjoy!
Chapter One: Using Your Script Desired State
Configuration Resource
The community of Microsoft has done a good job of making sure that the
resources for DSC are provided for those who use the program. There are at
least a dozen different resources that you are going to have access to by going
to the GitHub page that is provided by Microsoft. With all of these resources,
it is difficult to imagine why you might want to make your own resource for the
DSC.

In reality, despite the fact that Microsoft provides these resources through the
PowerShell gallery, there are going to be a few times when you will find that
the packed DSC does not exist for what you want to do. Being that there is no
resource available, you are going to have two options; you can create your
own, or you can make the script resource.

In the event that your resource has to be planned to be part of the script that is
being executed around it, then you are going to be better off creating your own
resource. When you create your own resource, you will have the advantage of
learning what the resource does due to the fact that you have created it. You
will also need to run your code as part of the configuration that is being used
for DSC which means you will not need to spend time creating the entire
resource.

The script resource for DSC is going to be considered a general resource that
you can use. The script source is nothing more than your way to insert code
into the resource without having to create a real resource. Your script is going
to come from being installed by default by PowerShell wherein there will be
three properties that you can use. Those properties are: GetScript, SetScript,
and TestScript. You will most likely see that these codes are going to coincide
with your usual properties for get, test, and script due to the fact that they have
to be defined whenever you are creating a resource from scratch.
Syntax

PS> Get- DscResource name script

Example:

Code [string] #the name of your resource

GetScript = [string]

SetScript = [string]

TestScript = [string]
[Validation = [PS Credentials]]

[Depends on = [string [ ]]]

[PSDsc run as validation = [PS credential]]

In order to use the scripts resource, you are going to be required to create a bit
of PowerShell code that is going to be used with each of your properties. In
reality, it does not matter what kind of code is being used. However, every
properties code is going to be returned to its specific type. To show you how
this works, you will look at the script resource that is going to be allowed by
the firewall on Windows.

PowerShell configuration allow Windows firewall {bring in dscresource


name of the module PSdesiredstateconfiguration node local host {script to
allow firewall {# a hash table will be returned with at least one key number
that is named result because of the GetScript type. = {outcome @ {outcome =
[string] $ (netsh, advanced firewall, show every profile)}}
# Need a Boolean returned $correct or $incorrect

Testscript = {

If ((netsh advanced firewall show every profile) like state * off) {

Write out the firewall is off for more than one profile.

Return $incorrect

} else {

Write out "every firewall is on."

Return $correct

# the return will be nothing

Setscript = {

Write out "the settings for the firewall profiles is on."

Netsh advanced firewall settings every profile states on


}

You should see that the property for the getscript command is going to hold any
code that it needs to so that it can locate the current state of what it is that you
are attempting to do. These properties are going to be in a script block and
have to return a hash table that contains at least one key that is labeled result.
However, you are not going to use it when you go to invoke the DSC
configuration.

The test property is going to do the same thing except for the code that is in it
will test the state to check and see if it is in compliance. The code needs to
return a true or false answer.

Lastly is the setscript which is where the real changes are going to be made.
Your setscript property will return nothing and is going to hold the block of
code to force the testscript to return a true value.

The whole reason behind your script resource is so that you have a script that
is going to be similar to a real DSC resource. The biggest difference is going
to be that you can define the arbitrary code to a particular property where it
may not be tied to previously. However, while you continue to create extra
script resources, you are going to notice that you are going to rely on the code
resources when it comes to working with more advanced scenarios. How
complex the code is will be a part of what is needed for keeping your tools and
the various resources that you are going to create.
Chapter Two: Managing Your Windows Firewall
Through PowerShell
If you click around on the GUI for Windows in an effort to change, add, or
remove the rules of a firewall does not sound like how you would want to
spend your time. So, if you are configuring a single computer, it is not going to
be that bad. Some people have several machines that they use that are going to
mean that you are going to have to practice the standard configuration settings.
You need to have one way to apply the proper settings to several different
computers at once. In order to do this, you will use PowerShell script that you
write in order to deploy the script to multiple machines in one fell swoop.

The server 2012R2 and Windows 8.1 introduced the cmdlets that were going
to control the firewall on Windows as part of the netsecurity module in
PowerShell. This module is going to hold at least a dozen different cmdlets
that are going to be able to modify the firewall. Keep in mind that the cmdlets
are not going to know whenever ports are opened or closed; however, they are
going to be aware of the three different profiles that are on Windows. Private,
Public, Domain. It is these cmdlets that are going to enable you to manage any
part of the firewall that is on the GUI.

You can locate the cmdlets for the firewall by using the get command noun
"netfirewall". If you use any get cmdlet, you are going to put the state of your
firewall together instantly and what it looks like. It is known that the firewall is
not going to come with the proper configuration that is going to do what you
need it to do. Therefore you are going to have to use various cmdlets to
configure it the way that you need it configured.

For example, if you are going to open up the requirements for RDP to anyone
that is on your private network, you are going to be using the get netfirewall
rule to get the information that you need to see all the properties of the
firewall.

At the point in time that the firewall has been located, you are going to be able
to see that the firewall is enabled. The direction of the firewall is going to be
inbound, and the action will be blocked due to the fact it cannot locate the
proper port. In an effort to look deeper you can use the get
newfirewallportfilter command which is going to show you the TCP and UDP
ports as well as its source and where it is going to be sent.

After you have discovered that you have the right rule, you have to open it up.
In order to change the rules that currently exist you will use the command set
netfirewallrule. As you use the pipeline in PowerShell you can pipe your result
to the set netfirewallrule in an effort to change your action from blocked to
allow.

Syntax
Get netfirewallrule displayname remote desktop | set netfirewallrule
actionblock.

Yet another cmdlet you can use us the show netfirewallrule. With this
command, you are going to instantly be able to see everything that has to do
with your firewall rules.

When you use the above-mentioned cmdlets, you are going to be enabled to
build a configuration that is standard and has the ability to be used on multiple
systems. This means you are no longer going to need to randomly click through
the GUI to find the setting you want.
Chapter Three: Working with WMI in PowerShell
WMI stands for Windows Management Instrumentation. This module has been
around for a long time, and many IT professionals will either be using it
directly, or they will be working with tools that are going to read the
information used with WMI. WMI is a de facto place where you are going to
be able to obtain information about the machine in order to manipulate the
services made available by Windows. Since WMI offers so much information,
it is one of the best places to execute your script, so tasks are automated.

Thankfully, as one of the first systems that is put on Windows, PowerShell is


going to take commands for the WMI. Due to the fact that PowerShell is going
to be the native support that you will need for WMI, you will be able to write
out commands that are easy to understand which are ultimately going to interact
with the WMI. A power user is going to be able to invoke the events for WMI
as well as the classes that are in it just by using a standard PowerShell
command.

PowerShell has two different command sets that are going to interact with
WMI. Many PowerShell users are going to refer to these sets as the old way to
interact with the CIM cmdlets and WMI. Whenever you are searching for
information that is located on WMI, you are going to get the same information
returned, however, you are going to be approaching how to obtain that
information differently. You can use the get wmiobject command in order to
read information that is pulled from WMI. The other cmdlet that you can use
would be invoked wmimethod, register wmievent and others that are going
to pull information from WMI.

In using the get wmiobject is going to have its own setbacks. Whenever you
search for a remote computer, it is going to rely on DCOM, and there are
reports of attacks coming into this vector for the bad guys. DCOM is going to
be blocked by several firewalls because of this security risk. This is also
another reason that you are going to want to try and avoid using this method. It
is going to be easier for you to use the CIM cmdlet get CIM instance. The
biggest difference is going to be that you are not going to be using DCOM to
get access to a remote computer. Get CIM instance is going to use WSMAN
to transport the PowerShell code to a remote feature.

For example, if you are wanting to get information returned to you so that you
can figure out which version of Windows is being used on a computer, you are
going to want to see information that is called DC. This is going to be done by
specifying the WMI class where this information is contained and the name of
the computer that you want to search. As you will see in the syntax below, the
get CIM instance is not going to display every attribute in that class. Instead,
you are going to have to pipe out the results to the select object command, so
all the properties are returned to you.
Syntax

PowerShell PS > get ciminstance -classname

Win32_ operating system computername DC | Select *

You are going to be gathering information from the properties as well as the
classes as well because you are invoking the CIM and WMI methods. You are
going to have the ability to stop processes that are operating on the other
computer. Keep in mind though that you are not going to be using the stop
process command in PowerShell because it is not going to work with WMI. If
you want to kill a process on the remote computer, you are going to need to
locate the process that you want to be terminated. From there you can
enumerate the processes that are running by looking at the process class.

Syntax

PS C: Windowssystem32 > Get CimInstance ClassName CIM_Process


ComputerName DC

Once you have determined which process you want to terminate, then you will
pass the terminate () method to your process class. In order to do this, you have
to capture the instance of your process that you are wanting to be killed. You
will notice that you are going to use the filter parameters in an effort to ensure
that you are only getting the processes that you want. This is of vital
importance to remember!
Now that you have captured your instance, you will invoke your terminate ()
method to get rid of that process through the use of invoking CIM method.

Example:

PS C: Windows system 32> $instance = get ciminstance name of class

CIM_process name of computer DC sort name = process name

PS C: Windows system 32 > $instance

Syntax for terminating the process:

PS C: Windowssystem32> invoke cimMethod -inputobject $instance -


method name terminate

The value returned: name of the computer using PowerShell.


Chapter Four: Using the PS ScriptAnalyzer to Analyze
PowerShell Scripts
You have to be creative when it comes to writing code. Writing code is kind of
like an art form, just because you possess the creativity that you need does not
mean that the code is necessarily going to be good. There are possibilities that
you are going to spend several days working on one of your PowerShell
projects just to see if it can solve an issue that you are having, only to see that
it is not going to because of a single line being changed. Keep in mind that just
because you can write the code a specific way, does not mean it should be
written that way.

However, when working with PowerShell, you are going to have a tool that is
going to allow you to run your scripts to make sure that your creativity is going
to be up to par with the coding practices that you should work with. Your tool
is going to be the PSSCriptAnalyzer, and you need to be familiar with how this
tool works, especially when it comes to sharing your code with others. You do
not want others to have access to code that is not going to work properly in
PowerShell.

The script analyzer tool is a module that Microsoft created in order to test the
PowerShell code written by its users to ensure that the code is meeting the best
practices. There are rules that are inside of the module that were placed there
by Microsoft and the community in their effort to make sure that all the code
that is put into PowerShell is going to work as it is supposed to and is not just
random lines of code that someone placed together in an effort to create code.

You can download this module from the PowerShell gallery with the use of the
install command.

Syntax

Install module name PSScriptAnalyzer

You are going to want to check and make sure that you have the most up to date
version of the script analyzer so that you are keeping up with the best coding
practices and so that your code is being checked against these practices.

The script analyzer module has two commands that it is going to work with.
Get scriptanalyzerrule and invoke scriptanalyzer. If you run the get
scriptanalyzerrule then you are going to be getting a list of every rule that is
installed on the script analyzer. It is from here that you are going to be able to
start to understand the checks that your code is going to go through. When you
use this command, it is only going to give you the default rules; you do have the
option of creating your own rules to place in the analyzer as well.

When it comes to actually using the script analyzer, it is quite simple; you will
place the invoke command in your script and just wait for the results.

Example:

Function join PC {

Arg (

$ name of computer

$password

Try {

} catch {

Your result is going to be the name of the computer and the password that goes
with that computer.
The output that comes from the invoke method is going to be easy to understand
and tell you exactly which rule was broken and what line the error is on. You
will then be able to go back to your script and change it based on this
information. Invoking the script analyzer is also going to be pointed at an entire
folder to be checked if there is script inside to ensure your script is perfect.
Chapter Five: Working with Regular Expressions in
PowerShell
When working with PowerShell and writing script, it is common to have to
match strings. It does not matter how many objects are in PowerShell that
contain useful properties; there will always be a time when you have a string
that was not written just right. You will then need to check it and see if the
string contains a specific set of characters or if there is a need for information
to be removed from the regular expression.

Using regex is going to take a little bit of time to get used to, but you are going
to learn how to integrate regex into your PowerShell language so that it
becomes easier to use and you can use it on a more regular basis.

Whenever you are working with regex, you are going to be working with a
method that matches strings within other strings. PowerShell is going to allow
you to put anything you want here, as long as it contains the full power of your
.net framework. In this chapter, we are going to discuss some ways you can
match and parse strings by using regex.

The Match Operator

There are some methods that you are going to use in PowerShell that are going
to make it to where you get a false condition should the string contain another
string that uses regex. One of the easiest methods to use is to match the strings
through the match operator. This method is going to allow you to specify your
string search and the matched string all in one line.

Example:

PS> Where are you? match You? $correct

This is going to give you a true or false output depending on your match to find
the string that is nested inside of another string. You will see that the match is
going to allow the regex command to be used due to the fact that you are
defining the character in an effort to make sure that the word you is at the end
of the string. You will also use the question mark as an escaped character so
that a literal match is found.

Matching also gives you the added benefit of populating your PowerShells
automatic variable known as $matches each time that a match is found. This
will be an array that is going to give you all of the matches that have been
executed before.

The value that you find in $matches is going to tell you that the string has been
matched. This is going to be one method that you can parse a string from
another string. You will also have a few variations for the match operator in
which PowerShell is going to give you a case sensitive matching.

Select String

Another regex matching tool you will use in PowerShell is the select string
command. You will use this command when you want to pipe a string to it
directly and then choose a pattern that will be the parameter in which your
return is going to match the objects. The Select string is going to be similar to
the match operator, but it is going to be able to do so much more. This method
is also similar to the grep command that is going to accept the strings that are
piped and then perform the matching.

Example:

PS > Where are you? | select string -pattern you?$

Where are you?

Take notice that you are not getting a true or false output for your expression;
instead, you are getting everything that you inputted into the string. But, this is
not completely true due to the fact that the PowerShell commands are rich with
objects and other properties that are useful.

Example:
PS C :> "Where are you?" | select string pattern "you?" $ | get member

Syntax

Typename: Microsoft. PowerShell. Commands. Matchinfo

You will be able to see that you can locate the line number that is going to be
where the match is performed, the context of your match, and the string that
supports the match. You may even get the matching property which is going to
include the original string, the regex groups used, and the match string. It is
recommended that you look at the help for the select string in order to get a
sense of what is going on.

If you do not get a match or a select string, you are going to be able to move
down to the .net and use a regex class. It does not matter what situation your
code is in; you are always going to be able to find a way to solve any problem
that you have with it by using PowerShell.
Chapter Six: Understanding the Functions Used in
PowerShell
Whenever you write out a script in PowerShell, you are not going to
necessarily be concerned about things such as modularity, best practices, or
even if you are going to be able to reuse the code. However, there is a chance
that as you write your code, you are going to come to realize that you are just
repeating yourself in your code.

When you keep doing the same thing over and over, your codes are going to be
nothing more than copy and paste of the same code. However, this is not
practical. Rather, you should build a building block in your code to ensure that
it can be reused. This is when you are going to start creating functions that can
be used in PowerShell.

Functions are going to be a grouping of code that is going to have input and
output that is completely optional. This way you can collect a lot of code to
perform an action multiple ways with one piece of code rather than to
duplicate the code every time that you need to repeat it.

The two functions that you will use in PowerShell are the basic function and
the advanced function. Your basic function is going to be the simplest function
that you can create. They are not going to have any built-in capabilities that the
advanced function is going to have. It is simply going to be created or declared
through a function statement that is followed by curly braces.

Syntax:

Function do something { }

The code that you see above is a function that will be invoked when you enter
the do something command, but it is not going to do much. This is due to the
fact that you have not put any code into the function that needs to be run.
Example:

Function do something {

Write host I am a mommy!

PS > do something

I am a mommy!
When there is code in the function that needs to be invoked, you are going to
see the code be run as it is supposed to be. What would happen if we passed
something into your code in that function while it is running?

Example:

Function do something {

Param ( $string)

Write host I am a mommy - - $ string! }

PS > do something string mommy.'

I am a mommy - - mommy!

Whenever the string parameters have been specified, you are going to be
including dashes that will be followed by the name of your parameter which
will then have the version behind that which is the do something command.
This is one of the basics of getting a parameter to pass to your function.

A basic function will work, however a lot of the time you are going to see that
you are doing nothing more than creating an advanced function. An advanced
function is going to have all of the functionality that a basic function is going to
have, but it is also going to include the built-in features that the basic functions
cannot hold. For example, there is a concept in PowerShell known as error,
verbose, warning, and much more. It is these streams that are going to be
crucial in displaying the correct output to the user. A basic function is not going
to understand these streams.

If you get an error being displayed due to something that occurred in the
function, you are going to want to hide the error so that you can go back and fix
it at a later date. But, when you are working with an advanced function, the
functionality is already provided, so by default, any parameters that are set up
are not going to have to be included and they are just going to be leveraged in a
different way.

Example:

Function do something {

[cmdletbidning() ]

Param ($string)

Write error message Hold on, wait a minute!

Whenever this code is going to be run, you are going to see text that is red
instead of white, and that is going to tell you where the error stream begins. In
order to silence this error, you are going to use this code.

Syntax

Do something error action silently continue

The parameter for the error action is only one of the parameters that is built
into an advanced function. There are other function actions that you are going
to be able to do, and you are even going to be able to write your own functions.
Chapter Seven: Building A Better PowerShell
Parameter Validation

One of the aspects of having code that is written properly is going to be used in
making sure that the input your code gets is what you are wanting it to be. It is
best to try and keep the scope of your input low. This means that there are
going to be limits on the possibilities that you will need to deal with when it
comes around later. When writing a routine for validating your code, you need
to learn what is going to be accepted and what is not going to be accepted by
PowerShell. You will also want to make sure that it has the chance to go
through parameter validation attributes.

As you go about writing PowerShell functions and scripts, you are going to
need to create the parameters that go with it. A parameter broken down to the
most basic sense of the expression is going to look something like this.

Syntax

Param (

[string] $filepath

While the code is going to be alright to place in your PowerShell, when it


comes to defining the parameters, the value of file path is going to be left open
in order for the user to insert what they want to be inserted there.

What happens if part of your function reads the file and then takes the value for
the file path so that it can figure out where the file is located. Due to the fact
that you know the file does exist, you need to use one of your validation
techniques to validate your values in your parameter by using validescript
commands.

When you use the file path parameter, you are going to be creating a parameter
that is going to have a more extensible manner than if you were just to use the
keyword parameter.

Syntax

Function set file {

Param (

[ parameter () ]

[string] $filepath
)

By adding in the [parameter()] function, you have successfully made your


function an advanced function. After you have put it into place, you will then
need to add the parameter validation code. For what we are doing, you are
going to want to make sure that the file that was put into the file path exists on
the computer that you are working on before you proceed with your code. In
order to do this, you are going to use the validate script attribute which is then
going to enable you to run any code that you are wanting to run. Just make sure
that it is going to be returned as true so that the function is executed by
PowerShell.

Example:

Function set file {

Param (

[Parameter ()]

[Validate your script ({test the path path $ _ _ - type of path leaf})]

[String] $filepath
)

Whenever you use the pipeline for the variable $ _ _ you are going to be
inserting the value for the parameter. In the event that the file path does not
exist, the user is going to be notified.

If you add in another parameter validation attribute for the validate pattern, you
will be limiting the file path so that it is not just available, but it is also a text
file. By doing this, you can use the pattern parameter attribute and provide a
regular expression by using the .txt extension.

Syntax

Function set file {

Param (

[Parameter ()]

[Validatescript ({test path path $ _ _ -path type leaf})]


[Validate pattern (.txt$)]

[String] $file path

The validate script and validate pattern commands are just two ways that you
are going to be telling PowerShell to enforce the limits of your parameter so
that your code gives you the output that you are wanting it to give you.
Chapter Eight: Using Trello and PowerShell

Trello is one of the more popular web services that you are going to be able to
use. Trello gives you a Kanban style layout of cards. In using this method, you
are going to be creating these cards on a variety of boards in order to track
your activities and tasks. This website is going to be appealing visually, and it
is easy for you to be able to work with. However, it is not going to work well
when it comes to bulk management of the objects that you are going to put into
it. However, Trello is going to make it to where there is an API that will allow
the user to make a variety of applications to communicate with the web service
so that it can be set up in any fashion that you so choose.

So that you do not have to learn the API for Trello as well as figure out what
the rest method is, we are going to explore a shortcut that is going to put to us a
module that is already built into the program by the community so that you are
able to get your project running quicker. This module can be downloaded from
the PowerShell gallery.

Syntax

Install module name power Trello

There is some set up that you are going to have to do in order to make sure that
your PowerShell is communicating with Trello. The first thing that you are
going to do is get the API key. You will need to go over to the developer portal
and log in to set your account up. Whenever you are ready for your API key,
save it to make sure that Trello can use this. In order to do this, you are going
to be requesting a Trello token that is going to be used through the command of
request trello token.

Syntax

$token = request Trello Access Token ApiKey <place your API key here>

It is this prompt that you are going to notice that you will authenticate the
power Trello application. After you have completed this step, you are going to
take this token and use it to communicate with Trello. Make sure you are
saving you API key as well as the token to your systemso that you do not have
to get one from the server constantly.

Syntax

Set Trello configuration API key myapikey access token $token

You have now made it to where you have the ability to configure your session
by running the get Trello Configuration command. Here you are going to be
free to execute any command that is in the module, and that is going to get you
the results that you desire. In order to get a complete list of everything that you
are able to do in the Trello module, you will execute this command: get
command module power Trello.

There are a lot of commands that you are going to have open to you when you
are working with the objects that are in Trello. The pipeline for the module is
going to support a broad range of commands as well. Therefore, you are going
to be able to manipulate PowerShell to do exactly what it is that you want to
happen with the commands that are available with Trello.
Chapter Nine: Transfering Files with Shared
Permissions

Whenever you are migrating files, you need to think of the files and the folder
that those files are in. Not only that, but you need to think of the permissions
that these objects are going to have. For every folder or file that you want to
migrate, you might run into the possibility of them having different Access
Control Entries (ACEs) which are going to make up your Access Control List
(ACL). Depending on a number of files that you are migrating, this can be a lot!

As you are moving the files to their new locations, there are going to be some
files where the permissions do not move along with it. If you are doing a large
migration where there are intricate permissions put into place, you need to
keep those permissions with the objects as they move to their new destination.
Here is how you are going to do it.

One tool that you can use is the robocopy. With this tool, there are a lot of
extras that you are not going to need necessarily, but it is going to make it
different from the other tools you can use. While robocopy is complicated, it is
important to remember that it is not going to work with every situation.
Whenever robocopy does not work, you can move to icals which is a lot like
robocopy. However, it is going to have switches that are going to make it
simpler to use with some of your PowerShell code.

Using PowerShell

PowerShell is going to be used as a wrapper when you are using the icacls
tool in order to simplify the process. The first thing that you are going to have
to do is download the tool that PowerShell created. That is one of the greatest
things about PowerShell, almost any tool that you need is going to be there
because someone in the PowerShell community has already created it.

For this, we are going to using the PowerShell module. To download this
module, you are going to go to the PowerShell gallery. In the event that you are
working off of version 4 or more recent, you are going to have some commands
that are going to be easier for this version to use than others.

Syntax

Find module name NTFS permission migration | install module

After the code that you put in above has been executed, you are going to need
to obtain a new module that is going to be installed on your computer. After
this has been done, you are going to run a command inside of this module that
is going to go against the folders that are holding all the other files that you are
wanting to transfer with the permissions attached.
Syntax

Save acl folder path \ older server file share save file path C: file
permissions. Txt

After this, you should see an output that is going to show you where your saved
file is growing. When this step is complete, you are going to have all of the
permissions that you need for those files or folders saved inside of a file. At
this point in time, we are going to restore the file. However, before you can do
this, you need to ensure that you have an exact copy of everything that is in your
old folder or your code is not going to work properly.

In order to restore the permissions to your new folder, you will have to use the
restore acl command

Syntax

Restore acl restore to folder path \ new file server file share permission
file path C: file permissions.txt successfully processed XXX files ; failed 0
files

Now that you have completed this step, your permissions should have been
moved over from your source folder and be mirrored in your new folder.
Chapter Ten: Creating Your First Chocolatey NuGet
Package

Automation with PowerShell is becoming more and more of a necessity for


you to know how to use it. If you work in IT, then you are going to want to
know how to use automation so that you know how to perform menial tasks,
and one of those tasks is going to be to install software from PowerShell.
Instead of going through and downloading an MSI that you will have to double
click on and go through the setup wizard, it is in your best interest to look for
an easier way. Almost all of the software in PowerShell is going to have
command line switches that install even without you knowing, and if you look
through everything that you get when the software is installed, you may be able
to find the proper switches. Whatever you install may end up appearing like
this.

Syntax

Install. Exe / q /n /e/ noreboot

How are you going to remember all of the switches? You could take these
switches and place them into a batch file, but you may end up finding that you
forget where you place this file. Another option is to install a package.

Syntax

Install package name acme software

That is thankfully something that you are going to be able to remember.


However, how are you going to get to this point? This is going to happen
because of the NuGet repository and the NuGet package. This is a traditional
software package that you are going to be able to use to wrap around a piece of
software that is going to be placed in the repository, installed, and downloaded
whenever it chooses to. There is an open source tool named Chocolatey that
you can use with NuGet so that you can download and install software silently.
For the purposes of this section, it is going to be assumed that you have NuGet
already and you know the location in which your package is going to be sent.

Installing Chocolatey

Being that Chocolatey is not going to install by default, you have to download
it and install it yourself. You can download it with this code.

Syntax

Iex (( new object

System. Net. Web client) download strings (https://chcolatey.org/install.ps


))

Creating NUSPEC files

Each Chocolatey package is going to have an NUSPEC file that is going to


come with an XML package manifest that is going to give you a summary for
the package and its contents. This file is going to be formatted in a particular
way. In the example below, you are going to see how the file is formatted and
what elements it is going to need to have to run properly.

Example:

<? Xml version = 3.2 encoding = fut -3 ?>

<package

Xmins = http:// schemas.Microsoft.com/packaging/2010/07/nuspec.xsd>

<meta data>

<this is my software>

<version> 4.3 </version>


<summery> a package that I created </summery>

<writer> Samuel Austen </authors>

</ meta data>

</ package>

Creating the Chocolatey Package

Here is where you are going to create your package. In order to do this, you
have to install the chocolatey install package command. For the purpose of this
chapter, we are going to assume that the package is exe and that the switches
have all been installed in the background. You are going to need to send the file
location and the silent switches to your command so that it can be used.

Syntax

Install chocolatey install package package name acme software file type
exe file C: install. Exe silent args /s

This command that will be creating your package. After that has been done,
you will need to pack the package with the use of choco exe.

After your software is packaged properly, you are going to need to format it so
that it can be published in the repository for chocolatey.

For every piece of software that you are wanting to use, you are going to have
to repeat the process so that it is all deployed to chocolatey. There are a few
extra steps that are going to take place to ensure that the software really is
chocolatey ready. However, doing this is going to allow you to do your tasks
that matter rather than attempting to figure out how to deploy your software to
several machines at the same time.
Chapter Eleven: Integrating Ansible and DSC to
PowerShell

As an IT administrator, having to manage multiple servers is going to take up a


lot of time. You are going to have to install software, fix any security issues
that there may be, and so much more. This is going to be when you are going to
want a configuration management tool. A tool such as Ansible is going to allow
an IT administrator to make any modifications that need to be done to the
multiple servers at once without having to go to each individually to do the
same thing over and over again. But, with Windows, you are going to have a
configuration tool built in which is known as the desired state configuration
(DSC). However, which one is going to be best?

When you use Ansible the engine is going to be set up to deliver the
configurations for DSC to any servers that will take advantage of both
technologies. But, Ansible does not support DSC on its own, there has to be
some modifications done to it so that it will work. The first thing that you are
going to do is get the module for Ansible, at this time there is not one that is
available in the box, but there is a built-in module with the title of win_dsc5
that is going to be there for you to make playbooks for Ansible before DSC
moves over and invokes them. You will have to download them and add them
to your Ansible server first before the can be executed.

With the Ansible module, PowerShell version 5 needs to be running on each


node which is why it is recommended that you have the DSC Local
Configuration Manager node turned off. You will want this disabled due to the
fact that the win_dsc5 module is going to work directly with DSC resources to
invoke the DSC resource rather than the LCM.

After your module has been placed on the Ansible server, you are going to
have the tools you need to reference your module in the playbooks that you
create with Ansible.

Example:
Title #make sure that GUI is removed

Win_ dsc 5

Name of resource: Windows feature

Title: Server gui shell

Ensure: current

You will notice that when you are building a task in Ansible, it is going to be
similar to creating the configuration that will be used in DSC through the
specification of the resources and the properties that are in that resource. The
Win_dsc5 module is going to go through every property and that properties
value over to DSC. This is going to mean that you are not going to need to
define every attribute in the DSC resources that you are using.

Example:

Title: place the DNS server query order

Win _dsc 5

Name of resource: GIH_ network adapter

Interface nickname: ethernet

Address: 392. 482. 2. 2

Ensure: current

Should you run into an issue, you should go back and look at your resources
because it could not be located with the DSC resource that was originally
invoked from your target node which needs to be made available to
PowerShell. Therefore, you need to figure out a way to copy the DSC modules
for every target node. You are going to have a couple of options for this.
However, it is going to be either method that will copy what is in the playbook
so that you can place it where it needs to go.

By using Ansible to invoke the DSC resource, you are going to be working
with both modules. Being that DSC is not going to have the updates that will
allow it to manage the configuration across several nodes at once, an
administrator is going to be forced to build their own tool for this. But, when
you use Ansible, you are going to be able to stop doing this and figure out a
way to work with the configuration management tool that has already been
designed.
Chapter Twelve: Exploring the Abstract Syntax Tree
that Works with PowerShell

By now you probably know that PowerShell is a language that is automated.


PowerShell is also known for the fact that it can create active directory users,
exchange mailboxes, move files, and tons of other things all in one program
without having to worry about not having the tools that are going to assist you
in making your job easier.

The first thing you have to do to make all of these actions be executed is to
write the script, and writing script can be complicated depending on what it is
that you are doing. While you are writing them, it is easy to forget that there is
a particular order that your script has to follow. Essentially, every script you
write is going to be able to be broken down into multiple components. These
components are functions, variables, conditions, so on and so forth. You may
not realize what is going on because it looks like nothing more than a lot of text
that you have placed in a file, however, your code is going to be placed in a
specific order so that it executes properly. This order is going to be shown in
PowerShell by use of the abstract syntax tree (AST)

Your AST is comprised of the .net namespaces that are going to break your
code down into the most logical components. Parsing the script in this manner
is going to give you several benefits that you may not have noticed before, like
locating all of your variables, any functions that have been declared, so on and
so forth. You are not going to need this each time that you use PowerShell
necessarily, however when it comes time that you do, AST makes sure that you
are working with a clean solution rather than having script that looks messy
and is hard to follow.

In this example, you will first see PowerShell to parse the script

Example:

Function do something {
Param ($name)

Do thing title tool.'

Write out text is this thing on?

Now when you parse this code, you need to insert the parse file method on
your object.

Example:
[System.Management.Automation.Language.Parser]::ParseFile('C:\Script.ps1',
[ref]$null,[ref]$Null)

With this step parsing your script, your code will now be broken down into the
logical components.

PS C:\> $ast

Attribute { }

Use of statements { }

Argument block

Start block

Process block

Block end

Function do thing {

Param ($title)
}

Do thing -title -tool

Write out message is this thing on

Dynamic argument block

Requirements for script

Extent

Function do thing {

Argument ($title)

Do thing title tool

Write out message does this thing work

Parent
Rather than having a lot of text in your code, your script is going to be parsed
to just the important components. After the code has been put into this format,
you are going to do some modifications to it. For example, if we wanted to find
any function declaration that is inside of the script, you are going to use the find
all () function technique.

Syntax:

PS C:\> $AST.FindAll({$args[0] -is


[System.Management.Automation.Language.CommandBaseAst]},$true )

Every function is going to be able to pull the call inside and modify the search
before locating every variable that is inside as well as changing the object
type.

Syntax

PS C:\> $AST.FindAll({$args[0] -is


[System.Management.Automation.Language.VariableExpressionAst]},$true)

Every component that is in your PowerShell script that is listed under the
system management automation language namespace. In order to look at every
option type that is available to you, you will hit the table key while on your
PowerShell console. Several of the objects are going to be found, but it is not
going to make sense instantly. Despite that small issue, you should still try the
objects out in your code just so you can see how they work and what is going
to be returned to you. In doing this, you are going to locate functions and
variables along with variable types, parameters for functions and a lot more
that you will be able to use.

AST is a complicated topic, but it is one of the few things that you are going to
want to use and learn by trial and error. After you have gotten the basics down,
you are going to be able to expand the knowledge that ou possess and parse all
of your scripts.
Chapter Thirteen: Working with JSON Data in
PowerShell

While the world around us is constantly overtaken by software, those who


work in the IT field are going to have a front row seat to how software is
taking over our world due to the fact that they work with the software defined
programs that are replacing everything that we know. One of the biggest
components that you are going to want to focus on with your software is the
constant adaptation of the DevOps applications. Any of these services are
going to need to communicate so that they can provide a path for the programs
and users to interact with them and make them work as they need them to work.
This is where you are going to want to use an API.

What we are going to be looking at is the rest API that is going to send back
data whenever searched. It is this data that is going to come in the JSON format
normally. JSON is one of the methods that you can use to structure your data so
that the software is able to intake the data properly. While working with
PowerShell, you are going to have tools at your disposal so that you can work
with JSON. One of the tools is going to convert your data from JSON, and the
other can convert it from JSON. These commands are going to work quickly
with the rest APIS or a great number of other services where a return and be
sent out or accepted in the format of JSON.

Lets look at these two commands and see how they are going to work.

The JSON is going to work with the rest API or any other service that you may
want it to work with.

Example:

{"employees":[

{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},

{"firstName":"Peter", "lastName":"Jones"}

]}

It is in this example that you are going to be showing the objects of the
employees with the array and there are going to be three objects listed inside
of that array. At this point in time we are going to assign the string varaible
inside of PowerShell.

Example:

$employees = '{"employees":[

{"firstName":"John", "lastName":"Doe"},

{"firstName":"Anna", "lastName":"Smith"},

{"firstName":"Peter", "lastName":"Jones"}

]}'

If you just read the string, then there is not going to be a lot that you can do with
it. Really, there is no way that you are going to have the capabilities to extract
specific employees without using a string manipulation which is going to
extend your code and get messy. Instead, you are going to use the JSON data
and turn it into a structured object. Once all of the objects have been made in
PowerShell, you are going to use the convert from json code on the
$employees code.

Once you have done that, you should see that the object is in a position that is
going to make it easier for you to parse the object. However, when you
perform the task for each employee on the list.

Syntax

$employeesObj.employees | foreach { $emp = $_; Get-AdUser -Filter "


(givenName -eq '$($emp.firstName)') -and (surName -eq '$($emp.lastName)')"
}

Using the convert command for json you are going to have the option of
converting any piece of code for json straight into the PowerShell object.
However, you do not have to do this if you do not want to. You can take your
object and send it to your rest API or any other selected service where json
data is required. For this you are going to use the convert to command.

In order to use the convert to command, you are going to be doing the opposite
of what you were doing with the convert from command. Your command is
going to pull your object and convert it into a json string. But, with your data in
this form, you cannot truly work with the object in powerhell. You are typically
going to use this command when you need to manipulate the object before
working with a pure source of json code.

Your convert to and convert from json commands arethe only two commands
you are going to use when working with json in PowerShell.
Chapter Fourteen: Automating SQL Server
Deployments with DSC

Your job can change at any time. Your boss could come up to you and say that
you need to work with a server that is running off of SQL and it needs to be up
and ready to be used by everyone by Friday. While this is going to sound like
something that you are not going to be able to accomplish, you are gong to be
able to. Before you continue, you are going to need to figure out where the ISO
for the SQL server is. In this section, you are going to learn where that ISO is
and how you can use SQL with DSC.

Thanks to PowerShell and DSC you are no longer gong to have to write out
long scripts that are going to only execute a simple task. Thanks to DSC, you
are going to have the ability to write the configuration for a task and have it
applied across a single server, or several servers at one time. Thankfully,
Microsoft has made it to where DSC resources are going to work with SQL
servers and you should take advantage of that!

You need to ensure that you are working with PowerShell version 5 for this
strategy. It was with this version that DSC was improved upon thanks to
updates. The first step is to make sure you can create a configuration with
DSC. In order to do this, you are going to use the optional configuration data
since the SQL server is going to require credentials. You do not have to set out
the specifics for an option that is going to enable plain text credientals through
the configured data. Instead, you are going to have to set certificates that are
gonig to work with your credentials.

You can create a configured data file and place all the information that you are
going to need to enable the plain text passwords for the DSC MOF file as well
as the node that is going to apply to this configuration.

Example:

@{
AllNodes = @(

@{

NodeName = '*'

PSDscAllowPlainTextPassword = $true

},

@{

NodeName = 'localhost'

With your data configured, you are going to move on to create the DSC
configuration.

This code is going to hold every bit of script that is going to represent the SQL
server and what it is going to look like when it is deployed. You need to open a
text file and copy and paste all of the code into it.

Syntax

#requires -Version 5
Configuration SQLStandalone
{
param(
[pscredential]$SetupCredential ## Need to pass a credential for setup
)
## Download the xSQLServer module from the PowerShell Gallery
Import-DscResource -Module xSQLServer

## Run this DSC configuration on the localhost (gathered from configuration


data)
Node $AllNodes.NodeName
{
## Install a prerequisite Windows feature
WindowsFeature "NET-Framework-Core"
{
Ensure = "Present"
Name = "NET-Framework-Core"
Source =
"\MEMBERSRV1InstallersWindowsServer2012R2sourcessxs"
}

## Have DSC grab install bits from the SourcePath, install under the
instance name with the features
## using the specified SQL Sys admin accounts. Be sure to install the
Windows feature first.
xSqlServerSetup 'SqlServerSetup'
{
DependsOn = "[WindowsFeature]NET-Framework-Core"
SourcePath = '\MEMBERSRV1InstallersSqlServer2016'
SetupCredential = $SetupCredential
InstanceName = 'MSSQLSERVER'
Features = 'SQLENGINE,FULLTEXT,RS,AS,IS'
SQLSysAdminAccounts = 'mylab.localAdministrator'
}

## Add firewall exceptions for SQL Server but run SQL server setup
first.
xSqlServerFirewall 'SqlFirewall'
{
DependsOn = '[xSqlServerSetup]SqlServerSetup'
SourcePath = '\MEMBERSRV1InstallersSqlServer2016'
InstanceName = 'MSSQLSERVER'
Features = 'SQLENGINE,FULLTEXT,RS,AS,IS'
}
}
}

As you can see in the code, you are going to see comments that are going to tell
you various things about the code that are going to make it easier for you to
understand. There is the possiblity that the code does not make a lot of sense to
you at first, however, it will begin to make more sense to you as you learn
more about the DSC and practice it with your own code.

Take note of what is on line nine, there is the import resource code and this is
crucial to your code. This is going to bring the SQL module where all of SQL
DSC resources that are going to need to be used when you are trying to run the
configuration. It is these resources that are going to be easy for you to obtain by
downloading them from the PowerShell gallery. You can always open a
PowerShell console and be able to detmine if your module is the module you
are looking for by using this code.

Syntax

Find module name xSQL Server

You may also notice that version 2 is available for you to use by installing the
find module to the install module.

Syntax

Find module name xSQL Server | install module

You can now verify every bit of the SQL Server with the DSC resources that
are made available through the program.

Syntax
Get dsc resource module x SQL server
After you have built the configuration, you are going to create a MOF file for
your node so that the server has something to be installed on. In an effort to do
this, you are going to use a dot source with the configuration that was built on
the sessiont hat you are currently using which is going to make the DSC
configuration that is available a stand alone for SQL.

When you execute the configuration iti s going to create a MOF file for your
server which is going to be installed with the SQL Server on the DSC. With the
MOF file you are going to call on the local host.mof which is going to hold all
of the instructions tha tyou need to for installing the SQL server to the machine
that you are using.

Syntax

Start dsc configuration wait force path C: SQL stand alone verbose

When doing this process, it is going to take quite some time to complete since
it is instlaling the entire SQL server. As long as it runs into no issues, the
server is going to tell you that you need to reboot your system or it is going to
reboot automatically dependiong on the reboot settings.

And that is it. You are done. You have no successfully installed the SQL server.
When you use the appropriate configurations you are going to be able to go
through this process multiple times over making it easier and easier each time
that you do it.
Chapter Fifteen: PowerShell Cmdlets that are
Essential for Managing the Active Directory

As you administer the active directory, you are going to be performing one of
the most critcal roles that there is in Windows. It is going to be in this chapter
that you are going to learn some of the basics for using the active directory and
the accounts on it.

Creating a Test Domain

As long as you understand how to use DSC then creating the test domain is
going to be easy to follow. First you are going to create a Windows server
2012 R2virtual machine. If you want, you can use Azure to create the virtual
machine, however you can also choose somewhere else to create it to. Azure is
going to make it to where you can isolate the virtual machines into individual
networks. Doing this is going to make it to where you run the risk of doing you
tasks on the production network where people do not like tasks being
performed.

With PowerShell 5, you can gain acess to the PowerShell gallery. If you are
working on an older version, then you need to download thr virtual machine
module. Once you have finished the installation process, your computer will
need to restart. When you log back in, you are going to be working on a domain
instead of you machines account.

Exploring Domains with PowerShell

First thing that youa re going to od is gather some basic information with your
new domain by using the get addomain cmdlet. One of the most intersting
things about this cmdlet is that you are going to be able to see the domain
mode. The mode for the domain is going to be one of the biggest influences on
your code which is going to depend on if you can use the managed service
accounts portion of PowerShell. Should you not set the domain up, then you are
going to be able to obtain the information that you ned easily.
PowerShell is going to inform you of anything that you are wanting to know
about the domain, and you are going to know what is available to be used with
the get command cmdlet which will show you all of the cmdlets that can be
used with the get verb.

With the get verb there at are least forty-three different cmdlets in the active
directory module which of course is going to be a lot of information to
process. One of the main things that you are going to want to do is to locate
information about the users with the get aduser command.

You may realize that you have already run into an error message. This can be
fixed easily though, all you need tothink about is the domain and how you do
not need to return every user that is in the domain. Therefore you are going to
use a filter with this cmdlet.

You have the opprotunity to use the get aduser and insert a single user name
or you can filter it to locate multiple accounts. Either technique is going to
work and give you the result that you are wanting, however if you use the filter
syntax, the parameters will need to target the properties that are on the list and
use some of the comparison operators against the the value that is entered. Not
every comparison operator is going to be supported with your -filter
parameter, but to execute the script, you are going to get a detailed summary.

Syntax

Get help get aduser parameter filter

The properties you see on your screen are only going to be some of the
properties that are in the cmdlet for that object type. You can add in the -
properties parameter in order to obtain all the available properties PowerShell
has to offer.

After using the filter syntax, you ar enot always going to have to enter the
whole filter to find the user you want to find, you can use the call get
aduserabertram in the event tha tyou know who you are looking at.
Another thing you may want to explorer is to find out about groups. A group is
going to make it easy for you to find the users that you may commonly need to
find or the members that are part of a special club. Using the get adgroup is
going to filter out to the groups based on the membership a user is holding in
that group.

Your cmdlet that is used to find the users is going to have a different name. The
syntax for it is: get ad principal group membership. This cmdlet will refer to
the principal rather than refer to the user.

The cmdlets are also going to make it to wher eyou can work with users on he
level of modifying their profile, or even adding in members so that they are
part of the active directory. Anything that you do with an account is going to
have to be marked explicity or else the program is gonig to makr it as disabled
by default.
Conclusion
Thank you for making it through to the end of PowerShell, lets hope it was
informative and was able to provide you with all of the tools you need to
achieve your goals whatever it may be.

The next step is to take the strategies that you have learned in this book and
apply them to your code writing. You have learned a lot in this book and it is
going to be enough to assist you in making sure that you are fully prepared
when it comes to coding with PowerShell.

If you are an administrator or in the IT department, hopefully this book has


shown you some good tips that you are going to be able to use and that you may
have learned something new.

Finally, if you found this book useful in any way, a review on Amazon is
always appreciated!

Thank you and good luck!

Do not forget to check out the beginners guide and the tips and tricks book!

You might also like