Affichage des articles dont le libellé est tutos. Afficher tous les articles
Affichage des articles dont le libellé est tutos. Afficher tous les articles

lundi 10 octobre 2011

IPv6 tutorial

You still have no clue about IPv6? Read this and get convinced to start learning IPv6 now.

Part 1: Get started now!

You’ve probably heard the news that the Internet is in trouble. The last block of IP addresses has been assigned by the Regional Internet Registries. However, considering that NAT is an efficient mechanism to remedy the shortage of public IP addresses, we won’t really experience problems any time soon.
IPv6 Ready Logo

IPv4 address shortage

But this is only true for the developed countries. Developing countries, especially the emerging markets, are only at the beginning of building up their Internet infrastructure. For them, NAT probably is not really a solution because you need at least a certain number of public IP addresses to be able to communicate efficiently with the rest of the world. Hence, these countries probably will start introducing IPv6 quickly now.
This will also increase the pressure on those countries that already have a developed Internet infrastructure. Although there are ways that IPv4 and IPv6 networks can communicate, the fact that IPv6 introduces quite a few new features will cause problems when IPv6 traffic has to be transferred to IPv4-only networks.

IPv6 complexity

All of these problems are certainly solvable, but there is no doubt that the complexity of the Internet will increase rapidly now, and this won’t make life easier for system administrators. While network engineers will tell you that IPv6 will simplify networking, the truth is that it will only make things easier for computers but not for humans. It is not only that we will have to manage IPv4 AND IPv6 for quite some time, and that during the transition the interoperation of IPv4 and IPv6 will produce countless error messages in our networks, it is also because IPv6 is certainly more complex than IPv4. All of these new features come at a price. Many new organizations will need to hire new network administrators to manage these new complexities.

IPv6 for Windows admins

As a Windows administrator, you probably don’t have to know all the details of IPv6 as long as you are not responsible for your organization’s routers and firewalls. However, since networking issues are often the cause of Windows administration problems, you need at least a basic understanding of IPv6 and, from what I have seen so far, you will have to invest more time than you invested in learning IPv4.
I think now is a good time to start learning IPv6. This will probably be a long process because you also have to do your regular work. As to my experience, you can’t really learn such a technology by just reading some papers or books. You really have to play with IPv6 for some time until you get a feeling for which things you really need to know for your work. Hence, even if you most certainly won’t switch your productive network to IPv6 within the next months, it can’t be wrong to make the transition now in your test network.

In the next two posts of this IPv6 series, I will give an overview of the new features of IPv6.

Part 2: New features: Routing


 The new IPv6 features that are most often discussed are the new large address space, hierarchical addressing, and Quality of Service (QoS).

In the last post of my IPv6 series, I outlined the main reason why you should now get started with IPv6: IPv6 will come soon to your network whether you like it or not. Network engineers have a few other reasons to offer, and this is the topic of the next two articles. The new IPv6 features are not really new because the protocol has already existed for more than 10 years. For this reason, I won’t just repeat the feature descriptions, which you can read on countless other sites, but I will outline my view about the significance of these enhancements.
Cisco Router

Large address space

While the other new IPv6 features are all nice to have, the new large address space is certainly the main (perhaps the only) reason why IPv6 will come. An IPv4 address consists of 32 bits; the IPv4 address space, therefore, allows 232 addresses. An IPv6 address is four times as long and has 128 bits. Thus, in theory, IPv6 allows 2128 = 340,282,366,920,938,463,463,374,607,431,768,211,456 addresses. This corresponds to 655,570,793,348,866,943,898,599 (6.5×1023) addresses for every square meter of the Earth’s surface.
To be honest, I am not really impressed by these numbers. We are now entering the nano technology age, which means that we will have more and more, much smaller, communication devices than the IPv6 inventors have anticipated. Considering that a cubic meter of ideal gas contains around 1025 atoms, the number of 1023 IP addresses per square meter appears to be relatively small. I know this sounds like science fiction, but, for the inventors of IPv4, the Internet as we know it today certainly was science fiction at their time. We needed about 30 years to use up all of the IPv4 addresses. My gut tells me that the IPv6 addresses won’t last that long.

Hierarchical addressing

The Internet address classes of IPv4 allow hierarchical addressing to a certain extent. Hierarchical addressing makes routing more efficient because it reduces the size of routing tables. However, considering that the computation power of routers increased at a higher rate than the growth of the Internet, this was not really a problem.
Nevertheless, it is quite likely that the Internet will now grow at a higher rate than ever before, not only because the total population of the emerging markets (especially China and India) far exceeds the population in the developed world but also because the new type of devices (mobile phones, tablets, ebook readers, TV sets, etc.) also require IP addresses. Thus IPv6′s new hierarchical addressing capabilities are certainly important. And here the IPv6 inventors did not really scrimp. Of the 128 bits of an IPv6 address, 64 bits are used for hierarchical addressing, 48 bits for the public topology, and 16 bits for the site topology. The latter means that you can work with hierarchical addresses within your organization.

Better support for Quality of Service (QoS)

IPv4 has limited support for Quality of Service (QoS)—that is, real-time delivery of data through the Type of Service (TOS) field. One problem of QoS in IPv4 pertains to TCP and UDP port identification, which is not possible if the IPv4 packet is encrypted. The other problem is that QoS in IPv4 is not really standardized. The IPv6 header has the Flow Label field, which allows QoS handling that is independent of the payload.
While this new feature is technically interesting, in practice QoS is quite problematic for traffic on the public Internet. You might have heard of the stir that the alleged Google-Verizon deal caused. Google intended to pay Verizon to prioritize their traffic.
The main question is how you decide which traffic has priority. Is it justified that you have to wait for the latest 4sysops article to show up on your screen just because some teens clogged the net with their YouTube videos? And if you pay for QoS, how can you measure that your traffic really has a higher priority? One thing is for sure, if QoS really comes, then the complexity level of the Internet will be raised again by one or two bars, which means more work for IT pros.
In the next post I will talk about IPv6 IPsec and the IPv6 LAN features.



Part 3: New features: IPsec and LAN features

This article discusses the new IPv6 features of IPsec support, automatic address assignment, and the neighbor discovery function of the ICMPv6 protocol that will replace ARP.

In the last post of this series, I discussed the new IPv6 features Quality of Service (QoS), hierarchical addressing, and the new address space. In this post, I talk about some of the new IPv6 features that are most relevant for Windows admins.

Mandatory IPsec support

The IPv6 specification mandates support for IPsec (Internet Protocol security). IPv6 supporters often claim that this will improve overall security on the Internet. Since IPsec for IPv4 is optional, proprietary VPN solutions are ubiquitous. However, I believe, the main reason why IPsec deployments are rare is because configuration is relatively complicated. Thus, I doubt somehow that we will see significantly more IPsec deployments because of IPv6.
But what is most disappointing for me is that IPv6 doesn’t encrypt all kinds of IP traffic. While IPsec implementation is mandatory for IPv6, IPsec deployment is not. Besides, IPsec is essentially a solution for securing connections among sites; it is not a P2P encryption solution.
In my view, it is unbelievable that we are now introducing a new network protocol with a huge amount of effort but will still send data in clear text across the Internet. The inventors of IPv4 couldn’t foresee that secure data transmission would be an issue since their protocol was just intended to allow data transfers between educational institutions. No one really could imagine that the whole planet will use this form of communication in the future.
The IPv6 creators had the chance to correct this shortcoming of the Internet protocol and ensure that any kind of network traffic is encrypted by default. It is really a pity that they didn’t use this once-in-a-lifetime chance.

(Simplified) automatic address assignment

This is perhaps one of the features that will affect the work of Windows admins the most. Much of the documentation talks of “simplified” address assignment, but I somehow think this new feature will cause confusion among admins in the beginning. In an IPv4 network, a computer’s automatic address assignment means that a DHCP server is involved.
IPv6 still knows DHCP-based address assignment (also called stateful address configuration), but now hosts can also configure themselves with IPv6 addresses (stateless address configuration). There are two types of stateless configurations. Hosts can derive an IP address from a prefix (the first part of an IPv6 address that belongs to your organization) advertised by a local router, and they can assign themselves so-called link-local addresses (addresses that are not routed), which they can use to communicate with other nodes on the link (local network). Scary, isn’t it?

Neighbor discovery

