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

The Ins and Outs of Using DSQuery with Windows PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using DSQuery to return results for use in Windows PowerShell.

Hey, Scripting Guy! Question Hey, Scripting Guy!  I like using the DSQuery tool to search Active Directory Domain Services (AD DS). Can I use that tool with Windows PowerShell?

—WS

Hey, Scripting Guy! Answer Hello WS,

Microsoft Scripting Guy, Ed Wilson, is here. Yes, it is possible, but I think that there are problems with using the DSQuery tool from within Windows PowerShell. The problems come from the nature of the DSQuery tool itself, and not from within Windows PowerShell. If you are good at using DSQuery and DSGet, you might not have any problems, but personally, I think there are easier methods. I wrote a Hey, Scripting Guy! Blog called Query Active Directory Without Writing a Script; and in that blog, I discuss different methods of querying AD DS. You can refer to that blog for additional information about the tools.

The bad thing about DSQuery

The bad thing about it is not so much a limitation of DSQuery, as it is a limitation of all such command-line utilities. It returns strings; therefore, if the output is not exactly to my liking, I have to do string manipulation—and personally, I hate string manipulation. I have always hated string manipulation—from the VBScript days, and even back into the days of CPM. String manipulation simply is not “my thing.”

Another bad thing about DSQuery is that it is not installed by default, and the only way to get it on my laptop running Windows 8 is to download and to install the Remote Server Administration Tools (RSAT), which is yet to be released. A bad thing about the RSAT is that it is version specific, and even service pack specific. In Windows 7, I had to uninstall the RSAT, install Service Pack 1, then reinstall the RSAT. Of course, I did not find that out until after the service pack installation failed. So, I am always a little leery of installing extra stuff that I really do not need on my computers.

Of course, by using Windows PowerShell remoting, I do not need to install the RSAT on my computer only to use DSQuery. I can easily use the Invoke-Command cmdlet to perform the remote query on a server (by default all domain controllers will have DSQuery installed with their admin tools). I first store the credentials that I need in a variable I call $cred. I use the Get-Credential cmdlet to obtain the credential object. Next, I use the Invoke-Command cmdlet to specify the remote server from which to process the query, and I pass the credentials. I store the returned array of strings in the $computers variable, and I then display the strings. The commands are shown here.

$cred = get-credential iammred\administrator

$computers = invoke-command -cn dc3 {dsquery computer} -cred $cred

$computers

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

Image of command output

The strings are included in the output. To obtain only the computer name itself requires further processing. One way to get the computer name would be to use a regular expression and pick out the stuff following the first CN= that occurs before a comma. That would work, but I like regular expressions even less than I like string manipulation.

Therefore, I can turn the returned strings into ADSPath and supply that to the [adsi] type accelerator. To do that is not to horribly complicated. First, I need to get the output into a fashion I can pass to the [adsi] type accelerator. This is a two-step operation. First I replace the first CN= with LDAP://CN= and store the results back into a variable. This command is shown here.

$ads = $computers -replace '^"CN=', '"LDAP://CN='

For some reason, it does not seem to like the quotation marks when I pass it to [adsi], so I need to remove them. Here is the command that I use for that.

$ads = $ads | % {$_ -replace '"', ""}

Now, I can use ADSPath to create a DirectoryEntry object and retrieve the CN property (the basic computer name). This command is shown here.

$ads | Foreach-Object  {([adsi]$_).cn}

The nice thing about objects

The nice thing about objects is that they make it easy to access different parts of information. For example, when I use the [adsisearcher] type accelerator to find computers from inside AD DS, it returns a SearchResult object. This object contains a number of methods, but it also contains two properties. The first property is the Path property, which is a string. The second property, the Properties property contains an additional object. The output from the Get-Member cmdlet displays this information.

[dc3]: PS C:\> ([adsisearcher]"objectcategory=computer").findall() | get-member

 

   TypeName: System.DirectoryServices.SearchResult

 

Name              MemberType Definition

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

Equals            Method     bool Equals(System.Object obj)

GetDirectoryEntry Method     adsi GetDirectoryEntry()

GetHashCode       Method     int GetHashCode()

GetType           Method     type GetType()

ToString          Method     string ToString()

Path              Property   System.String Path {get;}

Properties        Property   System.DirectoryServices.ResultPropertyCollection Pr...

The cool thing about the Properties property is that it contains a collection of default properties and their associated values. The following command stores the Properties collection into a variable.

$a = ([adsisearcher]"objectcategory=computer").findall() | ForEach-Object {$_.properties}

To obtain only the computer names in Windows PowerShell 2.0, I can use the GetEnumerator method and then select only the CN property. In addition, I can create a custom object that contains only the properties I want. First, here is the code to select only the computer names.

$a.GetEnumerator() | select { $_.cn}

Note   I talked about using the GetEnumerator method when working with hash tables in a blog called Dealing with PowerShell Hash Table Quirks.

I can sort the information, and return a custom object. This command is shown here.

$a.GetEnumerator() | sort {$_.operatingsystem} | select {$_.cn, $_.operatingsystem}

Because I am working with Windows PowerShell objects, I can do anything I want to do to them. For example, I can sort and group the output as shown here.

PS C:\> $a.GetEnumerator() | sort {$_.operatingsystem} |

group {$_.operatingsystem} -NoElement | sort count

 

Count Name

----- ----

    1 OnTap

    1 Windows 7 Enterprise

    1 Windows 8 Consumer Pre...

    1 Windows 8 Pro N

    1 Windows 8 Release Preview

    1 Windows Server 2012 Da...

    1 Windows Server 2012 Re...

    1 Windows Vista™ Enterprise

    2 Windows 8 Enterprise E...

    2 Windows 8 Pro

    2 Windows Server 8 Beta ...

    3 Windows Server® 2008 E...

    8 Windows 7 Ultimate

   11 Windows Server 2008 R2...

WS, that is all there is to using DSQuery to search Active Directory Domain Services. 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: Formatting Numeric Output Using PowerShell

$
0
0

Summary: Learn how to format numeric output in Windows PowerShell by using format specifiers and numeric constants.

Hey, Scripting Guy! Question How can I print the amount of free space on a fixed disk in MB with two decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n2}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1MB)

