Powershell: Get-Help

Posted by Kris Powell

Sep 18, 2014 1:48:00 PM

kris_resizedFrom the results of my last Powershell blog post (Get-Command and Get-Member), we should have a list of commands (cmdlets, aliases, etc).

But, how do we know what each cmdlet does?  Or, what if we know how a command works but want to see some examples?

We need some more information about how to use those commands in more detail.  Let’s learn more about the Get-Member cmdlet that we introduced last time by utilizing the tools built into Powershell.

Get-Help

Get-Help displays detailed information about how to use a command and any examples that may exist.

The basic syntax is pretty simple and straightforward.

Get-Help <cmdlet>

In order to find out more about the Get-Member cmdlet, we type:

Get-Help Get-Member

This will give us some basic syntax and usage information about Get-Member as well as a brief description.  Let’s introduce some of the parameters that give us even more information about the cmdlet that you’d like to know more about.

Get-Help <cmdlet> -Examples

This will show usage examples for the cmdlet

Get-Help <cmdlet> -Detailed

This will show more detailed information than the basic syntax

Get-Help <cmdlet> -Full

This shows the entire help file relating to the cmdlet, including details/examples.

Get-Help <cmdlet> -ShowWindow

This will show the full help file for a cmdlet in a new window.  It includes a search box and a settings button to help you configure which information you want displayed.

Get-Help <cmdlet> -Online

This will pull up the online help files for the cmdlet.


Note: If you find that you’re help files seem to be lacking, it’s possible that they’re not fully installed or up-to-date.  In that case, run Powershell as an Administrator and type the cmdlet, Update-Help and it will update all the associated help files.)

Read More

Topics: powershell

PowerShell: Get-Command and Get-Member

Posted by Kris Powell

Sep 11, 2014 9:10:00 AM

kris_resized

Today, I want to show you a couple great cmdlets that can really strengthen your understanding of 

PowerShell: Get-Command and Get-Member.

Get-Command

Get-Command will list all commands that are installed on the computer, including cmdlets, aliases, functions, etc.

Try it out. The results should look something like this:

 

Get-Commandget-command

There’s a lot of output on the screen, so we can clean this up a little bit to make it easier to read.

Let’s say we just want the name of the commands. We’re going to select only one object property by piping the results of Get-Command and selecting the property that we want to see.

Get-Command | Select-Object Nameget-command select-object name

But, how do we know which object properties exist to select and sort? We’re going to introduce another command today called Get-Member.  

Get-Member

Get-Member tells us about the Properties and Methods of an object.

The easiest way to use it is to pipe in an object that you want to know more about.

Get-Command | Get-Memberget-command get-member

We can see that there are many properties for Get-Command that we can use to sort and view.  Let’s use CommandType and Name.

Get-Command | Select-Object CommandType, Name get-command select-object commandtype name

You should be able to look at that list and find any cmdlet that’s installed that you can use.

In the next blog, we will go over another tool that will help get more detailed information about each cmdlet from within PowerShell itself.

In the meantime, here is more help about Get-Command and Get-Member from Microsoft's Technet:

Get-Command

Get-Member

 
Read More

Topics: powershell

PowerShell:Get-Date Cmdlet

Posted by Kris Powell

Aug 7, 2014 1:26:00 PM

Today, I’d like to make use of an awesome PowerShell cmdlet, Get-Date. Get-Date as the name implies, gets the current date and time and use the results for other cmdlets. Get-Date by itself will return the current date.

powershell get date

We can manipulate this result a handful of ways to make the date into a format that’s more useful to our needs.

We can use -Format to view the date any just about any date format that we can imagine.

powershell get date change format

Here is a great link for which format patterns you can use - http://ss64.com/ps/syntax-dateformats.html

In addition to formatting the date to whatever format suits you best, there are also methods you can use to manipulate the date itself (not just the formatting).

In this example, we can see what day it will be a week from now:

powershell get date manipulate date

Here's a quick list of methods you can use to modify Get-Date:

  • AddDays
  • AddHours
  • AddMilliseconds
  • AddMinutes
  • AddMonths
  • AddSeconds
  • AddTicks
  • AddYears

We can make use of Get-Date and these methods in our scripts to do fancy things like finding all files that have been created within the last 30 days.  We can even take that result and process it to remove the files that are found.