The Internet Control Message Protocol for IPv6 (ICMPv6) will replace the Address Resolution Protocol (ARP). You probably know that ARP is used to determine the link layer address (MAC address in the case of Ethernet) from the IP address. The main problem of ARP is that it uses broadcasts, which disturbs all hosts on the link (LAN). By contrast, IPv6 uses Neighbor Solicitation multicast messages for neighbor discovery. Instead of sending a broadcast message to all nodes on the link, only the so-called solicited node multicast IPv6 address is contacted. The first 104 bits of the solicited node multicast are fixed (FF02::1:FF00:0/104), and the last 24 bits are equivalent to the last 24 bits of the IP address that has to be resolved. Since only nodes that share the last 24 bits in their IP address will listen to the solicited node address, fewer hosts are disturbed.

Extensibility

This is my favorite new IPv6 feature. While the IPv4 header only supports 40 bytes for options, the size of the IPv6 extensions is only constrained by the size of the IPv6 packet. IPv6 supports multiple so-called extensions headers that can be added after the IPv6 header. These extensions headers have no maximum size, which makes future enhancements of the protocol quite flexible. My hope is that this feature will be used for mandatory encryption of all IP packets.
Next, I will introduce the IPv6 address syntax.

Part 4: IPv6 address syntax

 In this article, you will learn the main concepts of the IPv6 address syntax: colon-hexadecimal representation, leading zero suppression, zero compression, and IPv6 prefix.

Now that you know about the new features of IPv6, it is time to have a closer look at the practical details. In this post, I will give a short summary about the IPv6 address syntax. It is essentially a condensed version of the corresponding part in Microsoft’s white paper “Introduction to IP Version 6.”

Colon-hexadecimal representation

An IPv6 address consists of 128 bits and is presented in eight 16-bit blocks. Each 16-bit block is converted to a four-digit hexadecimal number. Blocks are separated by colons.
Example: 2001:0DB8:0000:2F3B:02AA:00FF:FE28:9C5A

Leading zero suppression

Because IPv6 addresses are quite long, the leading zeroes within a 16-bit block can be removed, but each block must have at least a single digit.
Example: 2001:DB8:0:2F3B:2AA:FF:FE28:9C5A

Zero compression

A contiguous sequence of 16-bit blocks set to 0 can be replaced with the so-called double colon (::). Zero compression can only be applied once in an IP address. To determine how many blocks have been omitted, you just have to count the remaining blocks and subtract this number from 8.
Example: FE80:0:0:0:2AA:FF:FE9A:4CA2 can be zero compressed to FE80::2AA:FF:FE9A:4CA2.

IPv6 prefix

IPv6 prefixes are used to express IPv6 subnets, routes, and address ranges. The syntax of IPv6 prefixes looks like this: address/prefix-length. It is comparable to the Classless Inter-Domain Routing (CIDR) notation for IPv4 (for instance, 192.168.0.0/16 represents a Class B subnet): Subnet masks are no longer used in IPv6.
Example: 21DA:D3:0:2F3B::/64 represents a subnet of 264 addresses, where the first 64 bits are fixed and the last 64 bits are variable.
Admittedly, IPv6 addresses look somewhat complicated compared to the relatively simple IPv4 addresses. Rest assured that typos in IPv6 addresses will knock down quite a few systems once IPv6 starts replacing IPv4. But this is the price of the large address space. I guess, we will get used to it. In my next post, I will discuss the different types of IPv6 addresses. I promise that things won’t get easier. :-)

In the next post of this tutorial I will say some general words about the IPv6 address types and I will introduce the most address type, the global IPv6 unicast address.

Part 5: Address types and global unicast addresses

This part of the IPv6 tutorial discusses the three general IPv6 address types (unicast, multicast, anycast) and introduces the sub type global unicast address.

In my last post in the IPv6 series, you learned the IPv6 address syntax. Today, I will introduce the different types of IPv6 addresses.

IPv6 address types

There are three general types of IPv6 addresses: unicast, multicast, and anycast.

Unicast addresses

You know unicast addresses from IPv4. A unicast address is the most common form of an IP address and is assigned to one network interface.

Multicast addresses

Multicast addresses are also known in IPv4. These addresses identify multiple network interfaces / hosts. A typical use of multicast addresses in a Windows environment is the deployment of OS images to multiple hosts, simultaneously.

Anycast addresses

This is a new address type in IPv6. Like a multicast address, an anycast address identifies multiple interfaces; however, while multicast packets are accepted by multiple machines, anycast packets are delivered only to one interface (host). This address type allows for services that are provided by multiple servers where only one server has to respond. In routing, anycast addresses are used to route packets to the closest routers.
And what about broadcast addresses? They no longer exist in IPv6. Broadcasts are replaced by multicast messages. I will say something about this IPv6 technique in a later post.
IPv6 knows five different unicast address types: global unicast addresses, link-local addresses, site-local addresses, unique local IPv6 unicast addresses, and special addresses.

Global unicast addresses

A global unicast address is simply what we call a public IP address in IPv4—that is, an IP address that is routed across the whole Internet. You can make out a global unicast address easily: The first three bits are set to 001. Thus, the address prefix of a global IPv6 address is 2000::/3 because 0010000000000000 is 2000 in hex. However, in the future, the IANA (Internet Assigned Numbers Authority) might delegate currently unassigned portions of the IPv6 address space. Hence, 2000::/3 won’t always be the prefix for global unicast addresses.
IPv6 - tutorial - Global unicast address
(Note: The diagram is from Microsoft’s “Introduction to IP Version 6.”)
The next 45 bits are the so-called global routing prefix. This is the part that is assigned to organizations. The following 16 bits are for the subnet ID, which you can use for hierarchical addressing in your network. The last 64 bits indicate the interface ID, which is the part of the IPv6 address that must be unique within a subnet. You know what this means, right? You can have 65,536 (=216subnets), and each subnet can have 18446744073709551616 (=264) computers. I hope you have an efficient OS deployment tool. ;-)

In my next post, I will cover the site-local addresses and link-local address.

Part 6: Site-local addresses and link-local addresses

In this article, you will learn about the syntax of IPv6 site-local addresses and link-local addresses, which are so-called local-use, unicast addresses

In the last post of this IPv6 tutorial, you learned about the different address types and the new public IP addresses, the global unicast addresses. Today I will introduce the so-called local-use, unicast addresses, which are those IPv6 addresses that are not routed across the public Internet. There are two types of local-use, unicast addresses: site-local addresses and link-local addresses.

Site-local addresses

Site-local addresses are equivalent to private IP addresses in IPv4. The address space reserved for these addresses, which are only routed within an organization and not on the public Internet, is 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16. In IPv6, the first 10 bits of a site-local address are set to 1111111011, which is why these addresses always begin with FEC0. The following 54 bits are the subnet ID, which you can use in your organization for hierarchical routing, and the last 64 bits are the interface ID, which is the part that has to be unique on a link (local network on which hosts communicate without intervening routers). Thus, the prefix of a site-local address is FEC0::/10.
Note:  Site-local addresses have been deprecated, but existing implementations can still continue use them. Thus, they will probably stay around for a while. The proper way to work with private addresses in IPv6 is the use of unique local addresses which I will discuss in my next post.

Link-local addresses

From IPv4, you might know APIPA (Automatic Private IP Addressing) or AutoNet. Whenever automatic IP configuration through DHCP fails, Windows automatically assigns an autoconfiguration address in the range 169.254.0.1 to 169.254.255.254, which allows the computer to communicate with other machines on the link. In IPv6, link-local addresses always begin with 1111111010 (FE80).
Unlike site-local addresses, link-local addresses are never forwarded by routers and therefore can only be reached on the link. This is the reason why the next 54 bits are set to 0. The last 64 bits are set randomly by the operating system.
There is an important difference between IPv6 link-local addresses and IPv4 APIPA addresses. Once a PC receives an IPv4 address from a DHCP server, the APIPA address is no longer reachable. However, with IPv6, a network interface always has a link-local address even if you assign another IPv6 address manually or if the NIC receives an IPv6 address from a DHCP server. This means that computers on a link can always communicate through IPv6 using link-local addresses, which is not the case in IPv4 because APIPA addresses are not in the same subnet as private or public IPv4 addresses. Thus, if the local DHCP is unavailable, the computers can still access local services through IPv6 but won’t be able to reach the Internet or services in other links.
In the next post of this IPv6 tutorial, I will talk a little about the zone ID and unique local IPv6 unicast addresses.