Hey, Scripting Guy! Question What if I want to display the output in GB with three decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n3}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1GB)

Hey, Scripting Guy! Question I like big numbers. Can I display it in KB and have five decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n5}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1KB)

Hey, Scripting Guy! Question I want something simple. Can I print the amount of free space on a fixed disk in MB in whole numbers?

Hey, Scripting Guy! Answer No need for a format specifier, as shown here:

[int] ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1MB)


Use PowerShell to Query AD DS for Servers and then Find Hotfixes

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about querying the AD DS module via PowerShell and using the results to find hotfixes.

Hey, Scripting Guy! Question Hey, Scripting Guy!  We have a server running Windows Server 2008 R2 that is acting as one of our domain controllers. I do not have access to install the Remote Server Administration Tools (RSAT) on my workstation. However, I would like to use the Active Directory Domain Services (AD DS) cmdlets to return a listing of all servers on the network. I need to check the status of the most recent hotfix installed on all the servers. I do not have a list of servers because we are constantly adding and removing virtual servers based on load and demand, so Active Directory is the only place I feel comfortable in obtaining this information. Can you help?

—BB

Hey, Scripting Guy! Answer Hello BB,

Microsoft Scripting Guy, Ed Wilson, is here. There are over 100 people already signed up for PowerShell Saturday in Charlotte, North Carolina on September 15, 2012. The tickets are fast disappearing, so if you want to attend this event, you should register before the event sells completely out. By the way, there are several sessions that talk about using Windows PowerShell with Active Directory on the agenda. Microsoft PFE, Ashley McGlone will be making an excellent presentation for this track.

Use Windows PowerShell remoting to load the module

If you are using Windows PowerShell 2.0 and you have access to the Active Directory module, there are several ways to load and use the module. In a particular scenario where I only need a list of server names, it is easiest to use the Invoke-Command cmdlet and store the returned information in a variable. The command shown here accomplishes this task.

$cred = Get-Credential iammred\administrator

$servers = Invoke-Command -cn dc3 -cred $cred -script {import-module ActiveDirectory;

Get-ADComputer -LDAPFilter "(&(objectcategory=computer)(OperatingSystem=*server*))"}

To verify that the command worked properly and that I have an array of server names, I access the count property. This command is shown here.

$servers.Count

In Windows PowerShell 3.0, I can directly access the server names by using the name property as shown here.

$servers.name

But in Windows PowerShell 2.0, I need to use a ForEach-Object loop. This command is shown here.

$servers | foreach {$_.name}

The commands and the output associated with the commands are shown in the image that follows.

Image of command output

Use Invoke-Command to do the query

When I know that I have my list of servers, it is simple to query to find the latest hotfix. I can use the computer parameter of the Get-Hotfix cmdlet to do the query, but that presupposes that a large number of ports on the remote server are open, and that simply might not be the case. In Windows Server 2012, Windows PowerShell remoting is on by default, and if you are running Windows PowerShell in your environment, you should turn it on for your other servers (after the appropriate security review of course). I like using WinRM instead of RPC or DCOM on my network because WinRM uses only a single port, and the Enable-PSRemoting command makes it really easy to set up and configure.

Therefore, I use the Invoke-Command cmdlet to get the required hotfix information. In the command listed here, I use the Invoke-Command cmdlet, and I pass the collection of Server objects to the CN parameter. I use the Windows PowerShell 3.0 syntax and pick the name property directly from the array of objects. I pass my credential object to the credential parameter and the Get-HotFix cmdlet in the script block chooses the last hotfix from the collection. The ErrorAction gets set to 0, which means that errors do not halt operation, nor do they display. (See PowerTip: Specifying PowerShell Error Actions for more information about error actions.) The command is shown here.

Invoke-Command -cn $servers.name -cred $cred -script { get-hotfix | select -Last 1 } -ea 0

It is not necessary to create a new variable to store the server names if you are using Windows PowerShell 2.0. The syntax to pick out only the server name is usable in the ComputerName parameter of the Invoke-Command cmdlet. This technique is shown here.

Invoke-Command -cn ($servers | % {$_.name})  -cred $cred -script { get-hotfix | select -Last 1 } -ea 0

The commands and the associated output from the commands are shown in the image that follows.

Image of command output

BB, that is all there is to using Windows PowerShell to query Active Directory Domain Services when you do not have the RSAT installed on your workstation. 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: The Finer Points of Finessing an Array

$
0
0

Summary: Learn how to replace items in an array and how to sort an array.

Hey, Scripting Guy! QuestionI need to replace the “2” with “12” in the $array variable shown here:

$array = "1","2","3","4"

How can I do this?

 Hey, Scripting Guy! Answer

    1. $array=[regex]::replace($array,"2","12")
    2. $array = $array -replace "2","12"
    3. $array.SetValue("12",1)

Hey, Scripting Guy! QuestionI have an array defined in the $array variable shown here.

$array = 2,5,9,12,3,5

What is the easiest way to sort the array?

Hey, Scripting Guy! Answer 

1. Sort the array by using the sort static method from the [array] .NET Framework class.

[array]::sort($array)

2. Pipe the array to the Sort-Object cmdlet, and store the results back in the $array variable.

 $array = $array | sort

 

Use PowerShell to Query AD DS and Not Use LDAP Dialect

$
0
0

Summary: Learn how to use the Filter parameter and the Windows PowerShell Expression Language on the Active Directory module cmdlets.

Hey, Scripting Guy! Question Hey, Scripting Guy! I do not know why you like ADSI so much. The syntax is obscure, and it makes things hard to read. Yesterday’s blog that used Get-ADComputer could have been so much better if you had left out that stupid ADSI filter. What gives, Scripting Guy? You’re not turning developer on me are you?

—JJ

Hey, Scripting Guy! Answer Hello JJ,

Microsoft Scripting Guy, Ed Wilson, is here. No JJ, I am not turning developer on you, but Windows PowerShell is a great way to allow one to get in touch with their “inner developer.” I have been writing code for a very long time. Back when I bought my first computer (an Osborne), if I wanted a program to do something like balance a check book, I had to write it myself. It was a great way to learn programming (if somewhat error prone and slow). Since then, I have written everything from assembly (at the University) through C++. Truly and honestly though, Windows PowerShell is the most fun. Even though I can write code, I do not consider myself a developer. In my heart-of-hearts, I am an IT Pro and a hardware geek.

