Week 1: A Better Basics Rundown

DISCLAIMER: This was originally a way to document what I was learning when I first ran into PowerShell as a student who had no prior scripting experience. The examples given and the posts done in relation to the project most likely do not follow best practices and should definitely be reviewed if they are going to be used in any fashion. You have been warned! ūüôā

I thought we only see blue screens when we die. I was wrong.

PowerShell has a vast amount of resources scattered around the internet. Being the first week, this was more about basic functionality and tutorial hunting. It’s time to look at the CLI (Command Line Interface)!

What is this post about?

  • PowerShell Resources
  • Cmdlets
  • Aliases
  • Some cmdlets
  • Variables
  • Super Simple Script I
  • Mistake of The Week

PowerShell Resources

Being the first week truly diving in, it was pretty obvious that I was going to grab the internet for all of it’s essential resources. Rampant assimilation brought me a good starter pack for PowerShell scripting! This list will soon be posted on The PowerShell Project page. It will be periodically updated for when I find more cool stuff.

What are Cmdlets?

These are the foundations of PowerShell. Every thing you do will generally be due to running a cmdlet. Want to change a directory, copy a file, sort the contents of subdirectories, etc? All of these flow through cmdlets. Get-Help, Get-Process, Set-Location, etc. It is a collection of verbs-nouns that open the gates to the command line. Do you know what else is cool?

Note of Awesome: Use the Tab button. PowerShell has integrated tab-completion for cmdlets, their parameters, and files within the directory. It’s pretty cool stuff, especially when I have no idea what I am doing.

What are Aliases?

Aliases are simple commands like:

ls
cd
cp
md

They are really like shortcuts to the actual cmdlets, which would have been these (in the following order):

Get-ChildItem
Set-Location
Copy-Item
New-Item

You can view all aliases by simply typing Get-Alias,¬†or even use it’s alias:¬†gal.¬†Whoa, but wait a minute! I haven’t even explained what any of these thrown around commands even mean yet!

What are Some Basic Cmdlets?

Let’s dive right in!

  • Set-Location <filepath>
    Description: Navigate directories through the CLI
    Example: cd “c:\totally awesome\”¬†

This will bring you to the¬†totally awesome folder. Notice I used quotations, and cd as the alias of Set-Location. Because of the space in the directory name, I needed to place them so that the cmdlet didn’t think totally and awesome were two different parts of the command.

  • Get-ChildItem
    Description: List the contents of a directory.
    Example: ls -recurse -include *.avi

This will list all files in the current directory when I type ls, an alias of Get-ChildItem. Adding the -recurse paramater, a paramater being an added characteristic of a cmdlet, this command is also listing the file contents of all subdirectories in the current path. Though, becuase the -include is attached toward the end, the current command is going to sort out only the file/file-type you are looking for. The files that it will list are only .avi files. Notice the asterisk, also known as a wildcard, as it will mean something like any-titles. As a result, the complete command lists all the .avi files in the current directories and subdirectories.
Sweetness.

  • New-Item
    Description: Create a new files or folder.
    Example: md ./Awesome/

Creates a folder in the current directory called “Awesome.” The period before the /Awesome means “in this directory,” while a double-period (..) would instead mean “in the parent directory of this directory.”
NOTE: Copy-Item (alias: cp) and Remove-Item (alias: rm) are done in the same format, except instead of merely mentioning one directory, you would mention two. One side-by-side after the cmdlet, the first filepath being the source and the second being the destination.

Piping

Piping takes the output of a command, and then reacts to it. You would have a hard time creating a productive script without doing it, most likely. Further on in this post, you will see me piping by using the button below backspace ( | ) to flow commands through. When I began typing an explanation, I realized there is a far better rundown about what piping is by Microsoft themselves. Then again, the technet pages are an exceptional library of detailed walk-throughs. Of course, I’m not saying that you aren’t interested in my disembodied tutorials.

You’re saying that. Stop it.

Variables

Variables are like user-defined objects. Let’s say your script constantly references a specific file location, and you want to be able to adjust the script without having to replace the long file location referenced all over the place. If you simply define a variable as the directory location in the beginning of the script, you can just reference the variable each time instead.

You make a variable by typing a word-of-choice with the dollar sign ($) in front of it.

Defining a variable and using it:
$wat=”c:\user\derekface\documents\journal\entire life\philosophy”
rm -recurse $wat
md $wat
md $wat\sadness

Super Simple Script I

This is the first script of the project! You will be able to find this script, and all future ones, posted on the project’s Super Simple Scripts page. The script of the week started with an annoying issue.

I have been watching tutorial videos all about cool techie stuff. The problem is, I have them scattered among multiple DVD data disks. On top of that, the videos are generally buried in a directory tree as irritating as stubbing your toe. After searching one-by-one through the GUI to organize the video tutorials, I realized I could write a script!

get-childitem “D:\” -recurse -include *.avi | copy-item -destination “C:\users\derekface\My Videos\Learn Me”

In my situation, the files were .avi format videos, with any name, that I wanted moved from the disk to a destination in my “My Videos” folder. Though, this isn’t a script just yet. Why not allow it to work on other computers better?

# Searches directory/subdirectories for specific file types then copies to destination
$user = [Environment]::UserName
$filesrce = “D:\”
$filedest = “C:\users\$user\My Videos”
$filetype = “avi”

ls $filesrce -recurse -include *.$filetype | cp -destination $filedest

I started the script with a comment, which is a message describing what the following lines will do. These are only for reference, and are skipped when a script is ran (all comments MUST start with a # at the beginning of the line). Next, we grabbed the information from windows about who the current user is that is logged on and made a variable with it. We then referenced the variable when looking for the appropriate folder destination before defining the file type.

The two aliases, ls and cp, are commands that are also used in Linux terminals. They even work in a similar fashion (mostly). It’s like you are learning two languages!

An interactive script would prompt the user for the answer so that they don’t have to edit the script .ps1 (PowerShell script file extension) file itself:

# Searches directory/subdirectories for specific file types then copies to destination
$filesrce = Read-Host “Enter Directory to Search”
$filedest = Read-Host “Extract Files Here”
$filetype = Read-Host “File Type to Search For (examples are avi, pdf, txt)”

ls $filesrce -recurse -include *.$filetype | cp -destination $filedest

Mistake of the Week

We learn best from our mistakes, right? Every week, I will shamefully include a goofy mistake I made while creating the Super Simple Script.

I thought I could use the same setup to copy one folder and all of it’s subdirectories from my external hard-drive to the PC. Little did I know that this was pointless:

ls <folder> -recurse | cp -destination <destination>

What this command did instead, was search for all files and folders in the directory, and then copy them all into the destination folder…completely unorganized. The subdirectories copied over were empty, and their contents mixed with everything else in the root of the folder I replicated. What happened?!

Well, the Get-ChildItem (ls) command really just listed all the files\folders that could be found in the source directory. Next, it piped the whole list of files into a command that dictated every single file and folder to be emptied out into the destination. The correct command we were looking for really just needed to copy a source directory with all of it’s subdirectories:

cp <source> <destination> -recurse

It really was far simpler than I made it out to be!

Whew. Now that finishes up this long intro article that is replacing my two previous “Learning PowerShell” posts. See you next week!

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s