Part 7: Zone ID and unique local IPv6 unicast  addresses

 The zone ID is used to distinguish ambiguous link-local and site-local addresses. Unique local IPv6 unicast addresses are another way to address the problem of ambiguous IPv6 addresses.

In the last post of this IPv6 tutorial, I introduced link-local and site-local IPv6 addresses. The problem with local-use unicast addresses is that they are not unique because they can be reused. Everything is fine as long as duplicate addresses are in networks of different organizations (sites). However, within in an organization, local-use addresses can also be assigned multiple times.

IPv6 zone ID

The purpose of zone IDs is to distinguish these addresses. For instance, if host A has two NICs that are connected to two different links (subnets), the same local-link address could have been used for NIC 1 on host A and on host B that is on the link of host A’s NIC 2. To distinguish this ambiguous link-local address, host A uses the interface index of NIC 1 as the zone ID for the local IP address.
For site-local addresses, the operating system uses the site ID (also called the scope ID). If a host is only connected to one site, this ID is always 1.
You can display the interface indexes on a host with the command “netsh interface ipv6 show address level=verbose”. If you launch the ipconfig command, you can see the local-link and site-local addresses with their zone IDs. The syntax for identifying the zone is address%zone_ID. This is an example of a link-local IP address with zone ID 11: fe80::bd0f:a8bc:6480:238b%11.
Note that the zone ID is only known at the local host that assigned it. I think in practice you will seldom be bothered with zone IDs as you don’t have to configure them manually.

Unique local IPv6 unicast address

Even with the use of zone IDs, you should probably avoid having ambiguous IP addresses in your network. Instead of site-local addresses, you can work with unique local IPv6 unicast addresses. These local-use addresses are also not routed across the Internet; however, like global IPv6 addresses, they are unique. Well, more or less, as you will soon see.
The prefix of unique local IPv6 unicast addresses is FC00::/7. The eighth bit is the Local flag and is set to 1 for local addresses. A Local flag with 0 has not yet been defined. Perhaps this could be a way to make local IPv6 addresses global? Anyway, until IPv6, creators have made up their mind, the prefix of unique local IPv6 unicast addresses is FD00::/8. Don’t worry if you don’t really understand this; all you really have to know about unique local IPv6 unicast addresses is this:
The next 40 bits are for the global ID and are randomly set. The following 16 bits are the subnet ID, which you can use for hierarchical addresses within your organization. As usual, the last 64 bits are the interface ID.
The trick with the random global ID is that it makes it somewhat unlikely for duplicate local addresses to occur on a site or even in the networks of two merging organizations. Actually, the probability that two organizations use the same global ID for their unique local IPv6 addresses is 1/240=9.1 10-13. Winning the Lotto jackpot is a few magnitudes more likely. However, what the IPv6 creators didn’t take into account is that Murphy’s Law rules in all networks. Hence, “relatively unique local IPv6 unicast addresses” would probably have been a better name. ;-)
In the next post in this IPv6 tutorial, I will discuss the special IPv6 addresses: unspecified address, IPv4-mapped address, 6to4 addresses, IPv6 multicast address, and solicited-node address.

Part 8: Special addresses

The special IPv6 addresses discussed in this part of the IPv6 tutorial are the unspecified address, the loopback address, IPv4-mapped addresses, 6to4 addresses, multicast addresses, and the

solicited-node address.


Last time, I talked about zone IDs and unique local IPv6 unicast addresses. Today, I will introduce some special addresses. In practice, usually only the networking guys really have to deal with these addresses. But as a Windows admin, you should have at least heard of the terms.

Unspecified address

The IPv6 unspecified address is specified as “0:0:0:0:0:0:0:0″ (or “::” if you have a sense for mathematical beauty). I think, this naming convention is somewhat funny. It reminds me of the “unspeakable word.” But there is also some sense in this because applications use the unspecified address as a variable for, well, an unspecified address. I guess, you won’t see this address often, just like you didn’t have many encounters with the unspecified IPv4 address 0.0.0.0. Note that you can’t assign this address to an interface, which also makes sense because then you would specify it, which is strictly forbidden. ;-)

Loopback address

The IPv6 loopback address is almost as beautiful as the unspecified address: ::1. The loopback address for IPv4 127.0.0.1 is comparably ugly and, like its predecessor, is assigned to every host interface and used by applications to communicate with local services via TCP/IP. Packets addressed to the loopback interface must never leave the host.

IPv4-mapped address

Like the loopback address, IPv4-mapped addresses are only used for internal representation on a host. They allow developers to use one API for both IPv4 and IPv6 calls. The syntax of IPv4-mapped addresses looks like this: :FFFF:w.x.y.z, where “w.x.y.z” is the IPv4 address that is represented in the IPv6 address.

6to4 addresses

6to4 is a tunneling technique that allows two IPv6 cable systems to communicate over an IPv4 network (usually the Internet). For this, at least one of the IPv6 systems needs an IPv4 address and a special IPv6 address, the so-called 6to4 address. A computer that has a 6to4 address is called “6to4 host.” This transition technology will mostly likely be used by computers in IPv4 networks to reach IPv6-only hosts. Essentially, the 6to4 address makes the 6to4 host appear on the “IPv6 landscape” even if it is not directly reachable through IPv6 by encapsulating IPv6 packets in IPv4 packets. The IPv4 packets are converted to IPv6 packets and vice versa by a 6to4 gateway. 6to4 addresses have the prefix 2002::/16. The next 32 bits are the IPv4 address of the 6to4 host converted into hex. Since a 6to4 address can only be created by using a unique public IPv4 address, the correspondingIPv6 address is also unique. The last 80 bits are for the local network and the host.

IPv6 multicast addresses

Like in IPv4, IPv6 multicast addresses are used to send the same data to multiple hosts simultaneously. Since multicast-capable software, such as OS imaging tools, typically do all the IP configuration, Windows admins usually are not bothered with the networking details. But if you ever stumble across an IPv6 address that begins with FF, you know what you are dealing with.

Solicited-node address

A special type of multicast address are the solicited-node addresses, which have the prefix FF02::1:FF00:0/104. Solicited-node addresses are used for neighbor discovery, which I already discussed in my article about the new IPv6 features. If a host needs to know the MAC address that belongs to a certain IP address, it won’t use an ARP broadcast like in IPv4. Instead, it would use multicast to contact only those hosts that listen to the solicited-node addresses where the last 24 bits are identical to the ones in the IP address that has to be resolved.


mercredi 28 septembre 2011

Use PowerShell and WMI to Get Processor Information

Summary: Learn how to get the number of processor cores via WMI and Windows PowerShell.
Hey, Scripting Guy! QuestionHey, Scripting Guy! I need to perform an audit of computers on our network. Specifically, I am tasked with obtaining CPU information. I need the processor speed, number of cores, and number of logical processors. I feel like I should be able to use Windows PowerShell to do this, but I am not certain. Can you help?
—RS

Hey, Scripting Guy! AnswerHello RS,
Microsoft Scripting Guy Ed Wilson here. This has been a rather crazy time. This week I am in Seattle, Washington, talking to customers about Windows PowerShell. Later in the week, I will be talking to Windows PowerShell writers on campus at our Microsoft Office in Redmond. I fly back to Charlotte, and then I head north to Canada for a couple of weeks. I really enjoy the opportunity to meet with people who are using Windows PowerShell to solve real world problems. It is cool.
RS, to find out information about the CPU, I use the Windows Management Instrumentation (WMI) class Win32_Processor. In Windows PowerShell, a single line of code that uses the Get-WmiObject cmdlet to do the heavy lifting is all that is required. The syntax of a command to query WMI and return CPU information is shown here:
Get-WmiObject Win32_Processor
And I can shorten that command by using the gwmi alias:
gwmi win32_Processor
In the following figure, I illustrate using the Get-WmiObject command and the default output from the command.
Image of using Get-WmiObject and default output
The Win32_Processor WMI class is documented on MSDN, and the article describes what all of the properties and coded values mean. But RS, for your requirements, I do not need that article. What I do need is a good way to select only the information you require. To do this, I am going to choose which properties I need. I then pipe the returned object to the Select-Object cmdlet. The reason for this is to remove the system properties that are automatically included with the returned WMI object. To avoid typing the properties twice (once for the Get-WmiObject cmdlet and once for the Select-Object cmdlet), I store the array of properties in the $property variable. The revised command is shown here:
$property = "systemname","maxclockspeed","addressWidth",
            "numberOfCores", "NumberOfLogicalProcessors"