Reuse LDAP queries from other scripting languages

So what is the deal with using ADSI and LDAP? For one thing, it is standard. My early experience with messaging systems was all X.500 based, and from there, it is a short hop to LDAP. Familiarity with LDAP dialect permits one to easily use some of the many examples of LDAP dialect and ADO to query Active Directory on the Scripting Guys Script Repository. It is trivial to “steal” the LDAP query and plug it in to Get-ADComputer or Get-ADObject, regardless of the native language of the original script. As an example of this, consider the VBScript, Search for User Phone Numbers Beginning with 425, on the Scripting Guys Script repository. The essence of this 20 line script is shown here.

objCommand.CommandText = _

    "<LDAP://dc=fabrikam,dc=com>;(&(objectCategory=User)" & _

        "(telephoneNumber=425*));Name;Subtree"  

I take the filter portion of the script and I end up with the following LDAP filter.

"(&(objectCategory=User)(telephonenumber=425*))”

This filter is exactly what I need when I plug it in to the LDAPFilter parameter of the Get-ADUser cmdlet.  In fact, the hard part was already done when I found the LDAP dialect ADO query in the previous VBScript—not to mention the cool factor of taking a 20-line VBScript and shrinking it to a single Windows PowerShell line as shown here.

Get-ADUser -LDAPFilter "(&(objectCategory=User)(telephonenumber=425*))"

Query Active Directory without LDAP

One problem with using the filter parameter instead of an LDAP filter is having to learn a new filter syntax. (Of course, all the examples in Backus-Naur Form do not really help the average IT Pro much with this learning task). Another problem with using the filter parameter is that generally the syntax is more work than the corresponding LDAP filter. For example, the query to find users with phone numbers that begin with 425 is shown here.

Get-ADUser -Filter {(objectCategory -eq "User") -and (TelephoneNumber-like "425*")}

You can see that the syntax is similar to the LDAP filter, but it uses the Windows PowerShell operators instead of the LDAP operators. In addition, the quotation marks are required.

To rewrite the LDAP query that returns only servers, I would use the command shown here.

Get-ADComputer -Filter {(objectcategory -eq "computer") -AND (OperatingSystem -like '*server*')}

One thing to keep in mind is that the filter parameter does not support Regular Expressions in the filter. Therefore, I cannot use the following command because it generates an error.

Get-ADComputer -Filter {(objectcategory -eq "computer") -AND (OperatingSystem -match 'server')} -Properties operatingsystem

The command and the error message are shown here.

Image of command output

The following table lists the supported filter operators.

Operator

Meaning

Eq

equal

Le

Less than or equal

Ge

Greater than or equal

Ne

Not equal

Lt

Less than

Gt

Greater than

Approx.

Approximently

Bor

Boolean or

Band

Boolean and

Recursivematch

Recursive match

Like

Wild card like

Notlike

Wild card not like

And

And

Or

Or

Not

Not

JJ, that is all there is to using the filter parameter to query Active Directory and to not use LDAP dialect.  Join me tomorrow for more Windows PowerShell cool stuff. Until then, peace.

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.

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Adding a Default Exit to a PowerShell Switch

$
0
0

Summary: Learn how to add a default exit condition to a Windows PowerShell switch statement to control execution of commands.


Hey, Scripting Guy! QuestionI have the following switch statement, and I want to prevent the line Write-Host “switched” from executing? How can I do this?

$a = 3

switch ($a) {

 1 { "one detected" }

 2 { "two detected" }

}

Write-Host "switched"

Hey, Scripting Guy! Answer Add an exit statement to the default switch as shown here:

$a = 3

switch ($a) {

1 { "one detected" }

2 { "two detected"}

DEFAULT { exit}

}

Write-Host "switched 

Use PowerShell 3.0 to Easily Download 60 Spanned Files

$
0
0

Summary: Windows PowerShell MVP, Marco Shaw, talks about using a Windows PowerShell 3.0 cmdlet to download 60 virtual machine files from the Microsoft download site.

Microsoft Scripting Guy, Ed Wilson, is here. Today we have a guest blog from Windows PowerShell MVP, Marco Shaw. Take it away Marco…

I was pretty excited when I recently saw that Microsoft was releasing packaged evaluation VHDs of their latest System Center 2012 SP1 CTP2 release (SP1 will support Windows Server 2012). Here’s one example of where you can find the download links.

I thought that I could have the entire suite downloaded with about five clicks (App Controller, Operations Manager, Orchestrator, Service Manager, and Virtual Machine Manager). Much to my dismay, when I looked at the links, I found out that there wasn’t a single download available for each product. Instead, each product was roughly a dozen files—12 times 5 means 60 files to download.

Now, I like to pride myself in trying to automate things, and this was something I wanted to try to script. At that time, I figured I’d have to start with some complicated regular expressions, and I hate—OK, you caught me—I’m not good at them. So I decided that I’d get around to this later—or even better, maybe there’d be a one-click download added later.

I just started to look at getting the new MCSE Server Infrastructure certification, so I decided that it is time to face my demons and start building that regex. I was going to need that regex to do some parsing of the pages so I could pull out the URLs to the downloads. Or so I thought…

I had a prerelease version of Windows PowerShell 3.0 on my laptop, and I decided to roll up my sleeves. I couldn’t remember the cmdlet offhand; but eventually, I arrived at Invoke-WebRequest. So I passed off one of the URLs directly to the cmdlet as follows:

PS> invoke-webrequest “http://www.microsoft.com/downloads/details.aspx?FamilyID=4da3d1d9-91d4-472e-acb7-10885df9d1c2”

I took a quick peak at the output, because it wasn’t just raw HTML. What’s this?! A Links property! Could it be? The cmdlet already parsed out all of the links from the page for me?

A bit more Windows PowerShell magic:

PS> invoke-webrequest “http://www.microsoft.com/downloads/details.aspx?FamilyID=4da3d1d9-91d4-472e-acb7-10885df9d1c2”|select -exp links|where{$_.href -like "*.rar" -or $_.href -like "*.exe"}|select -exp href