#############################################################################
#   Find files older than 30 days 
#############################################################################

$time = (Get-Date).AddDays(-30)
$path = "C:\temp"

Get-ChildItem -Path $path -Recurse -Force | `
 Where-Object {$_.LastWriteTime -lt $time }

#############################################################################
#   Find files older than 30 days and DELETE
#   Please excercise caution. There is no undo to this action
#############################################################################

$time = (Get-Date).AddDays(-30)
$path = "C:\temp"

Get-ChildItem -Path $path -Recurse -Force | `
 Where-Object {$_.LastWriteTime -lt $time } | `
 Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Read More

Topics: powershell

Powershell: Searching Through Files for Matching Strings

Posted by Kris Powell

Jul 31, 2014 12:51:00 PM

 

kris-151

It can be very time-consuming and tedious to sift through many files. Unless you’re a fan of working over a weekend and opening file after file while being slumped in a chair, then I would suggest making use of the information from today’s Powershell blog post!

Consider a directory, “C:\Temp” with many text files created. Each of the files has random text data inside. We’re looking for only the files that contain one particular string. Additionally, since we don’t know how many matches we are going to find, we’re going to create an array to store the found matches.

In order to search for strings or string patterns, we’re going to use the cmdlet Select-String.

###########################################################

$Path = "C:\temp"
$Text = "This is the data that I am looking for"
$PathArray = @()
$Results = "C:\temp\test.txt"

# This code snippet gets all the files in $Path that end in ".txt".
Get-ChildItem $Path -Filter "*.txt" |
   Where-Object { $_.Attributes -ne "Directory"} |
      ForEach-Object {
         If (Get-Content $_.FullName | Select-String -Pattern $Text) {
            $PathArray += $_.FullName
            $PathArray += $_.FullName
         }
      }
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}


##########################################################

Here’s the breakdown:

This will search the directory $Path for any items that include “.txt” in their names and that are not directories.

Get-ChildItem $Path -Filter "*.txt" | 
   Where-Object { $_.Attributes -ne "Directory"}

For every match it finds, it will check the contents of the match using Get-Content and verify any matches with $Text by using Select-String. If it finds a match, it puts the full name of the match into the $PathArray array.

      ForEach-Object { 
         If (Get-Content $_.FullName | Select-String -Pattern $Text) {
            $PathArray += $_.FullName
            $PathArray += $_.FullName
         }
      }

There you have it.

Bonus options
Exporting results to file:

If you want to export that all to a file instead of on the screen, then simply pipe it into an Out-File cmdlet. For example:

$PathArray | % {$_} | Out-File “C:\Some Folder\Some File.txt”

Searching through all subfolders:

If you want to search all subfolders for additional *.txt files as well, then add “-recurse” to the original Get-ChildItem command:

Get-ChildItem $Path -Filter "*.txt" -Recurse

 
Read More

Topics: powershell

Powershell: How to Write Your First Powershell Script

Posted by Kris Powell

Jul 17, 2014 1:32:00 PM

“I love spending twice as long and working twice as hard to get half as much done!”  – Nobody ever.kris-151

Everybody loves shortcuts and time savers.  I think this goes twofold for the aggravation that comes with managing computers.

Enter Powershell!

Though there are many great scripting languages out there, we're going to spend our time with Powershell. If you're using a recent version of Microsoft Windows, you've even probably already got a version of it installed.  

Powershell saves scripts in the .ps1 format.  I have created both a file and a folder for our demonstration - C:\Scripts\My First Script.ps1 - but please feel free to use your own custom folder and filenames.

Edit your file and add the following line:

Write-Host “Hello, World!”

Save the file and return to the Powershell window. In order to run the script, the most common method is by calling it:

& “C:\Scripts\My First Script.ps1”

Go ahead and try that command.  You should get an error that says scripts have been disabled on your system.

This is normal behavior. In order to prevent malicious scripts from running on your system, Powershell enforces an execution policy.  There are 4 execution policies you can use:

  • Restricted – Scripts won't run.  Period. (Default setting)

  • RemoteSigned – Locally-created scripts will run. Scripts that were created on another machine will not run unless they are signed by a trusted publisher.

  • AllSigned – Scripts will only run if signed by a trusted publisher (including locally-created scripts).

  • Unrestricted – All scripts will run regardless of who created them and whether or not they are signed.

In order to use our newly-created script, we will have to modify our execution policy to allow our script to run.  Since we have not digitally signed our new script, our options for setting the execution policy are left to “RemoteSigned” and “Unrestricted.”  We are going to change it to RemoteSigned.

In order to change the execution policy, we will need to reopen Powershell as an Administrator (the command will fail otherwise) and run the following command:

Set-ExecutionPolicy RemoteSigned

It will ask to verify that you really want to change the execution policy. Go ahead and select Y for yes, then go ahead and close and reopen your Powershell window.

After restarting the Powershell window, go ahead and try running that script again 

& “C:\Scripts\My First Script.ps1”

It should write back, “Hello, World!” to the window:

Congratulations!  You just wrote your first script for Powershell!    

As this blog series continues, we'll continue to add more helpful tips on how to use Powershell.  In the meantime, you know have the amazing power to create and run your own scripts.

Tune in next week for more scripting adventures.


Read More

Topics: powershell

Random Grunts on the Sys Admin Scene

Posted by Shane Corellian

Jan 26, 2011 1:00:00 AM

Shane Corellian Raindog Sys Admin
Photo by Helen Rosemier

I came across a pretty good YouTube channel featuring PowerShell videos. I haven't finished with all of the videos yet but I dig this guy's (Don's) style. I wish the video examples were a little more magnified sometimes but otherwise I'm quite pleased. Definitely check them out.

When you have an obvious language barrier with someone you work with never, EVER, listen to them and just nod your head. In fact when you don't understand a damn word they're saying, violently shake your head and mutter "oh, HELL no". You'll thank me.

If you're getting ready to add a feature to a script or a program make sure to ask yourself this question: What is the real benefit I get from adding this feature? Seriously? If you can't come up with a semi-literate answer, scrap it. Toss it. Move on. You'll thank me.

Sluffing. Hookey. Skipping. Truant. What did you call it when you missed school? Remember how you'd get in trouble for missing that class or even the entire day of school? Well try sluffing a meeting or two at work. If there are more than 6 people in regular attendance at your meeting, skip one every now and then. If there are more than 15 people then count your blessings and have your make to miss ratio come in around 1:5. You'll thank me.

I don't understand why so many computer geeks get upset at how our industry is portrayed in movies. Let the beliefs live on. I'm happy that my family thinks I can create a network connection between my mac and the aliens that are on the way down to earth. I finally look a little cool. I'm pleased that my extended family all think that I can blow crap up by just hitting a few keys on the keyboard. It keeps them in enough awe that I can cut in line to get the best Bratwursts and potato salad at every reunion. Just sayin' is all.


Follow me on Twitter @ShaneCorellian
Read More

Topics: random musings, humor, powershell

Deploy PowerShell 2.0: Distribute to your PCs with PDQ Deploy

Posted by Shane Corellian

Dec 15, 2010 1:47:00 AM

Shane Corellian Raindog Sys Admin
Photo by Helen Rosemier

OK, if you don't have PowerShell 2.0 on your Windows computers it's time to gird up your loins and just do it.

Thankfully, PowerShell comes included with Windows 7 and Server 2008 R2. For your other Windows OSes go grab the appropriate install file. If you don't already use PDQ Deploy for your simple software deployment needs then grab a free copy right here.

It's quite simple to deploy, actually. Just grab the installer file appropriate for your target OS create a deployment in PDQ Deploy

Below is a screenshot of a basic Installation of Windows PowerShell 2.0 for Vista/2008 32-bit computers.

blog spc 20101215 PowerShellInstaller

PowerShell is here to stay and it is a great shell which is something that Windows has been lacking for a long time. I remember when I first started playing with PowerShell back in 2007 I was hooked. For Windows Sys Admins this is a must-use technology.

We are going to add the ability to run PowerShell scripts natively from PDQ Deploy. So get PowerShell 2.0 on your targets systems sooner rather than later... perhaps the slow holiday season perhaps?


Follow me on Twitter @ShaneCorellian
Read More

Topics: install software remotely, pdq deploy, powershell, Microsoft Windows, remote software deployment

Top 10 Rejected Names for PowerShell

Posted by Adam Ruth

Oct 8, 2010 1:00:00 AM

 
What's in a Name?
    Photo by chigmaroff

We in the system administration community have become used to the name PowerShell. I know I have (I write about it often enough.) The name projects an important image. The image of being Powerful and also... I guess... being a Shell. As is so often the case, one must wonder if the product gives meaning to the name or does the name give meaning to the product. Does "Rolls Royce" bring to mind quality because of workmanship or is the name just a great fit? Well, you be the judge as you consider the top 10 names considered and rejected for PowerShell. One thing we can all agree on is that we're glad Microsoft made the choice they did.

10. AlmostBash

9. YAALShell (Yet Another Admin Language)

8. Cmd#

7. ClippyShell

6. Cmdlet Runner And Processor

5. VBScriptWho?

4. HunkyShell

3. LinuxShminux

2. Microsoft Interactive Keyboard Command Line Interpreter Client Console And Dynamic Script Processor 2008 Version 1 (Release 2)

1. DOS 7

Read More

Topics: humor, powershell

6 Missing PowerShell Cmdlets

Posted by Adam Ruth

Oct 1, 2010 1:00:00 AM

  
Something's missingPowerShell 2.0 shipped back in 2009 and included over 100 new cmdlets including major new functionality such as Jobs, Modules, and Remoting. That's great to see, but there's still so much more that can be done. So, in the vein of demanding others to do things for me, here are the top 6* cmdlets that PowerShell should ship with. 

Threaten-Process: For when you want to keep a process from getting out of line but aren't quite to the point that you want to kill it. Alias: taze

Delete-FileForever: Not only deletes a file, but prevents it from ever being re-created. Pretty handy when dealing with viruses or playing pranks on co-workers. Optional argument -past goes back in time and stops the file from originally being created (the Sarah Connor option.) 

Convert-RegistryToIni: Removes the registry completely from the system and replaces it with hundreds of .ini files in the Windows directory. Alias: out-of-the-fryingpan

Set-UACAutoClick: Creates a process to automatically click the accept button on all UAC prompts. For the wishy-washy person that's too scared to disable UAC but wants to get rid of the inconvenience (usually an MBA.) Alias: miss-the-point

Enable-FullSpeed: Makes the processor run at its actual speed, not the speed that's been imposed by the Trilateral Commission to keep the masses from decrypting secret government communications embedded in lolcats. Requires the tinfoil hat extensions. 

Set-MovieInterface: Changes the UI to have really large text, make a clicking sound whenever a character is typed, add unnecessary maps and graphics to search functions, and the ability to extract gigabytes of image data from half an pixel. Alias: fakeintosh


* The list is limited to only the top 6 because there isn't a Finish-MyBlogPost cmdlet. Oh, I guess it's really a top 7 list.

Read More

Topics: humor, powershell

PowerShell Tip: Default Parameter Values

Posted by Adam Ruth

Sep 17, 2010 7:23:00 AM

Default parameter?  I don't get it either.
    Photo by nineball2727

If you've spent any time working with PowerShell you've probably built a function or two. Function parameters are a handy way to make general purpose functions that can be used in a number of different ways. Consider, for example, that you have a function that restarts a service that, for whatever reason, is misbehaving. You could have this:

function RestartService($name) {
net stop $name
net start $name
}

Sometimes you need to add a sleep between the start and stop to make sure that the service comes back up correctly, but you don't want to make a new function (one that sleeps and one that doesn't) so you add a new parameter.

function RestartService($name, $sleep) {
net stop $name
sleep $sleep
net start $name
}

This works great, except now you have to pass in a 0 most of the time, and only use the sleep parameter on those rare occasions. To fix this, you can make the $sleep parameter default to 0 so that if you omit it you don't get a sleep.

function RestartService($name, $sleep = 0) {
net stop $name
sleep $sleep
net start $name
}

This will give you the flexibility you need.

# Don't sleep
RestartService SomeService 
# Sleep for 10 seconds before restarting
RestartService SomeService 10
Read More

Topics: windows administrators, windows administrator tools, powershell

Admin Arsenal Blog

Subscribe to Email Updates