Get-WmiObject -class win32_processor -Property  $property |
Select-Object -Property $property 
RS, you mentioned wanting to query computers on your network. The easy way to do this is to use the Active Directory cmdlets. I have an entire series of articles that talk about how to get the Active Directory cmdlets, and how to load and use them. You should refer to that series if you have questions about using Active Directory cmdlets.
RS, I wrote a script called GetAdComputersAndWMIinfo.ps1. The complete text of this script appears here.
GetAdComputersAndWMIinfo.ps1
Import-Module ActiveDirectory
$pingConfig = @{
    "count" = 1
    "bufferSize" = 15
    "delay" = 1
    "EA" = 0 }
$computer = $cn = $null
$cred = Get-Credential
 Get-ADComputer -filter * -Credential $cred |
 ForEach-Object {
                 if(Test-Connection -ComputerName $_.dnshostname @pingconfig)
                   { $computer += $_.dnshostname + "`r`n"} }
$computer = $computer -split "`r`n"
$property = "systemname","maxclockspeed","addressWidth",
            "numberOfCores", "NumberOfLogicalProcessors"
foreach($cn in $computer)
{
 if($cn -match $env:COMPUTERNAME)
   {
   Get-WmiObject -class win32_processor -Property  $property |
   Select-Object -Property $property }
 elseif($cn.Length -gt 0)
  {
   Get-WmiObject -class win32_processor -Property $property -cn $cn -cred $cred |
   Select-Object -Property $property } } 
The first thing to do is to import the ActiveDirectory module. In a script, I recommend using the complete name for the ActiveDirectory module, instead of using a wildcard character pattern such as *AD*. This is because there are many modules available for download from the Internet that would match the *AD* pattern. If this is the case, you cannot be certain you have actually loaded the ActiveDirectory module. To load the ActiveDirectory module, use the Import-Module cmdlet as shown here:
Import-Module ActiveDirectory
Next, I intend to use splatting to simplify using the Test-Connection cmdlet. I wrote an article about splatting last week. Splatting uses a hash table for the parameters and associated values. This hash table is shown here:
$pingConfig = @{
    "count" = 1
    "bufferSize" = 15
    "delay" = 1
    "EA" = 0 }
I then initialize a couple of variables. This helps when running the command multiple times inside the Windows PowerShell ISE. I also retrieve credentials via the Get-Credential cmdlet. These two commands are shown here:
$computer = $cn = $null
$cred = Get-Credential
Now, I use the Get-ADComputer cmdlet to retrieve a listing of computers from Active Directory Directory Services. I use the Foreach-Object cmdlet and pass the host names to the Test-Connection cmdlet to ensure the computer is online. I then create an array of computernames and store the names in the $computer variable. This is shown here:
Get-ADComputer -filter * -Credential $cred |
 ForEach-Object {
                 if(Test-Connection -ComputerName $_.dnshostname @pingconfig)
                   { $computer += $_.dnshostname + "`r`n"} }
The array that gets created is an array of single letters. I split the string based on the carriage return and line feed characters “`r`n” and create a new array that contains the name of each computer in an array element. This process leaves an element at the end of the array; this empty element will be dealt with later in the script. Here is the code that creates the new array of ComputerNames:
$computer = $computer -split "`r`n"
I now define an array of property names that are to be collected from WMI. This is a straightforward value assignment:
$property = "systemname","maxclockspeed","addressWidth",
            "numberOfCores", "NumberOfLogicalProcessors"
The online computers are stored in the $computer variable. I use the foreach statement to walk through the array of computer names. If the computer name matches the local computer name, I do not use credentials because WMI would cause the command to fail. In addition, I check to see if the computer name is greater than 0 in length. This takes care of the empty element at the end of the array. This portion of the code is shown here:
foreach($cn in $computer)
{
 if($cn -match $env:COMPUTERNAME)
   {
   Get-WmiObject -class win32_processor -Property  $property |
   Select-Object -Property $property }
 elseif($cn.Length -gt 0)
  {
   Get-WmiObject -class win32_processor -Property $property -cn $cn -cred $cred |
   Select-Object -Property $property } }
When the script runs, output similar to that shown in the following figure is displayed.
 Image of output when script runs
RS, that is all there is to using the Active Directory module to retrieve computer names, and to use WMI to query for the processor information.

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

Source : http://blogs.technet.com/b/heyscriptingguy/archive/2011/09/26/use-powershell-and-wmi-to-get-processor-information.aspx

Scripting : Your First Steps


By The Scripting Guys
A long time ago, even before any of the Scripting Guys were born, people used to walk from one place to another. Not for exercise or recreation, but because they had to get somewhere. Those who were fortunate enough to have other forms of transportation could move along a little more quickly on their horses, camels, elephants, or whatever the local pack animal happened to be. (And to those of you still using any of the preceding as your primary mode of transportation—we’ll be thinking of you the next time we’re stuck in traffic.)
Then this thing came along known as the horseless carriage. Many people laughed. They said things like “It’s just a fad,” “Why would I ever want one of those?” and even “That looks too dangerous.” Then there were the very few visionaries who said “Wow, cool, I want to try one of those.” These last people were the ones who recognized not only how much fun a car could be, but how it could someday save them hours, even days, of travel time in getting from place to place.
People today have experienced some of the same reactions to scripting as those people had to cars all those years ago. “Why would I want to script?”; “Scripting is just for those fanatics who don’t want to run their systems like everyone else does”; and even, “Scripts are dangerous.” But actually, you don’t need to be visionary or adventurous to try scripting, you just need to be the type of person who wants to save some time. (It’s still only the fanatics who think it’s fun though.) Scripts can not only make your work go faster, they can make your job easier. And once you learn the basic rules of the road, they’re not all that difficult to operate. (And there are very few traffic jams.)

Step 1

Code

C:\>cscript test.vbs
This is the very first thing you need to know to start using scripts to manage your Microsoft Windows systems. Well, okay, technically it’s the second thing you need to know. The first thing you need to know is how to find the Script Center, but since you’ve obviously done that we decided to leave out that step.
On the Script Center (and possibly elsewhere on the Internet, but we can’t vouch for anyone else), you’ll find a lot of pre-made, ready-to-go scripts. A script will look something like this:

Code

Wscript.echo "My very first script."

Yes, that one line is a script. It’s a very simple script, most are longer than this, but it’s still a script. Now you might be wondering what to do with that one line. It’s very simple:
  • Open Notepad.
  • Copy the script from your browser and paste it into Notepad.
  • Save the script with a .vbs extension, such as test.vbs.

Now just open a command window, navigate to the folder where you saved your file, and type this:

Code

cscript test.vbs

If you did this with the script above, you’ll have output that looks like this:

Code

My very first script.

Note: There are probably some of you out there saying “Hey, this didn’t work! What’s the deal?” Don’t worry, you’re not alone. A common misstep in following the instructions we just gave you has to do with the Save As functionality. If you select Save As in Notepad and type a filename in the File Name box, Notepad will helpfully append a .txt file extension to whatever name you give it. So if you type in test.vbs, you’ll end up with a file named test.vbs.txt. There are two easy ways to prevent this, it’s your choice as to which way is easiest for you:
  • Surround the filename with double quotes. Instead of typing test.vbs in the File Name box, type “test.vbs”.
  • Select All Files from the Save As Type list box before clicking Save.

Perform these same steps and you can run just about any script you’ll find in the Script Center. Have fun!

What is All This Scripting Stuff Anyway?

Oh, you want to know more? Okay, let’s step back a moment (yes, all the way back to step zero) and talk about what scripting is and why you might want to use scripts.
Scripting is just a way to automate getting information to and from your computer (and other computers). Our first script did this: we gave a sentence to the computer and got the same sentence back from the computer. This may not seem like an especially useful feature, but this was just a first step, and one step doesn’t even get you all the way across the room, let alone out the door. (Okay, one of the Scripting Guys did once live in an apartment where one step could get you across the room. But, for various reasons we won’t go into [something about ice and giant spiders], that apartment wasn’t much more useful than our first script.) There are a number of scenarios where scripts start to get really useful. Here are just a few:

  • You have to perform a series of system administration tasks on a regular basis
  • You have to perform a series of system administration tasks on several computers
  • You want to consolidate and organize the output you get from the computer
  • You want to run tasks when you’re not there to interact with the GUI
  • You need to ensure the exact same actions are repeated each time a task is run