Oh my, jackpot! I have string-based objects that give me the direct links to all of the downloads for App Controller. It was that easy.

PS> invoke-webrequest “http://www.microsoft.com/downloads/details.aspx?FamilyID=4da3d1d9-91d4-472e-acb7-10885df9d1c2”|select -exp links|where{$_.href -like "*.rar" -or $_.href -like "*.exe"}|select -exp href

All I needed to do with the last command is to invoke one of the Background Intelligent Transfer Service (BITS) cmdlets to download:

PS> invoke-webrequest “http://www.microsoft.com/downloads/details.aspx?FamilyID=4da3d1d9-91d4-472e-acb7-10885df9d1c2”|select -exp links|where{$_.href -like "*.rar" -or $_.href -like "*.exe"}|select -exp href|foreach{start-bitstransfer $_ C:\users\my_home}

That was it, and my download started. Oh, make sure you download to a drive that has enough free disk space.

Note   For some reason, the previous full code does not seem to work on Windows Server 2012 RC.

~Marco

Thank you, Marco, for an interesting Windows PowerShell command that should come in very useful for a lot of people.

Join me tomorrow when I will talk about the new release of the Script Explorer.

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 Alternate Credentials with WMI

$
0
0

Summary: Learn four  ways to supply alternate credentials with WMI and Windows PowerShell.

Hey, Scripting Guy! Question How can I supply alternate credentials for a remote WMI call when I am using the Get-WmiObject cmdlet?

Hey, Scripting Guy! Answer

a. Use the credential parameter as shown here.

