Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all 3333 articles
Browse latest View live

Use PowerShell to Create a User in Active Directory

$
0
0

Summary: Use the Active Directory cmdlet New-ADUser to create a new user via Windows PowerShell.

Microsoft Scripting Guy, Ed Wilson, is here. The Scripting Wife has the Window PowerShell Saturday site bookmarked on her Windows 7 smart phone, and she keeps hitting refresh on the little Internet Explorer window to watch the available tickets for the Charlotte PowerShell Saturday event march down to zero. I will admit, the tickets are going rapidly. This is a great chance to learn Windows PowerShell, meet new friends, and have a lot of fun—all for the nominal cost of lunch.

Use splatting to simplify user creation

The New-ADUser Windows PowerShell cmdlet (from the ActiveDirectory module) has a ton of parameters. Filling these out makes for cumbersome code, and does little to encourage readability. In fact, I hate having to read the command syntax (via Get-Help or Get-Command) because it seems to go on and on and on! I figure that most (if not all) of the attributes that are available to supply for a user in Active Directory can be supplied directly via a cmdlet parameter. (To be honest, I have never had the patience to compare the user schema with the cmdlet parameters to see if something is missing. By the way, anything that is missing can be filled in via the Set-ADUser cmdlet.

One way to make things a bit easier to read (and to open up interesting automation possibilities) is to use the technique of splatting. I have posted a number of Hey, Scripting Guy! Blogs that explain splatting or make use of the technique

Splatting uses a hash table

To use splatting, I create a hash table that has keys that are exactly the same as the names of the parameters of the cmdlet, and I store the hash table in a variable. I then assign values to the keys. These values are passed to the cmdlet when I pass the variable to the cmdlet that contains the hash table. The following command creates a hash table that contains a number of keys that are the same as the parameter names that are used by the Get-ADUser cmdlet.

$users = @{

 "name" = "fred"

 "givenName" = "manfred"

 "l" = "lexington"

}

When I run this bit of code, I see the hash table.

PS C:\> $users = @{

>>  "name" = "fred"

>>  "givenName" = "manfred"

>>  "l" = "lexington"

>> }

>> 

PS C:\> $users

 

Name                           Value

----                           -----

l                              lexington

givenName                      manfred

name                           fred

To use this, all I do is import the ActiveDirectory module, create the hash table, and then pass the hash table to the Get-ADUser cmdlet. This code is shown here.

Import-Module activedirectory

$users = @{

 "name" = "fred"

 "givenName" = "manfred"

 "l" = "lexington"

}

New-ADUser @users

That is it. Now, all I need to do is to figure out a way to read a file of some sort, and automatically create the hash tables. Hmmmm…shouldn’t be too difficult, should it? After all, it is Windows PowerShell.  

Join me tomorrow for more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Creating an Empty Hash Table

$
0
0

Summary:  Learn to create a Windows PowerShell hash table.

Hey, Scripting Guy! Question How can I create an empty hash table?

Hey, Scripting Guy! Answer Use @{} and assign it to a variable:

            $hash = @{}

Use PowerShell 3.0 to Work with Network Adapters

$
0
0

Summary: Learn how to use the Get-NetAdapter CIM cmdlet in Windows PowerShell 3.0.

Microsoft Scripting Guy, Ed Wilson, is here. I must live a rather boring life—although to be honest, it does not really seem to be so boring. Or perhaps, I am just a geek. What am I talking about? I am really excited about the Get-NetAdapter cmdlet in Windows 8 and Windows Server 2012 with Windows PowerShell 3.0. It allows me to easily determine the status of my network adapter. Perhaps because I spend so much time traveling around with my laptop, I am constantly connecting to various networks—wired or wireless.

Personally, I do not like the idea of bridged network connections, and therefore, I always disable the network adapter that I am not currently using. At times, however, I do forget to re-enable that network adapter, and I always spend a few mips before I remember to toggle my network adapters. I wrote a Hey, Scripting Guy! Blog about this a few years ago, How Can I Enable or Disable My Network Adapter. Although it was a cool script, it was a lot of work. With Windows 8 and Windows Server 2012 with Windows PowerShell 3.0, all that has changed—working with network adapters is a piece of cake.

Find and identify your network adapters

The Get-NetAdapter cmdlet returns the name, interface description, index number, and status of all network adapters that are present on the system. This is the default display of information, and it is shown in the image that follows.

Image of command output

To focus on a particular network adapter, I use the name parameter and supply the name of the network adapter. The good thing is that in Windows 8 and Windows Server 2012 the network connections receive new names. No more of the “local area connection” and “local area connection(2)” to attempt to demystify. The wired network adapter is simply Ethernet and the wireless network adapter is Wi-Fi. The following command retrieves only then Ethernet network adapter.

Get-NetAdapter -Name Ethernet

To dive into the details of the Ethernet network adapter, I pipe the returned object to the Format-List cmdlet, and I choose all of the properties. The command shown here uses the fl alias for the Format-List cmdlet.

Get-NetAdapter -Name ethernet | fl *

The command and the output associated with the command are shown in the following image.

Image of command output

There are a number of excellent properties that might bear further investigation. For example, there are the AdminStatus and the MediaConnectionStatus properties. The following command returns these properties.

Get-NetAdapter -Name ethernet | select adminstatus, MediaConnectionState

Of course, there are other properties that might be interesting also. These properties are shown here, along with the associated output (the following is a single logical command broken on two lines).

Get-NetAdapter -Name ethernet |

select ifname, adminstatus, MediaConnectionState, LinkSpeed, PhysicalMediaType

 

ifName               : Ethernet_7

AdminStatus          : Down

MediaConnectionState : Unknown

LinkSpeed            : 0 bps

PhysicalMediaType    : 802.3

I decide to look only for network adapters that are in the admin status of up. I use the command shown here.

PS C:\> Get-NetAdapter | where adminstatus -eq "up"

 

Name                      InterfaceDescription                    ifIndex Status

----                      --------------------                    ------- ------

vEthernet (InternalSwi... Hyper-V Virtual Ethernet Adapter #3          22 Up

vEthernet (ExternalSwi... Hyper-V Virtual Ethernet Adapter #2          19 Up

Bluetooth Network Conn... Bluetooth Device (Personal Area Netw...      15 Disconn...

Wi-Fi                     Intel(R) Centrino(R) Ultimate-N 6300...      12 Up

To find the disabled network adapters, I change the AdminStatus from up to down as shown here.

Get-NetAdapter | where adminstatus -eq "down"

I go back to my previous command, and modify it to return Wi-Fi information. This command and associated output are shown here (this is a single logical command).

PS C:\> Get-NetAdapter -Name wi-fi |

select ifname, adminstatus, MediaConnectionState, LinkSpeed, PhysicalMediaType

 

ifName               : WiFi_0

AdminStatus          : Up

MediaConnectionState : Connected

LinkSpeed            : 54 Mbps

PhysicalMediaType    : Native 802.11

If I want to find any network adapters that are sniffing the network, I look for PromiscousMode. This command is shown here.

Get-NetAdapter | ? PromiscuousMode -eq $true

Join me tomorrow when I will present additional information about using Windows PowerShell 3.0 to work with network adapters.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Find the Length of PowerShell Aliases

$
0
0

Summary: See how to determine the distribution of Windows PowerShell cmdlet aliases by length.

Hey, Scripting Guy! Question How many Windows PowerShell aliases are 1-letter or 2-letters or 3-letters in length? In fact, how do you determine what the entire distribution of cmdlet alias lengths is?

Hey, Scripting Guy! Answer Use the Get-Alias cmdlet to retrieve all of the aliases. Then pipe the aliases to the Foreach-Object cmdlet and convert them to strings and retrieve the length property.
             After you have done that, pipe the results to the Group cmdlet and sort by the name property (which will be the actual length of the alias.

Get-Alias | % {$_.tostring().length} | group -NoElement | sort name -Descending

Use PowerShell 3.0 to Stop Network Adapters on Windows 8

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell 3.0 to stop network adapters on Windows 8.

Microsoft Scripting Guy, Ed Wilson, is here. The other day a customer asked me, “Is it a Microsoft requirement that all their consultants can’t be more than five miles from a coffee house?” Perhaps a little bit of background is in order. I was onsite with a large Microsoft premier customer, delivering a Windows PowerShell class. Their TAM, Robert, is one of my good friends at Microsoft, and I have worked with him for over a decade. Because I miss my teapot and my stash of teas, I developed the habit of stopping by the coffee house after lunch and getting a large cup of green tea—they actually have a pretty nice green tea with spearmint and lemon grass in it. They had no monkey-picked and no jasmine; but after all, it is a coffee house and not a tearoom. I was happy with what I could obtain. I looked around, and all of the Microsoft people (there were other consultants working on various projects as well) had similar looking large cups of coffee. And thus the question. Although both Microsoft and this particular coffee house chain are based in Seattle, as far as I know, there is no other relationship—and most certainly, there is no proximity-based requirement.

Stopping network adapters

Windows Vista introduced the ability to stop a network adapter by using the Win32_NetworkAdapter WMI class. In the following example, I use the Get-CimClass cmdlet from Windows PowerShell 3.0 to return cimclassmethods from the Win32_NetworkAdapter WMI class. I use the dotted notation and automatic foreach technique to pipe the resulting class methods to Where-Object (? is the alias), where I use the simplified Where-Object syntax from Windows PowerShell 3.0 to find only the implemented cimclassmethods. (For more information about these types of Windows PowerShell 3.0 syntax tricks, see My Five Favorite PowerShell 3.0 Tips and Tricks.) The Win32_NetworkAdapter class methods are shown here.

PS C:\> (Get-CimClass win32_networkadapter).cimclassmethods | ? qualifiers -match implemented

 

Name                            ReturnType Parameters           Qualifiers

----                            ---------- ----------           ----------

Enable                              UInt32 {}                   {Implemented, Map...

Disable                             UInt32 {}                   {Implemented, Map...

In Windows 8 and Windows Server 2012, I can use Windows PowerShell 3.0 to stop or to start a network adapter by using one of the CIM commands. Of course, the function wraps the WMI class, but it also makes things really easy. The netadapter functions are shown here (gcm is an alias for the Get-Command cmdlet.)

PS C:\> gcm -Noun netadapter | select name, modulename

 

Name                                       ModuleName

----                                       ----------

Disable-NetAdapter                         NetAdapter

Enable-NetAdapter                          NetAdapter

Get-NetAdapter                             NetAdapter

Rename-NetAdapter                          NetAdapter

Restart-NetAdapter                         NetAdapter

Set-NetAdapter                             NetAdapter

Note   To enable or disable network adapters requires admin rights. Therefore, you must start the Windows PowerShell console with an account that has rights to perform the task.

The various network adapters on my laptop are shown in the image that follows.

Image of menu

I do not like having enabled, disconnected network adapters. Instead, I prefer to only enable the network adapter that I am using. (There are a number of reasons for this, such as simplified routing tables, performance issues, and security concerns.) In the past, I wrote a script. Now I only need to use a Windows PowerShell command. If I only want to disable the non-connected network adapters, the command is easy. It is shown here.

Get-NetAdapter | ? status -ne up | Disable-NetAdapter

The problem with the previous command is that it prompts as shown in the following image. This is not much fun when there are multiple network adapters to disable.

Image of command output

To suppress the prompt, I need to supply $false to the –confirm parameter. This is shown here.

Get-NetAdapter | ? status -ne up | Disable-NetAdapter -Confirm:$false

A quick check in Control Panel shows the disconnected adapters are now disabled. This appears here.

Image of menu

If I want to enable a specific network adapter, I use the Enable-Network adapter. I can specify by name as shown here.

Enable-NetAdapter -Name ethernet -Confirm:$false

If I do not want to type the adapter name, I can use the Get-NetAdapter cmdlet to retrieve a specific network adapter and then enable it as shown here.

Get-NetAdapter -Name vethernet* | ? status -eq disabled | Enable-NetAdapter -Confirm:$false

It is also possible to use wildcard characters with the Get-NetAdapter to retrieve multiple adapters, and pipe them directly to the Disable-NetAdapter cmdlet. The following code permits the confirmation prompts so that I can selectively enable or disable the adapter as I wish.

PS C:\> Get-NetAdapter -Name vethernet* | Disable-NetAdapter

 

Confirm

Are you sure you want to perform this action?

Disable-NetAdapter 'vEthernet (InternalSwitch)'

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help

(default is "Y"):y

 

Confirm

Are you sure you want to perform this action?

Disable-NetAdapter 'vEthernet (ExternalSwitch)'

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help

(default is "Y"):n

That is about it for now. Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Create a Strongly Typed Array in PowerShell

$
0
0

Summary: Learn how to create a strongly typed array.

 

Hey, Scripting Guy! Question I want to create a strongly typed array of system.diagnostics.processes and store it in a variable called $a. How can I do this?

Hey, Scripting Guy! Answer Use a command such as:

[diagnostics.process[]]$a=get-process

PowerShell 3.0 is now available for download!

$
0
0
Summary: Windows PowerShell 3.0 is now available for download! WOOHOO! Windows PowerShell 3.0 is now available for download for Windows 7, Windows Server 2008 R2 and for Windows Server 2008. Windows PowerShell 3.0 comes in the Management Framework...(read more)

Use PowerShell 3.0 to Rename Network Adapters

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell 3.0 in Windows 8 to rename network adapters.

Microsoft Scripting Guy, Ed Wilson, is here. I received an exciting email yesterday from Lido Paglia. As you may recall, Lido was a winner of the 2012 Scripting Games. I think it is so cool that he is now going to start a Windows PowerShell User Group in Philadelphia, and their first meeting is on October 4, 2012.

The Charlotte Windows PowerShell User Group is sponsoring PowerShell Saturday on September 15, 2012 at the Microsoft office. There are still a few tickets left, but they are selling quickly. If you want to attend, please do not wait until the last minute, because it may be too late. The PowerShell Saturday in Columbus, Ohio sold out, and there was a long waiting list for tickets that never became available. Go ahead and register now. With three tracks and 15 presentations, it will be a tremendous learning event for a nominal cost. We have some major sponsors who have stepped up to defray most of the expensed for this event. We even have PowerShell Saturday T-shirts (the T-shirt is worth more than the registration fee). It will be a really cool event.

Renaming network adapters

One of the things that quickly becomes confusing, especially if you are using Hyper-V, is the way the numbers of network adapters seem to proliferate. I mean, it is like one day all I have is a wired Ethernet adapter and a wireless network adapter—and the next day, I have twelve other adapters, and I have no idea what they do, where they came from, or even which ones I can disable and still remain connected to my local network and the Internet. The following image shows the results of using the Get-NetAdapter Windows PowerShell cmdlet from Windows 8 and Windows PowerShell 3.0.

Image of command output

After I figure out what a network adapter does, and to which network it connects, I like to rename the adapter. I developed this habit when I was a consultant, and it is something I continue to this day. The difference is that now I use the Rename-Adapter Windows PowerShell cmdlet to do the heavy work.

Renaming a network adapter via Windows PowerShell requires admin rights. Unfortunately, the Help does not mention this. You just have to sort of know this. Luckily, an error occurs if you attempt to run the command without admin rights. The error is instructive, and it informs you that access is denied. The error is shown here.

Image of command output

The good thing is that the access denied error appears. Some cmdlets do not display output and do not let you know that you need admin rights to obtain the information. The Get-VM cmdlet is one of those. It returns no virtual machine information, but it does not generate an error either. This situation is also true with the Start-VM cmdlet. It does not do anything, but does not generate an error if you do not have admin rights.

So I close the Windows PowerShell console, right-click the Windows PowerShell console icon that I created on my task bar, and run Windows PowerShell as Administrator. I now run the command to rename my network adapter with the whatif parameter to ensure it accomplishes what I want. Here is the command I use:

PS C:\> Get-NetAdapter -Name v* | ? status -eq up | Rename-NetAdapter -NewName "192.1

68.3.0" -whatif

What if: Rename-NetAdapter -Name 'vEthernet (WirelessExternal)' -NewName '192.168.3.0

Groovy. That is exactly what I want to happen. I now use the Up arrow and remove the whatif. Here is the command. (No output returns from this command.)

Get-NetAdapter -Name v* | ? status -eq up | Rename-NetAdapter -NewName "192.168.3.0"

That is all there is to renaming network adapters. Join me tomorrow when I will talk about more way cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Finding Letters in Strings with PowerShell

$
0
0

Summary: Learn four ways to use Windows PowerShell to find letters in strings.

Hey, Scripting Guy! Question I want to find out if a string contains the letter “m.” The string is stored in the variable $a as shown here:

$a=”northern hairy-nosed wombat”

Hey, Scripting Guy! Answer Here are a variety of ways to accomplish this:

a.  [string]$a.contains(“m”)

b.  $a.contains(“m”)

c.  [regex]::match($a,"m")

d.  ([regex]::match($a,"m")).success

Discover Windows PowerShell 3.0 Cmdlets

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about discovering Windows PowerShell 3.0 cmdlets.

Microsoft Scripting Guy, Ed Wilson, is here. There are still a few tickets available for Windows PowerShell Saturday in Charlotte, North Carolina on September 15, 2012. The agenda includes sessions about Active Directory, SharePoint, Exchange Server, Windows 8, in addition to beginner and advanced Windows PowerShell sessions. This is a great chance to learn about Windows PowerShell from world class speakers, meet fellow Windows PowerShell enthusiasts, and fill your contact lists with excellent resources. Yep—networking at a Windows PowerShell Saturday event is always exceptional, and this event will prove to be another opportunity to meet new friends and to make important Windows PowerShell contacts.

You may want to take the survey that was put out by the community group organizing the next Windows PowerShell Deep Dive in Redmond, Washington at the Microsoft Campus in April 2013. This is a great chance to make your voice heard.

One of the things I really like about Windows PowerShell 3.0 (in general—not necessarily in Windows 8) is that it is more discoverable than previous versions of Windows PowerShell. Now, don’t get me wrong. Even Windows PowerShell 1.0 was highly discoverable. In fact, the same three cmdlets you used then still work: Get-Help, Get-Command, and Get-Member. They are still the most basic cmdlets you will use. However, there is now a new one now. Show-Command is the name of the new cmdlet. You do not pipe a cmdlet to the Show-Command cmdlet. This generates an error (as illustrated here when I piped the Get-Process cmdlet to Show-Command).

Image of error message

To use the Show-Command cmdlet, you can specify the name of the cmdlet to Show-Command when calling it. This technique is shown here.

Show-Command -Name Get-Process

When you do this, the Show-Command window appears, and the Windows PowerShell console pauses until you close the Show-Command window or you specify parameters for the cmdlet. In the example shown here, I add a process name to the Show-Command window prior to pressing Run to run the command.

Image of menu

After the Run button is pressed, the Show-Command window closes, and the created Windows PowerShell command is written to the Windows PowerShell console. Then the command executes, and the results appear in the console. This is illustrated in the image shown here.

Image of command output

Another way to use the Show-Command cmdlet is to simply launch the Show-Command window. It details all the commands from all modules. To explore commands from a specific module, select it from the Modules drop-down list. This works even for custom modules. In the image shown here, I select my WMI module, and it displays all of the advanced functions that are contained in that module.

Image of menu

If I want to, I can choose one of the commands, and the dialog changes to display the parameters from the command. I can then run the command, or copy the command that gets created.

Keep in mind that I was demonstrating how to use this useful tool from within the Windows PowerShell console, but it also exists in the new and improved Windows PowerShell ISE.

That is about it for today, join me tomorrow for more Windows PowerShell cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Obtain User Input

$
0
0

Summary: Learn how to use Windows PowerShell to solicit user input.

 

Hey, Scripting Guy! QuestionHow can I solicit input from the user?

Hey, Scripting Guy! Answer Use the Read-Host cmdlet:

$in = Read-host “enter the data”

 

Weekend Scripter: Exploring New and Improved PowerShell 3.0 Cmdlets

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, goes spelunking for new and improved Windows PowerShell 3.0 cmdlets.

Microsoft Scripting Guy, Ed Wilson, is here. Today is officially the last day of my vacation. Tomorrow, early in the morning, I hop on a plane and head to Redmond, Washington for a week of meetings. This is not a bad thing because I will get to see many really cool people from the Windows PowerShell team. For a Scripting Guy, this will seem more like vacation than work. The only bad thing is that I get back right before Windows PowerShell Saturday in Charlotte.

Playing around with Get-Help to find new and improved cmdlets

I love playing around with Windows PowerShell 3.0. On weekends and when I am traveling, I open the Windows PowerShell console and begin to explore. I always return to the three most basic cmdlets when I am exploring. The three basic cmdlets I use are Get-Help, Get-Command, and Get-Member. A fourth one I always use is the Where-Object cmdlet.

Today, I decided to play around with Get-Help and see where Windows PowerShell 3.0 was specifically mentioned. I decided to do the search because I remembered seeing some cmdlets being mentioned as introduced in Windows PowerShell 3.0. Here is the command I used.

Get-Command -CommandType cmdlet | Foreach-Object { get-help $_ } |

select name, description | where description -match "powershell 3.0"

In this command (which is a single line command that I broke at the pipe character), I first use Get-Command to return only cmdlets. I pipe the returned cmdlet info objects to the Foreach-Object cmdlet and use Get-Help to obtain Help from the cmdlets. Next, I use the Select-Object cmdlet, and I choose the name and description where the description matches PowerShell 3.0.

The output was a bit difficult to read, so I decided to autosize the output and wrap the lines. To do this, I use the Format-Table cmdlet as shown here.

Get-Command -CommandType cmdlet | Foreach-Object { get-help $_ } |

select name, description | where description -match "powershell 3.0" | Format-Table -AutoSize -Wrap

Now that I have something I can read, I noticed that the Help uses the same types of language all the time when introducing a new Windows PowerShell 3.0 cmdlet or when announcing a modification to a previously existing cmdlet. Here is the text that introduces new functionality for an existing cmdlet.

Beginning in Windows PowerShell 3.0

Here is the text that introduces a new cmdlet.

This cmdlet is introduced in Windows PowerShell 3.0

Note   Today I am talking about exploring Windows PowerShell 3.0 via Get-Help and associated cmdlets. I am not writing a complete document that details all the changes in Windows PowerShell 3.0.

I then begin to explore. First, I look for modified cmdlets by using the command shown here (this command is a single command that I broke on the pipe characters for readability).

Get-Command -CommandType cmdlet | Foreach-Object { get-help $_ } |

select name, description |

where description -match "Beginning in Windows PowerShell 3.0" |

format-table -AutoSize –Wrap

The command and its associated output are shown here.

Image of command output

Next, I look for new cmdlets. Here is the command I used.

Get-Command -CommandType cmdlet | Foreach-Object { get-help $_ } |

select name, description |

where description -match "This cmdlet is introduced in Windows PowerShell 3.0" |

Format-Table -AutoSize –Wrap

The command and its associated output are shown in the image that follows.

Image of command output

Hopefully this will get you started playing around with Windows PowerShell 3.0 It comes installed on Windows 8 and Windows Server 2012. For more information about downloading it on Windows 7, Windows Server 2008, and Windows Server 2008 R2, see PowerShell 3.0 Is Now Available for Download!  

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Don’t Name a Variable $input

$
0
0

Summary: Advice against using $input for a variable name.

Hey, Scripting Guy! Question Can I use a variable named $input to hold input from the Read-Host cmdlet?

Hey, Scripting Guy! Answer $input is an automatic variable that is used for script blocks in the middle of a pipeline.

As such, it would be a very poor choice. 

Call the variable something like $userInput if you wish; but please do not call it $input

Weekend Scripter: PowerShell Saturday Sessions Revealed

$
0
0

Summary: Read sneak previews for Charlotte PowerShell Saturday sessions.

Microsoft Scripting Guy, Ed Wilson, is here. Today is just one week before Windows PowerShell Saturday #002 in Charlotte, NC.  I hope you have registered so you do not miss any of this exciting Windows PowerShell goodness. Today, three of our presenters will give you a sneak preview of their sessions. For the schedule details and registration, see the PowerShell Saturday #2 website.

First off, Jeremy Engel…

I will be presenting Better Scripting for a Brighter Tomorrow. This class is designed to expand your knowledge of scripting beyond simple batch sequences and bring you into the dynamic and adaptive world of Windows PowerShell functions and scripts. You will learn the secrets of my ancient month-old philosophy of advanced function development, known as The Fourfold Path. This path to scripting enlightenment flows through four distinct, and yet, interwoven stages.

The first stage, Acceptance, deals with understanding the myriad of ways in which data can be accepted by the function, known as parameters. We’ll explore the various attributes and qualifications that you can put on a given parameter to make your function easy to use. We will also review the CmdletBinding attributes and learn about when you’ll find these useful.

The second stage, Transformation, deals with using that most PowerShell-ish of traits: the pipeline. We’ll discuss how to use Begin, Process, and End to make your functions and scripts act and feel like native Windows PowerShell cmdlets. Along with pipelines, we’ll discuss how to effectively use parameter sets to make your functions more dynamic and intuitive.

The third stage, Balance, deals with displaying information to the user in the form of normal text, warnings, and errors, and when it is most appropriate to utilize them. Furthermore, we’ll delve into displaying progress for processes that take a long time to complete. Lastly, we’ll cover the use of the ShouldProcess and WhatIf concepts.

The fourth stage, Harmony, deals with ensuring that certain components of your function (such as its name, parameters, object-based output, and the Help info) adhere to Windows PowerShell standards. This goes a long way toward making your function as user-friendly as possible. It also allows it to be useable by others if they want to take the output and apply it to other functions or export it in some way.

Finally, if there’s time, we’ll touch on how to develop Windows PowerShell modules and their benefits for your future scripting endeavors.

Through this class, my hope is that you will learn techniques and practices that will move you further along the path to scripting enlightenment. And through your newfound scripting acumen, you will empower not only yourself, but others.

~Jeremy

Next up is Ashley McGlone…

As a Microsoft premier field engineer, I meet many customers and help them with their Active Directory and Windows PowerShell needs. I’ve taken some of that experience and wrapped it into a presentation called Active Directory PowerShell Notes From the Field, and I’ll be sharing it with the attendees at the upcoming Windows PowerShell Saturday.

I’ll cover these topics in the session:

  • Using Active Directory PowerShell to find schema update history
  • Using Windows PowerShell to migrate DNS zones
  • Using Active Directory PowerShell to remediate token size issues caused by SID history
  • A brief look at what’s new in Active Directory PowerShell 3.0

When I gave this presentation at TechReady in July, it was rated the #10 session out of 600+ sessions.

Here is a sneak peak at one slide where I demonstrate using my SIDHistory module to remove SID history from Active Directory accounts.

Twitter: @GoateePFE
TechNet blog: Goatee PFE

I hope to see you in Charlotte on September 15.

~Ashley 

And last, but by no means least, Mark Schill…

I have always used third-party editors for my daily scripting needs. With the release of Windows PowerShell 2.0, Microsoft introduced the Integrated Scripting Environment (ISE). It was a basic environment for creating and editing your Windows PowerShell code. It had extensibility which allowed for the community to enhance its functionality. But, it was still extremely underpowered compared to the many third-party editors that were available. It missed many features that I required to manage my scripts and modules. The Windows PowerShell ISE was not adequate enough for my needs—that is, until I launched the ISE in version three.

Windows PowerShell ISE version three includes many new features that, in my opinion, make it a serious competitor to those third-party editors I have been using for so long. A robust intellisense environment, code folding, and snippets are only a few enhancements in this version. The new enhancements with the extensible framework that was already present create an editor that seriously competes with the third-party editors on the market. Did I mention that it is completely free and already installed everywhere you need it?

Come check out my session at Windows PowerShell Saturday in Charlotte to see how you can turn the ISE into your very own supercharged scripting environment.

Blog: String Theory: Mastering the laws of physics with Windows PowerShell
 Active Directory SID history blog series
Email: Mark.Schill@cmschill.net

~Mark

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Two Quick Ways to Check Variables in PowerShell

$
0
0

Summary: Check for undeclared variables.

Hey, Scripting Guy! Question How can I cause the script to generate an error if a variable has not been declared?

Hey, Scripting Guy! Answer Here are a couple of ways to do this with Windows PowerShell.

a. Place set-psdebug –strict anywhere in the script. Any nondeclared variable will generate an error when accessed.

b. Use Set-StrictMode –Version latest

 


Increase PowerShell Command History to the Max (Almost)

$
0
0

Summary: In Windows PowerShell command history, you may run into the console history limit.

Microsoft Scripting Guy, Ed Wilson, is here. While I was in Cincinnati, Ohio for their first Windows PowerShell User Group meeting, I had a chance to meet a lot of my old friends. Later that week when I was teaching a Windows PowerShell workshop for a customer, I had a chance to meet other old friends. You might say that I was geeking out on seeing so many of my old friends—in fact, I was a bit worried that I would overflow my personal history buffer. Luckily, in Windows PowerShell 3.0, overflowing the history buffer is a bit difficult to do.

Playing around with Windows PowerShell 3.0 history settings

In Windows PowerShell 3.0 the MaximumHistoryCount is set to 4096. I find this value by using the Get-Variable cmdlet. This command is shown here.

PS C:\> Get-Variable -Name MaximumHistoryCount

Name                           Value

----                           -----

MaximumHistoryCount            4096

At 4096, it is unlikely that I will ever need to increase the storage space. In Windows PowerShell 1.0, it was set to 64, and I frequently was overwriting my command history. I generally do not keep the same Windows PowerShell console session open long enough to type 4096 commands—so I have never overwritten that history buffer. But what if I feel the need to increase my command history? What is the biggest value I can assign? One way to find out is to simply run a command and see what happens. Using one of my top ten favorite Windows PowerShell tricks, I use the range operator and begin assigning new values. Here is the command I use.

1..50000 | % {Set-Variable -Name MaximumHistoryCount -Value $_ }

What I am looking for is an error to raise that states I have exceeded the allowed value for the variable. This is exactly what happens, and I press CTRL-C to break the command and prevent further errors from appearing in the Windows PowerShell console. The command and the error that appears when the command runs are shown here.

Image of command output

A better approach to finding maximum values that are permitted for a variable involves using the Get-Variable cmdlet. In the following command, I return information about the MaximumHistoryCount variable by piping the output to the Format-List cmdlet.

PS C:\> Get-Variable MaximumHistoryCount | fl *

 

Name        : MaximumHistoryCount

Description : The maximum number of history objects to retain in a session.

Value       : 4096

Visibility  : Public

Module      :

ModuleName  :

Options     : None

Attributes  : {System.Management.Automation.ValidateRangeAttribute}

I see that the Attributes property contains an object. To investigate the Attributes property, I pipe the results of Get-Variable to the Select-Object cmdlet, and I use the ExpandProperty parameter. This technique is shown here.

PS C:\> Get-Variable MaximumHistoryCount | Select-Object -ExpandProperty attributes

 

                    MinRange                    MaxRange TypeId

                    --------                    -------- ------

1                                           32767 System.Management.Automa...

The MaxRange property tells me that the maximum allowed value for MaximumHistoryCount automatic variable is 32767. Interestingly enough, the error shown in the previous image occurs when I attempt to set the value to 32768, and I could assume that 32767 was the most that I could store. Now I know for certain.

Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Working with the Maximum History Setting

$
0
0

Summary: Learn how to increase the maximum history value.

 

Hey, Scripting Guy! Question How can I increase the number of commands that are stored in the Windows PowerShell command history?

Hey, Scripting Guy! Answer Specify a new value for the $MaximumHistoryCount automatic variable.

   In Windows PowerShell 3.0, the variable is set to 4096, but you can store up to 32767 history items
   in the variable if you need to do so. 

Bespoke Scripting? What Do You Want in PowerShell?

$
0
0

Summary: Let the Windows PowerShell team know what you would like to see in the next version.

Microsoft Scripting Guy, Ed Wilson, is here. This week is a complete geek fest for me. I am in Redmond at the Microsoft Corporation headquarters hanging out with the Windows PowerShell team. This morning I had coffee with one of the Windows PowerShell lead developers, Lee Holmes, and then I had lunch with Windows PowerShell PM, Travis Jones. Before all that, I had an early morning meeting with Joshy Joseph who is a principal program manager lead for the way cool Script Explorer. Later I get to meet with distinguished engineer, Jeffrey Snover, who was the lead architect for Windows PowerShell.

Yep. I love my job, but sometimes I REALLY REALLY REALLY love my job—and this week is one of them. But wait, as a late twentieth-century philosopher said, there is more. On Saturday, September 15, 2012, we will have  Windows PowerShell Saturday 002 in Charlotte, NC. There are still a few tickets left, but they really are going fast. Nearly 50 tickets sold over the weekend, so the remaining ones can go very quickly. Register now, before it is too late.

How to impact the next version of Windows PowerShell

Speaking of acting now before it is too late…

When I was talking with Lee Holmes and with Travis Jones, they told me that now is the time to give suggestions for the next version of Windows PowerShell. “But you just shipped Windows PowerShell 3.0,” you might say. Yep, and we immediately begin working on the next version. It is a long road to make a product as cool as Windows PowerShell even better.

This is where the community comes in to play. All Windows PowerShell MVPs basically understand this, but the general Windows PowerShell community might not. I know when I was an IT Pro, I did not get it at first. I would see the Beta of a product come out, and I would say, “I do not have time to mess with that.” Later I would see the Release Candidate come out, and I would say, “I will wait until it releases before I mess with it.” Then I would go to TechEd and complain about this feature not doing what I want it to do, or that feature not doing what I want it to do. It took me just once doing this before I figured out that I should be experimenting with the products I care about as soon as possible.

Right now, the Windows PowerShell team is looking at feature requests that did not make it into Windows PowerShell 3.0. They are also working with other teams and partners to see what features they would like to see in the product. They are busy talking to various customers and to MVPs, and everyone is providing feedback. This is also the time for you to do so. If you wait until the Release Candidate of a product (any product, not just Windows PowerShell), it is pretty much too late to provide meaningful feedback to the product group. They have been working on the product for a long time, and it is nearly feature complete, which means that they have added all the features and functionality they will be able to add. In the Release Candidate stage, the product group is fixing bugs and things like that. There may be time to get some small things into the product, but it will need to meet an extremely high bar to make it in.

During the Beta phase, there is still a bit of time to provide feedback; but even then, most of the features are already baked in. We are looking for bugs that may arise on various machines in different configurations, so we toss a relatively narrow net to capture as many different types of issues as possible.

Recently we have been releasing a Customer Technology Preview. This is pre-beta stuff, and it is designed to see if we are hitting the right balance between new features and improved functionality in the product. Here we are seeking a reality check—are we on target? It is possible that during this phase, new features could still be added to the product.

So all of this is to say NOW is the time to provide feedback to the Windows PowerShell team. They finished Windows PowerShell 3.0. You can download Windows PowerShell 3.0 now for Windows 7, Windows Server 2008 R2, or Windows Server 2008. Windows 8 and Windows Server 2012 have Windows PowerShell 3.0, and they are available via TechNet. Get it, try it out, and if you see something you would like to see in the next version of Windows PowerShell, file a bug on the Microsoft Connect website.

I am not making any promises. There is a good chance that your pet feature will not make it in. I mean, Lee Holmes is a very nice guy, but he did not seem too excited about my ideas for the Windows PowerShell ISE. Travis Jones is way cool, but he did not seem impressed by my idea either. But you know what? They listened. If you log a bug in Connect, someone will read it. They may not answer, but I do know that the bugs are read. And as a matter of a fact, numerous ideas from Connect bugs ended up in Windows PowerShell 3.0. The fact that the Windows PowerShell team listens is one of the major reasons it is such a cool product. Who knows, you might be able to one day demo something and say, “I submitted this as a bug in Connect; and as you can see, the Windows PowerShell team implemented my idea.” I mean, how cool is that?

Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Discovering PowerShell Functions

$
0
0

Summary: Learn how to discover Windows PowerShell 3.0 functions.

Hey, Scripting Guy! Question How can I find all of the functions that exist in my Windows PowerShell 3.0 installation?

Hey, Scripting Guy! Answer

a. Use the Function drive:

            Dir Function:

b. First import all of the modules, and then perform a directory listing of the function drive:

Get-Module -ListAvailable | Import-Module

Dir function:

c. Use the Get-Command cmdlet and search for the command type of function:

Get-Command  -CommandType function

The Scripting Guy Talks About PowerShell 3.0 Step by Step

$
0
0

Summary: The latest episode of TechNet Radio with the Scripting Guy just went live!

Microsoft Scripting Guy, Ed Wilson, is here. One of the good things I have to announce, is that I am continuing my podcast series with Microsoft IT Pro evangelist, Blain Barton. Blain and I have been doing monthly TechNet Radio IT Time shows for over a year. The latest installment just went live, and it is available for viewing on Channel 9. In this show, I talk about my forthcoming Windows PowerShell 3.0 Step by Step book. It is cool, so you may want to check it out.

Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Viewing all 3333 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>