If you think about some of the work you have to do as a system administrator, you might already be imagining tasks you want to script.

But This Stuff Looks Like Code

So maybe you’ve already been looking around the Script Center, possibly even read some of the daily Hey, Scripting Guy! articles, and you’ve seen scripts that look similar to this:

Visual Basic

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
   ("Select * from Win32_Process Where Name = 'Dfrgntfs.exe'")
If colProcesses.Count = 0 Then
   Wscript.Echo " Dfrgntfs.exe is not running."
Else
   Wscript.Echo " Dfrgntfs.exe is running."
End If

You might be thinking, “This scripting stuff looks pretty complicated.” Believe it or not, scripting isn’t just for professional computer programmers. There are much more powerful and complicated tools for programmers to use. Don’t get us wrong, a script can be powerful and complicated, but you can also write some fairly simple scripts that can be very helpful. So don’t let the thought of this stuff being “code” scare you off. There are a lot of things you can do pretty easily with no programming experience at all.
One of the advantages of scripting over other types of programming is that for scripting, everything you need is built into the operating system. We’ll briefly discuss some acronyms such as VBScript, WSH, and WMI a little ater, but we’ll tell you right now that all of those things are part of scripting, and they’re all built into Windows. You also don’t need fancy, expensive software to write a script. As you saw already, all you really need is Notepad, which, once again, is built-in.
In addition, scripting is specifically designed to help you administer your operating system. Even the most talented programmer would never attempt to create a full-blown software application, such as Word or Excel, using scripts. Scripts allow you to automate system administration tasks.
Keep in mind that the type of scripting we’re talking about here—and that we deal with almost exclusively on the Script Center—is system administration scripting. There are other types of scripting (such as web scripting), but you’ll have to learn about that somewhere else.
There are other scripting languages besides VBScript, and there are tools you can use to write scripts other than Notepad. But you can investigate all that on your own after you get a little scripting experience. Most of the scripts and examples on the Script Center use VBScript.
IMPORTANT: One last thing about system administration scripting, and it’s a really important thing to know. For most scripts to run, at least scripts that do anything very interesting, you must have local administrator rights to the machine the script is running against. Many of the scripts available on the Script Center will fail if you’re not running them as a local administrator.

Running Scripts

Enough of the background stuff, let’s get back to running some scripts. We already showed you how to run a script from the command line with Cscript. (If you got excited when you saw “Running Scripts” and came right here, you need to calm down, take a deep breath, and go back to the top and read Step 1.) You can also run scripts just by double-clicking on them from My Computer or Windows Explorer. The difference will be that the output from the script won’t be printed out nicely in the command window, instead it will pop up in a message box. Try this with the script we already created. Just double-click on the test.vbs file. You should see a message box that looks like this:
first.jpg
Well that was easy. Why didn’t we just do that in the first place? What do we need the command window for? Before we answer that, try this: Paste the following script into Notepad, save it with a .vbs extension, and double-click on the file.

Visual Basic

For i = 1 to 5
   Wscript.echo i
Next

What happened? You had to click OK in five different message boxes. Just imagine if your script were returning all the processes running on a computer, or all the computer names in a domain. You could be clicking for quite a while. Running your script with Cscript sends all this output straight to the command window, and you don’t have to deal with all those message boxes.
For more on running scripts, take a look at Running WSH Scripts in the Windows 2000 Scripting Guide.

What About Those Acronyms?

Because we said earlier we’d mention them, and the Scripting Guys never lie (well, maybe the occasional “Yes, your new haircut looks great”), here’s a very brief definition of some scripting-related technologies, along with the sections of the Windows 2000 Scripting Guide that explain them more fully:

-    VBScript – Visual Basic, Scripting Edition. A scripting language available by default with Microsoft Windows. See VBScript Primer.
-    WSH – Windows Script Host. The environment in which your scripts run. See WSH Primer.
-    WMI – Windows Management Instrumentation. A technology that provides you with the resources to manage Windows operating systems through scripting. See WMI Scripting Primer.
-    ADSI – Active Directory Service Interfaces. A technology that provides you with the resources to manage Active Directory and other directory services through scripting. See ADSI Scripting Primer.

Navigating the Script Center

The Script Center provides a number of resources to help you out as you begin scripting and as you become more skilled.
Learn to Script. The best place to start is on the Learn to Script page. Here you’ll find links to the Windows 2000 Scripting Guide (a full 1200 page book online), various articles, virtual labs, and on-demand webcasts. In the beginning you’ll probably find viewing the webcasts from Scripting Week 1 to be very helpful.
Script Repository. Another place you’ll probably find yourself spending a lot of time is the Script Center Script Repository. Here you’ll find thousands of scripts already created for you. Why spend a lot of time working on writing a new script when there might be one out there you can just copy for free? If you don’t see exactly what you’re looking for, you might find something close enough that you can make a simple modification to get what you need. (Keep in mind that the scripts on the Script Center typically don’t do any error checking, so once you get a little more comfortable and your scripts start to get more complex you’ll want to take a look at Error Handling in the Windows 2000 Scripting Guide.)
Scripting Tools. The Script Center also has links to numerous tools you can download—for free even—that will help you write scripts.
Scripting For…. If you’re trying to solve a problem in a specific area of system administration, such as Desktop Deployment or Windows Server 2003, take a look at the technology-specific areas of the Script Center.

You’re On Your Own…Mostly

We want to share one helpful tip with you before we send you out on your own: scripts are not case sensitive. There are one or two exceptions that we always point out to you, but for the most part mixing case in a script is purely for readability. So this script (which generates random numbers):

Visual Basic

intHighNumber = 100
intLowNumber = 1
For i = 1 to 5
   Randomize
   intNumber = Int((intHighNumber - intLowNumber + 1) * Rnd + intLowNumber)
   Wscript.Echo intNumber
Next

will run exactly the same as this script:

Visual Basic

inthighnumber = 100
intlownumber = 1
for i = 1 to 5
   randomize
   intnumber = int((inthighnumber - intlownumber + 1) * rnd + intlownumber)
   wscript.echo intnumber
Next

You should now be ready to head into the rest of the Script Center and get to work. If you really get stuck, you can email scripter@microsoft.com (in English, if possible) and we’ll try to see what we can do to help. Have fun, and good luck!

More Fun for Beginners

We hope you enjoyed this introduction to scripting, and more importantly that it was helpful to you. For more on beginning scripting, check out the Sesame Script series!

Tutos PowerShell (source 4sysops)

Part 1: cmdlets and pipeline

In part 1 of this PowerShell tutorial for Windows admins you will learn about the cmdlet and pipeline concepts.

Microsoft Windows PowerShell was conceived as the next-generation replacement for the old and reliable cmd.exe command shell environment. What’s especially cool about PowerShell is that it has a lot to offer both Windows systems administrators as well as .NET solution developers.
Trouble is, you have doubtless discovered that the PowerShell documentation, whether published by Microsoft or a third party, rarely differentiates between these two very different audiences. Therefore, administrators get confused and frustrated while trying to wade through PowerShell developer terminology, and .NET developers get befuddled and angry while trying to comprehend PowerShell administrator nomenclature.
To that end, I thought in this piece that I would attempt to help at least those in the systems administrator camp by explaining in plain English the primary PowerShell vocabulary terms. Let’s get started, shall we?

The cmdlet

The cmdlet (pronounced COMMAND-let) is the basic building block of Windows PowerShell. When you install PowerShell 2.0 on a Windows system, you receive by default the core library of PowerShell cmdlets. As you probably know, Microsoft has invested heavily in PowerShell technology. Therefore, most Microsoft server technologies ship with their own custom PowerShell modules. Examples of first-party extension modules include Active Directory, SQL Server 2008, SharePoint Server 2010 and Exchange Server 2010.
Regardless of their source, all cmdlets are designed (1) using a consistent usage rubric; and (2) to accomplish a single, specific task. Take a look at the following exhibit, and we’ll break down the constituent parts and pieces of a typical PowerShell command:
PowerShell Tutorial - cmdlet Components
The PowerShell cmdlet and its components
Cmdlets always consist of a verb-noun compound phrase separated by a hyphen; this is done by design in order to make remembering PowerShell commands easy and intuitive. In the previous example, Get-ChildItem, the Get (verb) part of the command directs the action; in this case, to retrieve data. The ChildItem (noun) part of the command provides the focus for the verb; in the example, to obtain a directory listing.
NOTE: Cmdlets are completely case IN-sensitive. Therefore, the statements get-childitem, Get-ChildItem, and GET-CHILDITEM are all equivalent in practice.
You will discover that PowerShell uses many of the same verbs regardless of the origin or context of a particular PowerShell cmdlet:
  • Get
  • Set
  • Add
  • Remove
  • Clear
  • Enable
  • Disable
  • Start
  • Restart
  • Resume
  • Stop