Get-WmiObject Win32_BIOS -ComputerName Server01 -Credential (get-credential ` Domain01@User01)

b. Use the credential parameter as shown here.

$c = Get-Credential

Get-WmiObject Win32_DiskDrive -ComputerName Server01 -Credential $c

c. Create a CIM session to the remote system by using the New-CimSession.

d. Create a PS session to the remote system by using New-PSSession.


Weekend Scripter: RC Milestone for the PowerShell Script Explorer

$
0
0

Summary: Announcing the Windows PowerShell Script Explorer RC milestone. Download it today!

Microsoft Scripting Guy, Ed Wilson, is here. Today I have a major announcement to make:

Microsoft Script Explorer for Windows PowerShell is now officially a release candidate (RC). This release represents a significant step toward realizing our vision for a next-generation information experience that unites product, community, and guidance. This release would not have been possible without the great support across the Microsoft Server and Tools Business group and with our partner teams. This is a full release from Windows. Thank you! 

With this release, customers can:

  • Find Windows PowerShell scripts, snippets, and modules in the following locations:
    • Online repositories such as TechNet Script Center, PoshCode.org, and Bing.
    • Local and network file systems.
  • Browse community resources, such as TechNet Wiki.
  • Browse “How-to” guidance about Windows PowerShell from online resources such as TechNet and MSDN.
  • Save scripts, snippets, and module with metadata.
  • Integrate with Windows PowerShell ISE as an Add-on.
  • Install Window PowerShell as a Windows feature and get future fixes through Windows Update.

Microsoft Script Explorer is tested with Windows Server 2012 RTM, Windows 8 RTM, Windows Server 2008 with SP2, Windows Server 2008 R2 with SP1, Windows 7 with SP1, Windows Vista with SP2, Windows PowerShell 2.0, and Windows PowerShell 3.0.

Download: Microsoft Script Explorer for Windows PowerShell RC

Feedback: Please provide feedback on the Script Center Forums site.

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 when we will have a guest blog written by the Scripting Wife. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Use PowerShell to Simplify Working with Random Numbers

$
0
0

Summary: Learn about using Windows PowerShell to generate random numbers.

Hey, Scripting Guy! Question How can I generate a random number?

Hey, Scripting Guy! Answer 

a. Use the Get-Random cmdlet.

b. Use the System.Random .NET Framework class, and call the next() method:

([random]5).next()

Hey, Scripting Guy! Question How can I generate a random number between the values of 1 and 10?

 Hey, Scripting Guy! Answer

a. Use the System.Random .NET Framework class, and call the next() method:

([random]5).next(“1”,”10”)

b. Use the Get-Random cmdlet:

Get-Random -Maximum 10 -Minimum 1

Weekend Scripter: Starting a PowerShell Saturday

$
0
0

Summary: The Scripting Wife talks about starting a Windows PowerShell Saturday event where you live, what’s involved, and how to get help.

Microsoft Scripting Guy, Ed Wilson, is here. Today we have a special blog written by none other than the Scripting Wife. Take it away Teresa…

A member of the Windows PowerShell community recently asked me, “How do we get a Windows PowerShell Saturday in city XYZ?” This question was especially important because this particular city does not yet have a Windows PowerShell User Group, or even a Windows PowerShell MVP to help to start the user group. We love to help. There is one key to having a PowerShell Saturday, and that is a dedicated person who really wants to host the event in their town.

All the speakers are volunteers, and most will drive a couple hours or four to volunteer their time. So speakers are not an issue for you. What you need is someone, and that someone can be you, to head up the event. You need to decide how many people will realistically attend, find a venue to host the event, and then hit the pavement for sponsors.

For example, PowerShell Saturday 001 was in March in Columbus led by user group leader, Wes Stahler. There are two Microsoft PFEs in Columbus, and Ed and I rounded out the team. We used the Microsoft office in Columbus, which has a limit of 116 people. So we sold 100 tickets and used the other 16 spots for speakers and vendors. The PowerShell Saturday coming up in Charlotte is again in the Microsoft Office, but it is a lot larger building. Actually, there are two buildings with two sets of conference rooms, so we are able to handle 200 attendees.

When you know how many people you think will come and how many your venue will allow, you can approach speakers and sponsors. If you charge 10 dollars per person, you can pull the event off, but it will be a no frills event. (At least, this is true in the United States. We tend to follow what SQL Saturday charges to stay in line with the “community standard.”) The 10 bucks will feed your attendees, and provide drinks and snacks if you shop wisely.

Sponsors in today’s economic times usually offer giveaways more than cash. However, sometimes a sponsor will pay for lunch, which frees up your 10 dollars per person to buy some giveaways other than what the sponsors provide. Don’t forget to offer travel money to your speakers if they are coming from out of town. Even providing 25 dollars to speakers to assist with the cost of gasoline is especially appreciated. Some speakers are reimbursed by their employer for their travel to such events and some are not.

Some speakers are signed up through INETA, which sponsors user groups. You may be able to coordinate with one of the existing user groups in your area to help obtain speakers via INETA. If this is a possibility, check with the INETA website to find speakers in your vicinity who may volunteer, depending on the date and so on. In addition to Microsoft Windows PowerShell MVPs and Microsoft employees (such as premier field engineers), think about people who write blogs, assist with forums, speak at user groups, and others who are active in the community.

Ed and I will help all we can. But certainly, we cannot promise that he will come to speak—but we can discuss that (especially if you are going to host the event in Hawaii or somewhere in the Caribbean during the long winter months).

Do not be afraid to think outside of the box (or room in this case). If you expand your speaker pool to include remote speakers (via LYNC for example), you have access to the very best Windows PowerShell people in the world. One of the great things about the Windows PowerShell community is that we love to help, and we are passionate about our favorite technology.

I know I have rambled, but wanted to share all I could think of for now. Be sure to let me know if you need introductions to anyone. Just email scripter@microsoft.com and Ed will pass the email along to me.

~Scripting Wife

Thank you, Teresa, for that very useful summary about organizing a Windows PowerShell Saturday event.

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 Transcript of Commands in PowerShell

$
0
0

Summary: Learn how to create a transcript of all commands and associated output from within Windows PowerShell.

Hey, Scripting Guy! QuestionHow can I create an audit file of all commands typed during a Windows PowerShell session?

Hey, Scripting Guy! Answer Use the Start-Transcript command:

Start-transcript

Hey, Scripting Guy! Question But I tried to use Start-Transcript in the Windows PowerShell ISE and it did not work. I even tried this in Windows PowerShell 3.0, and still a no go. Am I doing something wrong?

Hey, Scripting Guy! Answer No you are not doing something wrong. The Windows PowerShell ISE does not support transcription. You can implement your own function to simulate transcription. An example appears in this Hey, Scripting Guy! Blog post, Create a Transcript of Commands from the Windows PowerShell ISE.

My Five Favorite PowerShell 3.0 Tips and Tricks

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shares his top five Windows PowerShell 3.0 tips and tricks.

Microsoft Scripting Guy, Ed Wilson, is here. Today marks a red letter day. No, we have not yet sold out Windows PowerShell Saturday in Charlotte, North Carolina (but we are really close). And no, the Scripting Wife and I have not sold our house and moved to Australia (although we would not really mind doing that). No, it is something more primeval, something more substantive, and frankly, something more exciting than either of the two previous possibilities…

I restart my radio series on TechNet Radio: IT Time with Microsoft IT Pro evangelist, Blain Barton. You can catch the earlier episodes via the Learn PowerShell page if you are so inclined. For our first session of the new fiscal year, we discussed my new Microsoft Press Windows PowerShell 3.0 Step by Step book a bit. In the next episode, we will talk about my favorite Windows PowerShell 3.0 tips and tricks. Don’t worry, todays blog will not necessarily spoil the plot because Blain is an absolutely top notch interviewer. In fact, I would place him right up there will the likes of Hal Rotenberg and Jonathan Medd. Yep, he is that good.

Way cool Windows PowerShell 3.0 stuff

Much of the way cool stuff that is written about Windows PowerShell 3.0 has to do with new cmdlets—especially all the new cmdlets in Windows 8 and in Windows Server 2012. These are the bells and whistles, but some of my favorite new things in Windows PowerShell 3.0 are the stuff that makes my life easier day in and day out. For example, how often, really, will I be typing Get-NetIpAddress or Set-NetConnectionProfile? On the other hand, how many times do I need to access a single property from each object in a collection? For me, I need the latter a whole lot more times.

So here are my top five Windows PowerShell 3.0 tricks. They are all language related, and I predict that they will also become your favorites.

My favorite Windows PowerShell trick is the automatic foreach

In Windows PowerShell 1.0 and Windows PowerShell 2.0, if you have a collection of objects, you must iterate through that collection, individually retrieve a desired property, and then possibly store it back in the variable for later use. It worked, and the behavior was similar to the behavior in other languages. In fact, this behavior still works in the Windows PowerShell 3.0 world today. Here is an example of using the Get-Process cmdlet where I store the collection of process objects in a variable named $process, and then pipe the resulting objects to the Foreach-Object cmdlet to retrieve the name property from the current object in the pipeline. I store these retrieved names in a $names variable.

$process = Get-Process

$Names = $process | foreach { $_.name }

$names

This command sequence is not that difficult, and it is one that the enterprise scripter will eventually type hundreds and hundreds of times over the course of a couple years. But in Windows PowerShell 3.0 this sequence is no longer required, and entire $process pipeline to the Foreach-Object command sequence is eliminated. Instead, Windows PowerShell 3.0 makes desired properties immediately available, and directly accessible. This revision of commands is shown here.

$process = Get-Process

$process.name

Although simply displaying process names may be somewhat illuminating, this sequence saves me tons of time when I am gathering the names of servers to use in further remoting scenarios. This sequence is shown here.

$servers = Get-ADComputer –Filter *

Get-HotFix –CN ($servers.name)

Where are squiggle brackets for Where-Object?

My second favorite feature in Windows PowerShell 3.0 is the streamlined Where-Object syntax for simple where clauses. In Windows PowerShell 1.0 and in Windows PowerShell 2.0, to use the Where-Object cmdlet to filter returned information required the use of script blocks, special variables, and understanding how pipelining worked. In short, this important task was fraught with stumbling blocks for the beginner Windows PowerShell scripter.

But you may say, “YOU are not a beginner Windows PowerShell scripter. So why is this syntax so popular with you?” I will tell you…

Of all the cmdlets I use, the Where-Object cmdlet consistently ranks in the top four cmdlets I always use. In fact, I can prove this statement because I wrote a script that parses cmdlets used in scripts. In the Weekend Scripter: Hey, Scripting Guy! Blog post Playing Around With the Windows PowerShell Tokenizer, I include a script that I use to parse my scripts to reveal which cmdlets I use the most. When you have run the script against your script directory, use the following command to process the contents.

Get-Content $logpath | sort | group -NoElement | sort count

The long way of using the Where-Object is shown here.

Get-Process | where { $_.name -match 'word' }

Here is the short way of using the Where-Object.

Get-Process | where name -match 'word'

Not only is it less typing, but it is also easier to read.

Using local variables in remote sessions

With Windows PowerShell remoting gaining in popularity and importance, ease-of-use becomes vital. If I created a local variable in Windows PowerShell 2.0, and I needed to use it in a remote session, I had to write a bit of code to accomplish this feat, and I had to pass the local variable as an argument and as a parameter in the remote session. Sound confusing? Well, it wasn’t after the first 100 times doing it. By that time, it was just annoying. Here is what I am talking about (icm is an alias for the Invoke-Command cmdlet).

$class = "win32_bios"

icm -cn dc3 {param($class) gwmi -class $class} -ArgumentList $class

In Windows PowerShell 3.0, this process is much more straightforward and easier to understand. Here is the Windows PowerShell 3.0 syntax that is so sweet it checks in at number 3 on the Scripting Guy’s top five tricks list.

$class = "win32_bios"

icm -cn dc3 {gwmi -class $using:class}

Flexible script formatting

Because it seems that I am constantly writing a blog or a book, or teaching a class, I am always confronted with a narrow screen or a large font that takes up lots of screen real estate. Typically, I work with a maximum of 82 – 85 characters of width. This is a problem with a verbose easy-to-read language. Couple this with the fact that many of my readers or my audience is just learning Windows PowerShell, and I have a real problem. I have learned to despise line continuation because of the unnecessary errors that it potentially introduces. In Windows PowerShell 2.0 or Windows PowerShell 1.0, my basic choices were lots of variables, breaking at the pipeline character, or line continuation. In Windows PowerShell 3.0, flexible formatting enters the picture. This means that I can use a syntax such as the one shown here.

(get-process).

    name.

    gettype()

This feature is so cool that it deserves a picture. Seeing is believing with flexible formatting. OK, maybe it is just me, but it is good enough for number 4 in my top 5 Windows PowerShell 3.0 tricks.

Image of command output

Variable validation attributes

Windows PowerShell 2.0 had parameter validation attributes, but if I wanted to ensure that a variable value met specific requirements (other than parameters), I needed to write code to verify those requirements, or I needed to be ready to catch an error. In Windows PowerShell 3.0, the introduction of variable validation attributes can vastly simplify this error checking requirement to a single command. For people who write a lot of scripts (such as myself), this is a huge win. Here is an example of setting a validation attribute where the value of $c must be within the range of 1 to 5.

[ValidateRange(1,5)][int]$c = 1

When I run the command and exceed the permissible range, an error message appears. The following command runs 10 times and sets a random number between 1 and 8 to the value of $c.

1..10 | % {$c = Get-Random -Minimum 1 -Maximum 8 ; $c}

The command and the error are shown in the image that follows.

Image of command output

Come back tomorrow when I will talk about 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: Using Credentials in PowerShell

$
0
0

Summary: Learn how to find Windows PowerShell cmdlets and providers that support credentials.

Hey, Scripting Guy! Question How can I find which Windows PowerShell cmdlets support the credential parameter?

Hey, Scripting Guy! Answer Use the Get-Command cmdlet with a command such as:

Get-Command -ParameterName credential

Hey, Scripting Guy! Question How can I find which Windows PowerShell providers support credentials?

Hey, Scripting Guy! Answer Use the Get-PSProvider cmdlet and pipe the results to Where-Object. Then look for credential in the capabilities property. An example for doing this in Windows PowerShell 3.0 is shown here.

Get-PSProvider | where -Property capabilities -Value credential -Match

Use PowerShell to Check the License Status of Windows 8

$
0
0

Summary: Use Windows PowerShell and WMI to determine the number of days remaining on an evaluation copy of Windows 8.

Microsoft Scripting Guy, Ed Wilson, is here. One of the cool features in Windows 8 is that it has Hyper-V built-in to it. This means that I can use the cool new Hyper-V cmdlets to manage things. For example, I can type the following command to start all of my virtual machines:

Get-VM | Start-VM

When I am finished making my presentation, I can use the following command to shut down all of the virtual machines.

Get-VM | Stop-VM

All this is pretty cool, until I get ready to make a presentation, and all of my virtual machines are whining that they need to activate or they will shut down. Not the best situation if you are preparing to make a presentation at something like TechEd or Tech Mentor. One way to ensure that this situation does not occur is to use the following script.

Get-WindowsLicensingStatus.ps1

$cim = New-CimSession -ComputerName (get-vm).name -Credential nwtraders\administrator

get-ciminstance -class SoftwareLicensingProduct -CimSession $cim |

  where {$_.name -match 'windows' -AND $_.licensefamily} |

    format-list -property Name, Description, `

             @{Label="Grace period (days)"; Expression={ $_.graceperiodremaining / 1440}}, `

             @{Label= "License Status"; Expression={switch (foreach {$_.LicenseStatus}) `

              { 0 {"Unlicensed"} `

                1 {"Licensed"} `

                2 {"Out-Of-Box Grace Period"} `

                3 {"Out-Of-Tolerance Grace Period"} `

                4 {"Non-Genuine Grace Period"} `

              } } }

The first thing I do is create a CIM session to connect to all of my virtual machines. I use the cool automatic foreach technique that I talked about yesterday in My Five Favorite PowerShell 3.0 Tips and Tricks. Now, I use the Get-CimInstance cmdlet to perform a WMI query on each of the servers and clients that are running on my virtual machine.

Note   I could have used the Get-VM | Start-VM commands that I mentioned at the beginning of this blog post to start the virtual machines and to check their status.

I filter out the software products by names that match Windows and only those elements that have a LicenseFamily. Then I pipe the results to the Format-List cmdlet to produce a nice output. Keep in mind, if I am running this against a larger network, I might want to export the information to a CSV file so I can easily sort the results in Microsoft Excel.

The command itself uses a couple of custom labels: the GracePeriodRemaining property reports in minutes; therefore, to have a more meaningful result, I divide by 1440. The LicenseStatus property reports as an enumeration, so I use a switch statement to create a more easily readable report. Certain builds report multiple items. As shown in the image that follows, the server reports multiple items, all of which say there are no remaining grace days and no licensing status.

Image of command output

When I run the script (modified slightly) against my local computer, however, it reports exactly how much grace time I have, and the license status.

Image of command output

This WMI class also reports on things like Office status. Therefore, if you are running the beta version of Office 15 (like I am doing), that product also reports—all I need to do is change my Where-Object. This results in the command shown here.

get-ciminstance -class SoftwareLicensingProduct |

  where {$_.name -match 'office' -AND $_.licensefamily}

The output of the command is shown in the following image.

Image of command output

That is about all there is to examining licensing activation status for Windows 8 or for Windows Server 2012. 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: Create a Record of Your PowerShell Commands

$
0
0

Summary: Use Start-Transcript to create a record of Windows PowerShell commands.

Hey, Scripting Guy! QuestionHow can I create an audit file of all commands that I typed during a Windows PowerShell session? 

Hey, Scripting Guy! AnswerUse the Start-Transcript command:

Start-transcript

Hey, Scripting Guy! QuestionHow can I provide a custom name and location for my Windows PowerShell transcript? 

Hey, Scripting Guy! AnswerUse the Start-Transcript command with the Path parameter:

Start-transcript -Path c:\fso\mytranscript.txt

Hey, Scripting Guy! QuestionHow can I stop a transcript after I have started it?

Hey, Scripting Guy! AnswerUse the Stop-Transcript command:

Stop-transcript

 

Use PowerShell to Identify Port Connections in Windows 8

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell to identify port connections in Windows 8.

 Microsoft Scripting Guy, Ed Wilson, is here. There are only twenty-three days until Windows PowerShell Saturday in Charlotte, North Carolina. In fact, as far as I know, we have even had our last organizational meeting. The Scripting Wife has been busy finding water and soda on sale at various stores (shopping is one of her core skills), and the rest of the team has been busy working on sponsor layout drawings, presentations, and so on.

The Scripting Wife and I are heading to northern Kentucky where I will be teaching a Windows PowerShell class to a customer there. Teresa will be out and about visiting friends and going to outlet malls and finding cool places to eat. My good friend (and fellow Microsoftee), Robert from California, is flying in for the class, so we are looking forward to seeing him again. The Scripting Wife and I will be attending the first ever Cincinnati, Ohio Windows PowerShell User Group while we are in the area. I will be speaking about using Windows PowerShell 3.0 to manage a remote Windows 8 workstation. It’s a cool presentation if I do say so myself.

Identifying port connections

This is the third time I have written a script to obtain information about network connections. The first time I wrote it, I used a WMI class from the root/snmp namespace, and I wrote the script in VBScript. The second time, I used the NetStat command-line utility tool, I wrote it in Windows PowerShell 1.0, and I parsed the output by using regular expressions. In Windows PowerShell 3.0 in Windows 8, I use a simple cmdlet. This is a good thing, because gaining access to the SNMP namespace requires installing SNMP, and that requires evaluation and planning. I like things that are in the box as much as possible.

Using NetStat is easy (as long as you remember that it is netstat and not net statistics, and you remember what the switch –a –n –o accomplishes). The problem with netstat (it is not case sensitive) is that it returns string data instead of objects. Thus, the requirement for a bit of regular expression work. (I am not good enough with regular expressions to type very complicated patterns on the fly in front of a live audience without a lot of prior work—for example, say at Tech Mentor.)

As long as I do not need to do any post processing, and as long as I can remember the netstat –ano command (yes, you can gang the switches for netstat), there is no problem with the command. The output is shown here.

Image of command output

Using the Get-NetTCPConnection cmdlet

The default view of the Get-NetTCPConnection cmdlet is pretty useful, and it displays a decent amount of information about local and remote ports. For me, the display does not scale properly in my default Windows PowerShell size, but that is due to my need to take screenshots. On a larger monitor, using the default sizing for Windows PowerShell, the output is just fine. The image that follows illustrates the default output.

Image of command output

The nice thing about using the Get-NetTCPConnection cmdlet is that it returns objects, and it also has a number of useful switches. For example, if I am interested in only established connections, I use the state parameter, and I tell it to show established connections. The command is shown here.

Get-NetTCPConnection -State established

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

Image of command output

To view connections to the Internet, use the AppliedSetting parameter as shown here.

Get-NetTCPConnection -AppliedSetting internet

But keep in mind these are objects, and you can parse the information via Windows PowerShell. For example, I can quickly see the state of the connections on my computer by grouping by state. This command is shown here.

PS C:\> Get-NetTCPConnection | group state -NoElement

 

Count Name

----- ----

   21 Listen

    2 Established

I might be curious and want to see what ports are being utilized. I can easily see this by grouping by LocalPort as shown here.

PS C:\> Get-NetTCPConnection | group localport -NoElement | sort count -Descending

 

Count Name

----- ----

    2 49199

    2 49177

    2 49155

    2 49154

    2 49153

    2 49152

    2 2179

    2 135

    1 47001

    1 5985

    1 445

    1 62723

    1 62613

    1 62369

    1 2559

    1 139

After I have done this, I decide to obtain more information. Because these are objects, it is a simple matter of choosing the properties that I want to see. To find which properties are available, I first use the Get-Member cmdlet as shown here.

PS C:\> Get-NetTCPConnection | Get-Member -MemberType property | Format-Table name, definition -AutoSize

 

Name                     Definition

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

AggregationBehavior      uint16 AggregationBehavior {get;set;}

AvailableRequestedStates uint16[] AvailableRequestedStates {get;set;}

Caption                  string Caption {get;set;}

CommunicationStatus      uint16 CommunicationStatus {get;set;}

Description              string Description {get;set;}

DetailedStatus           uint16 DetailedStatus {get;set;}

Directionality           uint16 Directionality {get;set;}

ElementName              string ElementName {get;set;}

EnabledDefault           uint16 EnabledDefault {get;set;}

EnabledState             uint16 EnabledState {get;set;}

HealthState              uint16 HealthState {get;set;}

InstallDate              CimInstance#DateTime InstallDate {get;set;}

InstanceID               string InstanceID {get;set;}

LocalAddress             string LocalAddress {get;}

LocalPort                uint16 LocalPort {get;}

Name                     string Name {get;set;}

OperatingStatus          uint16 OperatingStatus {get;set;}

OperationalStatus        uint16[] OperationalStatus {get;set;}

OtherEnabledState        string OtherEnabledState {get;set;}

PrimaryStatus            uint16 PrimaryStatus {get;set;}

PSComputerName           string PSComputerName {get;}

RemoteAddress            string RemoteAddress {get;}

RemotePort               uint16 RemotePort {get;}

RequestedState           uint16 RequestedState {get;set;}

Status                   string Status {get;set;}

StatusDescriptions       string[] StatusDescriptions {get;set;}

TimeOfLastStateChange    CimInstance#DateTime TimeOfLastStateChange {get;set;}

TransitioningToState     uint16 TransitioningToState {get;set;}

I decide that I am interested in four specific properties, so I can write the command shown here.

Get-NetTCPConnection | ft state,localport, localaddress, remoteport, remoteaddress -AutoSize

The problem is that this is a lot of typing. I like to use wildcard characters in my Format-Table commands when I can get away with doing so. Here is a perfect situation for using wildcards and not destroying the readability of the command. Here is my revised command.

Get-NetTCPConnection | ft state,l*port, l*address, r*port, r*address –Auto

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

Image of command output

There is not an alias predefined for the Get-NetTCPConnection cmdlet. I found this by using the Get-Alias cmdlet as shown here.

Get-Alias -Definition Get-NetTCPConnection

If the Get-NetTCPConnection cmdlet is something that you intend to use a lot, you should create an alias for the cmdlet and store that alias in your profile. If you want to do so, you can even call it netstat. (I do not necessarily recommend this; I am simply showing you that you could do so. If you do something like that, and you want the real netstat, just call netstat.exe). This is shown here.

PS C:\> New-Alias -Name netstat -Value Get-NetTCPConnection

PS C:\> netstat -State established

 

LocalAddress                  LocalPort RemoteAddress                RemotePort

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

192.168.0.47                        62613     157.56.98.134                       44

192.168.0.47                        62369     157.56.98.129                       44

Well, that is it for now. 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: Measure the Time for a Command to Complete

$
0
0

Summary: Learn how to measure the time for a Windows PowerShell command to complete.

Hey, Scripting Guy! Question How can I see how many seconds it takes to retrieve objects from the application log?

  Hey, Scripting Guy! Answer

 (Measure-Command { Get-EventLog application }).totalseconds

Use PowerShell 3.0 to Clear the Client DNS Cache on Workstations

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell 3.0 to clear the client DNS cache on workstations.

Microsoft Scripting Guy, Ed Wilson, is here. One of the things I love about Windows PowerShell 3.0 in Windows 8 is the number of cmdlets available. These cmdlets make it possible to perform literally hundreds of tasks from within Windows PowerShell. Thus, I rarely leave Windows PowerShell, go to Start, and type to bring up whatever GUI tool I might have needed in times past.

To be perfectly honest, I never used the GUI to clear the DNS cache on my local computer; nor did I ever use the GUI to register that client in DNS. The cool thing is that there are now cmdlets to perform this rather pedestrian task. In the past, I used ipconfig to flush the DNS cache and to register my computer with DNS. Of course, when switches were added to ipconfig, I always wondered why exactly they belong with ipconfig, other than the fact that it was a pretty handy place to add the functionality.

Of course trying to talk a NOOB through this process on the phone is always a challenge. The two commands, flushing the DNS cache and registering the computer in DNS, do not have to go together. The first command removes entries from the DNS resolver cache, and therefore forces the computer to retrieve up-to-date information from DNS.

I run this command at least once a week—for example, when I wake up early in the morning and check to ensure that the day’s Hey, Scripting Guy! Blog posted on time and correctly. At times I go to the blog, and the new entry does not appear to have posted. Rather than getting all in a tizzy, I have learned that for some reason, cleaning out old entries in my DNS cache resolves the issue. In the past, I used ipconfig /flushdns to perform that task. I also figure that as long as things need updating, I may as well ensure that my computer information is registerd properly in DNS. This is a preventive action, rather than a corrective task.

Flushing DNS cache and registering DNS across the network

Because flushing the DNS cache and registering DNS clients is a task that I perform on a routine basis, I decided to take a couple of minutes to knock out a script to perform this action. The first thing I do is import the Active Directory module. Then I use the Get-ADComputer cmdlet to find the name of all computers on the network running Windows 8. These three lines of code are shown here.

Import-Module activedirectory

$c = Get-ADComputer -Filter * -Properties operatingsystem |

   where operatingsystem -match 8

Now I use the Invoke-Command cmdlet to run the Clear-DNSClientCache and the Register-DNSClient cmdlets on remote machines running Windows 8. This command is shown here.

Invoke-Command -cn $c.name -SCRIPT {

  Clear-DnsClientCache

  Register-DnsClient }

Here is the complete script:

ClearDNSCacheAndRegister.ps1

Import-Module activedirectory

$c = Get-ADComputer -Filter * -Properties operatingsystem |

   where operatingsystem -match 8

Invoke-Command -cn $c.name -SCRIPT {

  Clear-DnsClientCache

  Register-DnsClient }

Well, that is about all there is to using Windows PowerShell 3.0 and Windows 8 to flush the DNS cache and to register the client in DNS. More cool Windows PowerShell stuff will continue tomorrow.

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 and Import Modules

$
0
0

Summary: Learn how to find and import Windows PowerShell modules.

Hey, Scripting Guy! Question I want to get a list of all the modules that are installed with Windows PowerShell on my machine. How can you do this?

Hey, Scripting Guy! Answer Inside a Windows PowerShell console, type the following command:

Get-Module -ListAvailable

Hey, Scripting Guy! Question I want to load all of the modules that are installed with Windows PowerShell on my machine. How can you do this?

Hey, Scripting Guy! Answer Inside a Windows PowerShell console, type the following command:

Get-Module –ListAvailable | import-module

Viewing all 3333 articles
Browse latest View live


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