Please check out the nifty A-Z Index of Windows PowerShell 2.0 Commands for an alphabetical list of the built-in Windows PowerShell v2.0 cmdlet library.
Most PowerShell cmdlets support one or more parameters and arguments. A parameter represents additional data that is passed into a cmdlet to customize its operation. In PowerShell nomenclature, a named parameter is the parameter name followed by an argument. While most named parameters are prepended with a hyphen (-), not all are.
Moreover, not all cmdlets require an argument to accompany a parameter; these are called positional parameters because all that is required is the name of the cmdlet and the name of the parameter issued the proper order.
You can instruct PowerShell to list the full syntax of any available cmdlet by typing get-help cmdletname from the PowerShell prompt.
In case you haven’t picked this up from context, an argument is nothing more than a value that is passed to a parameter. In the current example, the Get-ChildItem cmdlet, which functions identically to the old DOS dir command, requires that you pass an argument (namely, the filespec for which you need a directory listing) to the cmdlet. In this case, -path is a positional parameter and can safely be omitted; thus, the statements Get-ChildItem –path C:\Tools and Get-ChildItem C:\Tools are synonymous.

The Pipeline

One of the most powerful aspects of Windows PowerShell (besides the fact that its command set has its roots in the all-pervasive .NET Framework, that is), is what is called the pipeline. Those of you who are already masters of *NIX shell scripting are already familiar with the pipeline, but for us Windows administrators, give a listen.
In PowerShell, piping refers to the process of passing the results of one cmdlet as an argument into a second cmdlet. Therefore, the pipeline enables us to create compound cmdlet sequences that perform multiple tasks in a single operation. Take a look at the following example:
PowerShell tutorial - pipeline
The PowerShell pipeline
In the previous example, we “chain” together three PowerShell cmdlets by using the pipe (|) character. The net result in this case is that we receive a nifty, formatted list of our Windows services, organized by their run status. Pretty cool, eh?

Conclusion

There is so much more to Windows PowerShell for us systems administrators that I have had space or time to devote to in this brief article. In the second installment of this two-part miniseries, Windows PowerShell Terminology for Administrators: Part 2 of 2, I will cover two additional basic PowerShell terms: Alias and PowerShell Drive.
If there are other PowerShell-related topics that on which you would like to see coverage here at 4sysops, then please leave your request in the comments. Thanks!

 

Part 2: Aliases and drives

Part 2 of the PowerShell tutorial for Windows admins introduces aliases and drives.

In the first part of this miniseries on Windows PowerShell terminology for administrators we briefly described what PowerShell is an introduced you to the cmdlet and the pipeline.
Let’s now continue our journey by learning two additional core terms that every PowerShell scripter should know.

Aliases

One of the things that I really love about Windows PowerShell is how much thought the Microsoft developers put into making the environment as user-friendly for existing Windows (and even *NIX) scripters as possible. To me, aliases represent the best example of this universality aspect of Windows PowerShell.
For instance, recall how earlier in this article I told you that the Get-ChildItem cmdlet is analogous in functionality to the Windows dir command? Well, as it happens, you can use dir all day long to retrieve directory listings in PowerShell. Are you a Mac or a NIX scripter? No problem—try using ls. It works!
In PowerShell, an alias is nothing more than a persistent mapping of a system- or user-defined shortcut to a known PowerShell cmdlet.
To obtain a full list of built-in aliases, simply invoke the cmdlet Get-Alias from your PowerShell environment.
PowerShell Tutorial - Aliases
Listing PowerShell aliases
Notice in the above exhibit that when you type cls to clear the screen, PowerShell actually invokes the Clear-Host cmdlet. You can define your own aliases as well by using the Set-Alias cmdlet. The kernel idea here is that over time you can develop a completely tricked-out, personalized scripting environment that is tuned to your intuitive workflow and command preferences.

Drives

As I previously mentioned, Windows PowerShell is built atop the .NET Framework. With PowerShell you can reach literally any aspect of local and/or remote computers, including the file system, the Registry, Windows Management Instrumentation (WMI) values, and the Active Directory Services Interface (ADSI).
According to Microsoft, a Windows PowerShell drive is a logical data store location that maps a logical name within PowerShell to a “real, live” data provider. Those data store locations can be:
  • Local or remote filesystems
  • Digital certificates
  • Environment variables
  • Registry keys and/or values
You can invoke the PowerShell cmdlet Get-PSDrive to obtain a list of currently loaded PowerShell drives on the local system. If you want to create a new PowerShell drive, then use the New-PSDrive cmdlet. The following exhibit demonstrates how we can define a virtual drive that maps to a remote file share.
PowerShell Tutorial - Drives
Figure 2: Defining a new PowerShell drive
In the preceding example, the alias remotedocs represents the \\srv1\documents remote file share. We can access the new PowerShell drive by using the command dir remotedocs.

Conclusion

At this point you should have a pretty good grasp of basic Windows PowerShell terminology. I will leave you with a laundry list of resources that I hope you will find helpful for further study in PowerShell. In the meantime, if there are other PowerShell-related topics that on which you would like to see coverage here at 4sysops, then please leave your request in the comments. Thanks! Next in this series you will learn how to run a PowerShell script.


For Further Study:

Part 3: Run a PowerShell script

In this article you will learn the basics of running PowerShell script files.

This is the third installment of a multi-part series on Windows PowerShell for Windows systems administrators. To get caught up on our subject matter, you might want to read the two previous articles about cmdlets and the pipeline and about aliases and drives.
Now, then—on with the show. While issuing ad-hoc PowerShell cmdlets from a PowerShell prompt is all well and good for occasional or on-demand use, you don’t truly begin to leverage the strengths of Windows PowerShell until you aggregate your code (which can include variables, branching, looping, error handling, etc.) into script files.
In a future installment we will begin to drill into practical examples of administering Windows using PowerShell. In this essay I will teach you the basics of creating and running PowerShell scripts from an overview perspective.

What is a PowerShell script?

A Windows PowerShell script file is nothing more than a plain text file that (a) has the .ps1 file extension; and (b) contains one or more lines of PowerShell source code.
Plaintext script file
Like VBScript, Python, and most other so-called “scripting languages,” your code is not compiled at run-time but is rather interpreted, line-by-line, by the PowerShell interpreter.
Therefore, you will get exactly nowhere unless and until you have PowerShell 2.0 installed on your target system. When you download PowerShell 2.0 (wonkily called the Windows Management Framework by Microsoft), you not only receive the PowerShell runtime environment, but you also receive the PowerShell Integrated Scripting Environment (ISE).
The ISE is a graphical interface (specifically a host application) for Windows PowerShell, and in my opinion should be your de facto scripting environment.
NOTE: In PowerShell nomenclature, a host application is a management tool that includes the Windows PowerShell runtime within its framework. For instance, the Microsoft Exchange Administrator console is a PowerShell host application, as are all third-party PowerShell ISEs.
The following exhibit shows the unique, three-paned interface of the PowerShell ISE:
Running a PowerShell script - The Windows PowerShell ISE
The Windows PowerShell ISE
The three viewing panes have the following purpose:
  • Script Pane: Enables you to edit your PowerShell scripts
  • Output Pane: Displays the output from your scripts
  • Command Pane: Enables you to issue PowerShell statements interactively
While we’re at it, in the name of completeness why don’t we briefly explain the function of the primary toolbar buttons as well:
Run.PowerShell.Script.The.PowerShell.ISE.toolbar
Figure 2: The PowerShell ISE toolbar
  • 1: New
  • 2: Open
  • 3: Save
  • 4: Cut
  • 5: Copy
  • 6: Paste
  • 7: Clear Output Pane
  • 8: Undo
  • 9: Redo
  • 10: Run Script
  • 11: Run Selection
  • 12: Stop Execution
  • 13: New Remote PowerShell Tab
  • 14: Start PowerShell.exe
  • 15: Show Script Pane Top
  • 16: Show Script Pane Right
  • 17: Show Script Pane Maximized

Creating a PowerShell script

Authoring a Windows PowerShell script is as easy as typing or pasting your code into the ISE script pane and then pressing the Run Script toolbar button. Be sure to save your file with the .ps1 extension; the PowerShell ISE takes care of that pesky little detail for you.
If you are a beginner to PowerShell scripting, then you will want to (1) purchase a great textbook or computer-based training course on the subject; and (2) make use of the wonderful Microsoft TechNet Script Repository.
In point of fact, the simple PowerShell script we use as an example in this article was borrowed from the TechNet Script Repository.

Running a PowerShell script

Before we learn how to run a PowerShell script from outside the ISE, we need to explain PowerShell execution policy, formally defined as Code Access Security.
By default, Windows PowerShell runs in the Restricted execution policy, which means that Windows PowerShell can be used only in interactive mode from a PowerShell prompt or from an ISE. This prohibition of PowerShell scripts from running “free” on a host system was done by design and obviously for security purposes.
The other three PowerShell execution policies are:
  • AllSigned: Only scripts that are digitally signed by a trusted publisher are allowed to run
  • RemoteSigned: Locally created scripts can run fine; downloaded scripts must be digitally signed by a trusted publisher in order to run
  • Unrestricted: All PowerShell scripts can run without restriction (not recommended for most environments)
To change the PowerShell script execution policy on a system, open an elevated command prompt, start PowerShell by typing powershell, and then invoke the Set-ExecutionPolicy cmdlet. To verify the current execution policy, run Get-ExecutionPolicy.
The following exhibit demonstrates how to both verify the current execution policy, as well as how to change the default execution policy to something a bit more reasonable in a development environment—RemoteSigned.
Run.PowerShell.Script.Setting.Windows.PowerShell.execution.policy
Setting Windows PowerShell execution policy
Now for the good stuff. To run a PowerShell script from an elevated command prompt, perform one of the following actions:
  • .\<script>.ps1 (You can use this form if your OS prompt is already focused in the local directory that contains the target PowerShell script file)
  • C:\Scripts\<script.ps1> (Here we specify the fully qualified filename of the target PowerShell script)
As long as Windows is properly configured to associate the .ps1 extension with Windows PowerShell, the inclusion of the file extension in your scripts is optional.
If, by contrast, you are already within PowerShell, you can employ the Invoke-Expression cmdlet to run the script. To wit:
PS> Invoke-Expression “C:\Scripts\<script>.ps1”
NOTE: The use of quotation marks is required only if your directory path includes spaces. Be aware, also, that by default you must always fully qualify the location of the script file even if your present working directory is the same location as the target script.
Finally, you can use the ampersand (&) shortcut to run a script from within PowerShell. That is to say:
PS>& “C:\Scripts\<script>.ps1”

Conclusion

At this point you know a thing or two about creating and running Windows PowerShell scripts. I will leave you with some helpful links to foster further learning. If there are other PowerShell-related topics on which you would like to see coverage here at 4Sysops, then please feel free to leave those requests in the comments portion of this post.

For Further Study:

Part 4: Obtaining server metadata

In this article you will learn how to leverage PowerShell to obtain system information in Windows Server 2008 and Windows desktop systems.

This is the fourth installment of a multi-part series on Windows PowerShell for Windows systems administrators. To get caught up on our subject matter, you might want to read the three previous article about cmdlets and pipeline, aliases and drives, and running scripts.
Now that we have a preliminary understanding of Windows PowerShell, it is time to turn our attention to practical application of the technology. To wit, in this blog post we will learn how to leverage PowerShell in order to ascertain metadata (that is to say, data about data) from a Windows Server 2008 computer. Of course, the same cmdlets apply for obtaining metadata from Windows client machines as well. Let’s get to work!

Preliminary Terminology

Before we begin, it is imperative that we have our terminology down pat. First, let’s define environment variables and WMI. According to Microsoft, an environment variable is “a string that contains information about the environment for the system, and the currently logged on user.”
In current Windows systems, the traditional ways to access environment variables are either through the System Control Panel item or the SET command-line program.
PowerShell tutorial Server metadata Environment variables
Accessing environment variables in Windows
Wikipedia defines Windows Management Instrumentation (WMI) as “a set of extensions to the Windows Driver Model that provides an operating system interface through which instrumented components provide information and notification.”
In Windows Server 2008, we use WMI not only to discover computer metadata, but we can also create employ WMI for local and remote system administration. In addition, we can define WMI filters in Group Policy to target Group Policy Objects (GPOs) based upon hardware and software-specific criteria.

Accessing Environment Variables in PowerShell

To begin with, fire up an administrative command prompt and type powershell to enter the PowerShell v2 environment. Next, issue the following command to return a list of all defined environment variables for the system:
PS>dir Env:
NOTE: You might recall that dir represents an alias for the Get-ChildItem cmdlet, and that Env: represents a PowerShell drive. See the earlier installments of this series for more information.
To query the value of an existing environment variable, use the following syntax:
PS>$Env:<variable_name>
Here is a nice list of examples to get you started:
  • $env:username (Displays the name of the currently logged-on user)
  • $env:userdomain (Displays the logon domain for the current user)
  • $env:computername (Displays the hostname of the local system)
  • $env:os (Displays the operating system kernel name)
  • $env:path (Displays the search path for executable files)
Some PowerShell cmdlets, specifically those that access and modify system information for local and remote systems, require authentication credentials.
We can define a PowerShell variable, for instance $cred1, and instantiate an instance of the Get-Credential cmdlet. That is:
PS>$cred = Get-Credential
PowerShell tutorial - Server metadata - Storing Credentials
Storing a credential in PowerShell
Do you see what’s going on here? The PowerShell script author is prompted for those credentials, which can then be used later on in an interactive session or PowerShell script file.
For greater flexibility, we can hard-code a credential:
PS>$cred2 = Get-Credential –credential corpdomain\admin
In this case, you are prompted for the password and PowerShell stores the password as an encrypted string, safe and secure. We can then call the password later in our PowerShell script or interactive session like so:
PS> $user2 = $cred2.username
$pw = $cred2.password
Now let’s link our understanding of stored credentials with the magic of WMI.
Obtaining System Information in PowerShell
If you have ever tried to use WMI before, you doubtless have found that the WMI Query Language (WQL) used to perform these actions is a bit obtuse. Okay, maybe more than a bit obtuse. Yes, WQL is a subset of the Structured Query Language (SQL) that we database administrators know and love, but the syntax is just so non-intuitive!
Regardless, let’s dive right in with some examples:
PS>Get-WMIObject –Class Win32_ComputerSystem
The above statement lists detailed information about one or more target computers. We can extend that statement big-time by adding additional computer names and attaching our previously defined credential:
PS>Get-WMIObject –Class Win32_ComputerSystem –ComputerName server01, server02, host144, host 255 –Credential $cred1
You can also use this same syntax, substituting only the specific WMI objects to be retrieved. To wit:
  • Win32_OperatingSystem (Detailed OS metadata)
  • Win32_UserAccount (Lists user accounts)
  • Win32_Group (Lists groups)
PowerShell tutorial - Enumerating Windows groups
Enumerating Windows groups with PowerShell

Conclusion

In a future installment of this series I will share with you some tools that will make your PowerShell WMI querying a much more painless process. In the meantime, please feel free to leave your questions, comments, and suggestions for new topics in the comments. Thanks for reading and take care!

For Further Study:


Part 5: Using PowerShell Scriptomatic

In this article you will learn how to use PowerShell Scriptomatic to perform WMI system administration by using Windows PowerShell.

This is the fifth installment of a multi-part series on Windows PowerShell for Windows systems administrators. To become current with our subject matter, I encourage you to read the four previous articles of this PowerShell tutorial.
As we discussed in a previous entry in this series, learning the syntax of the WMI Query Language (WQL) is tough enough without having the understand the WMI-related PowerShell cmdlets as well. In this essay I will introduce you to the nifty Microsoft PowerShell Scriptomatic utility. By the conclusion of this piece you will be integrating WMI and PowerShell with the best of ‘em!
Let’s get right to work.

Preliminary Terminology

As usual, we need to define our terms. By way of review, recall that Windows Management Instrumentation (WMI) is Microsoft’s implementation of Web-Based Enterprise Management (WBEM), which in turn uses the Common Information Model (CIM) standard to define access methods for computers, networks, applications, and so forth. Think of WMI and WBEM as the next generation of the Simple Network Management Protocol (SNMP).
In WMI, managed system information, including hardware and software-related data, is reported by using schemas. We employ the CIM schemas to access WMI classes, which in turn represent the specific data elements that we wish to query.
A WMI namespace is a subsection of the CIM repository. The most commonly used WMI namespace (and the one we will reference in this tutorial) is named root\CIMV2. The root\CIMV2 namespace ncludes an enormous number of Windows-related classes; lots of rich information in there!

Please see the following sources for a complete list of WMI namespaces and classes:
If you prefer the long way (that is, the manual way) around WMI systems administration, you can leverage the PowerShell Get-WMIObject cmdlet as well as your existing knowledge of WQL syntax to do your work. For instance, issue the following statement from a PowerShell prompt to return a list of all available WMI namespaces on the local system:
PS>Get-WMIObject –namespace “root” –query “SELECT * FROM __Namespace” | Select Name
PowerShell tutorial -  Listing WMI name spaces
Listing WMI namespaces from PowerShell
However, if you would prefer a bit of automation in your life with respect to WMI and PowerShell, then look no further than the PowerShell Scriptomatic tool. Read on, friends!

Introducing PoweShell Scriptomatic

Scriptomatic v2 is a GUI utility developed by the Microsoft Scripting Guys and has as its goal the easier creation of WMI scripts for system administration.
Scriptomatic 2.0
Scriptomatic 2.0
As you may or may not be able to tell from Figure 2, the use of Scriptomatic involves the following workflow:
  1. Select your desired WMI namespace and WMI class. The tool helpfully defaults to root\CIMV2.
  2. Choose appropriate scripting language and output format. Supported languages are VBScript, Perl, Jscript, and Python, and supported outputs are command prompt, plain text, HTML, Excel, and XML.
  3. Select the target computer(s) for the script
  4. Use the toolbar buttons to execute the script immediately, save the script to disk, etc.
Scriptomatic is a pretty awesome utility, isn’t it? However, unless you (a) are already proficient in VBScript or Jscript; or (b) already have the Perl and/or Python interpreters installed on your system, this tool is of limited use. After all, we are budding PowerShell scripters, correct?
Fortunately for us, the Microsoft Scripting Guys authored a PowerShell edition of Scriptomatic. You can’t beat the price, either: both Scriptomatic tools are free for your downloading pleasure!
Scriptomatic PowerShell edition
Scriptomatic PowerShell edition
Note that the workflow for the PowerShell edition of Scriptomatic is essentially identical to that of Scriptomatic V2:
  1. Select your desired WMI namespace and class
  2. Specify one or more target computers (comma-separated list; you can load this from an external file)
  3. Use the Control Pad buttons to specify output options
Scriptomatic PowerShell output
Scriptomatic PowerShell output
Check out the output in Figure 4; these expressions should look familiar to you if you’ve been keeping up on the content in this series. In this example we have variables and an invocation of the Get-WMIObject PowerShell cmdlet.
Following is a brief summary of the functionality of the Control Pad buttons:
  • Run: Executes the current code in a command prompt window
  • Save: Enables you to save your work as a .PS1 script file
  • Clear Script: Clears the work area
  • Refresh Script: Updates the active script to reflect any changes
  • Notepad: Opens your work in a new Notepad file
  • Open Temp File: Opens a blank file in Notepad
Hey, one more trick for you: Click the third toolbar button (for some inexplicable reason the Microsoft Scripting Guys have not differentiated these button icons!) and click Display Class Properties. Next, from the Control Pad, click Refresh Script. You now can drill into the granular data elements (aka properties) within the selected class. This procedure is shown in Figure 5:
Accessing class properties in Scriptomatic
Accessing class properties in Scriptomatic

Conclusion

Alrighty then! By now I think that you have a flying head start at using both WMI and PowerShell in your Windows systems administration work. I hope that you found this article helpful.
In the next installment of this series we will examine how to manage Windows Server 2008 roles and features by using PowerShell. Take care, and thanks for reading.

Part 6: Managing server roles and features

In this article you will learn how to manage Windows Server 2008 roles and features by using Windows PowerShell.

This is the sixth part of the Windows PowerShell series. PowerShell beginners should also read the previous parts.
In Windows Server 2008 a server role represents an installable unit of functionality that defines the primary function of a server. For instance, you may install Active Directory Domain Services (AD DS) to create a dedicated domain controller for your forest.
By contrast, Windows Server 2008 features are a bit more slippery to define. Like a server role, a feature is an installable unit of functionality. However, whereas a server role typically defines the chief duty of a server, a feature (at least according to Microsoft marketing literature) “provides auxiliary or supporting functions” within a system. Thus, a single server may be the holder of several features.
As you probably already know, you can manage server roles and features by using any of the following tools:
  • ServerManagerCmd.exe
  • Server Manager console
  • Windows PowerShell
You also may know that, as of Windows Server 2008 R2, the ServerManagerCmd.exe command-line tool is formally deprecated (read: does not work anymore); you are instead politely “encouraged” to use Windows PowerShell instead. In this article we will learn how to leverage the Windows PowerShell scripting and automation environment to install, administer, and remove server roles and features.

Installing Windows PowerShell 2.0

The first order of business is ensuring that your target Windows Server 2008 computers have Windows PowerShell 2.0 installed. If you are running Windows Server 2008 RTM, then you can use the ServerManagerCmd.exe utility to install Windows PowerShell:
OS>ServerManagerCmd –install PowerShell
If you run Windows Server 2008 R2, then you already have Windows PowerShell 2.0 installed. To verify your installed Windows PowerShell version, open an elevated command prompt, issue the command powershell to start a Windows PowerShell session, and then invoke the $Host.Version method. All of these commands are depicted in the following exhibit:
Verifying PowerShell
Verifying Windows PowerShell
NOTE: There is a world of difference between Windows PowerShell v1.0 and v2.0. Please ensure that you are running PowerShell v2.0, and be certain to run Windows Update to download the latest enhancements to the technology.

Installing a Role or Feature

As far as I am personally concerned, it is a blessing that Windows PowerShell does not try to split hairs and differentiate server roles and features. As you will see momentarily, all roles and features appear in a single master list.
From an administrative command prompt, fire up Windows PowerShell and issue the cmdlet Import-Module Servermanager to load the Server Manager PowerShell module.
Next, run the cmdlet Get-WindowsFeature to see a tree list of all available server roles and features. Any roles or features that are currently installed will appear with an X within the selection brackets. Pay particular attention to the role and feature short names in the Name column, as shown in the below screenshot; we will need those IDs to perform the next step.
Listing available server roles and features with PowerShell
Listing available server roles and features
NOTE: In Windows PowerShell nomenclature, a module is a self-contained, reusable library of related PowerShell functionality. Most Microsoft server technologies, such as SQL Server 2008, SharePoint Server 2010, and Exchange Server 2010, ship with their own custom modules to enable administrators to use PowerShell with those products.
We use the Add-WindowsFeature cmdlet to install both server roles and features. To leverage this cmdlet, we simply pass a comma-separated list of either display names (in quotes) or short names for the roles and/or features you wish to install.
PS>Add-WindowsFeature role, feature, etc.
See the following exhibit for an interface example in which we install the File Server, Domain Name System (DNS), and Dynamic Host Configuration Protocol (DHCP) server roles on a Windows Server 2008 R2 server.
Installing roles and features with PowerShell
Installing roles and features
To verify that the new server roles have been installed successfully, let’s fire up Server Manager and have a look at the Roles tree:
Verifying server role installation with PowerShell
Verifying server role installation
Ah, success!

Removing a Role or Feature

Removing Windows Server 2008 roles and features by using PowerShell is an equally simple procedure. To do this, we invoke the Remove-WindowsFeature cmdlet. You can throw in the optional –restart parameter to specify an automatic server restart if Windows needs to do so.
Removing server roles with PowerShell
Removing server roles
One word of warning: If you do elect to add the –restart parameter to your cmdlet, the server will restart (if necessary) with absolutely no timeout or other warning. It just goes!

Conclusion

At this point you should be able to manage Windows Server 2008 roles and features by using PowerShell. I will leave you with some related study resources if you are so inclined. I hope that you found this article helpful. Thanks!
For Further Study: