Quantcast
Channel: Scripting Blog
Viewing all 2129 articles
Browse latest View live

Use PowerShell DSC to Configure the Registry

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell and Desired State Configuration to configure the registry.

Microsoft Scripting Guy, Ed Wilson, is here. I thought I would piggy-back a bit on the excellent posts that Windows PowerShell MVP, Richard Siddaway, wrote this week about working with the registry with Windows PowerShell.

If I want to make sure that a registry entry exists (or does not exist), I can use Windows PowerShell Desired State Configuration (DSC). Another advantage to using DSC is that it automatically updates, so I do not need to worry if the entry will still be there at a later point in time.

Using DSC to configure the use of biometrics

I decided that I wanted to disable the use of biometric devices for sign in to my system. To do this, there are several registry keys available that work in conjunction with Group Policy. The thing is that I do not want to fool around with using Group Policy. In fact, I have heard from many IT pros that the Group Policy teams in their organizations are reluctant to make changes they request.

Note  DSC runs in a system context, and therefore, it does not have access to the current user registry hive (HKCU).

On to my configuration script...

The first thing I do is use the Configuration keyword and specify a name for my configuration. I then specify my node—I am using LocalHost, so I do not need to worry about a computer name. I then specify the registry resource, and a name. I specify that I want the registry key to exist, so I specify that I will ensure it is present. I provide the registry key, the key name, the value, and the type of value. This portion of the script is shown here:

Configuration SetBiometrics {

    Node localhost {

    Registry DisableBiometrics {

        Ensure = "Present"

        Key = "HKLM:\SOFTWARE\Policies\Microsoft\Biometrics"

        ValueName = "Enabled"

        ValueData = "0"

        ValueType = "Dword" }

The other two registry sections are pretty much the same. In fact, I pasted the script from my previous section and made minor changes. Here are the other two parts of the configuration script:

Registry DisableCredentials {

        Ensure = "Present"

        Key = "HKLM:\SOFTWARE\Policies\Microsoft\Biometrics\Credential Provider"

        ValueName = "Enabled"

        ValueData = "0"

        ValueType = "Dword" }

    Registry DisableDomainCredentials {

        Ensure = "Present"

        Key = "HKLM:\SOFTWARE\Policies\Microsoft\Biometrics\Credential Provider"

        ValueName = "Domain Accounts"

        ValueData = "0"

        ValueType = "Dword" } }}

The last thing I need to do is to call my configuration like I would a function. I pass a directory for my output. I then use Start-DSCConfiguration and specify the path to the MOF file. This command is shown here:

SetBiometrics -output C:\clientConfig

Start-DscConfiguration -Path C:\clientConfig -Wait -Force -Verbose

Here is the complete script as it appears in my Windows PowerShell ISE:

Image of command output

Because I called Start-DSCConfiguration with the –Verbose parameter, I can see everything that is going on, in addition to how long it takes to run the configuration. In the output in the following image, I see that the registry key did not exist, and therefore, it was created.

Image of command output

That is all there is to it. Now Windows PowerShell DSC will make sure the registry keys exist and that they are set the way I want them set. To be sure, I open Regedit to see if the keys were created. As you see here, they were:

Image of menu

That is all there is to using Windows PowerShell DSC to set registry keys and values. This also concludes Registry Week. Join me tomorrow when Microsoft PFE and Honorary Scripting Guy, Ian Farr, continues his RODC series.

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

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Use PowerShell to Display Registry Keys

$
0
0

Summary: Learn how to use Windows PowerShell to display registry keys.

Hey, Scripting Guy! Question How can I use Windows PowerShell to provide a list of registry keys that I can filter, instead of using Regedit to search?

Hey, Scripting Guy! Answer Use the Get-ItemProperty cmdlet and point it to a specific registry hive. The following command looks for
           software and Microsoft on the HKLM drive. It uses the psChildName property to display the registry key names.

Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\* | select pschildname

Weekend Scripter: Use PowerShell to Delegate Administrator of RODCs

$
0
0

Summary: Microsoft PFE, Ian Farr, discusses using Windows PowerShell to delegate administrator of RODC.

Microsoft Scripting Guy, Ed Wilson, is here. Today we have Honorary Scripting Guy and Microsoft PFE, Ian Farr, back for more words of wisdom...

Welcome to the third post in a four part series about securing and managing read-only domain controllers (RODCs). I like to think of this collection of posts as "organic"—they only became a series after the green shoots of the first two posts were already well established!

The first post discussed a function that analyses RODC authentication. The function reports on accounts that are authenticated by an RODC that aren’t revealed (that is, the account password or secret is not stored on the RODC). It helps you manage your password replication policies. For the full write up, see Use PowerShell to Work with RODC Accounts.

The second post discussed a function that checks whether a user is a member of a high-privileged group. It can be used in conjunction with the first function to see if your RODCs have authenticated high-privileged users. This helps identify and remove a potential means of compromising Active Directory. To read that post, see Use PowerShell to Search Active Directory for High-Privileged Accounts.

Today’s post discusses a function that allows you to delegate the administration of an RODC. The function adds a user or a group to the ManagedBy attribute of the computer account for the RODC. This grants the user or group members local administrative privileges on the RODC.

Note  Users delegated as RODC administrators should not be a member of any privileged groups in Active Directory because this negates the protections that an RODC provides. Furthermore, the accounts used for delegated administration should be "secondary logon accounts" that are used only for RODC administration. For example, they should not be accounts that are also used to log on to workstations for typical user activity, such as Internet browsing or reading email.

Here’s the function: Set-ADRodcManagedByAttribute

Let’s take a look…

The function has two parameters: Rodc and Principle.

Rodc This parameter determines the RODC on which the ManagedBy attribute is set. It can accept a value from the pipeline, so we can pipe a list of RODCs into the function. There’s also some parameter validation to ensure that we are dealing with an RODC. If the domain controller object has the IsReadOnly attribute set to True, we know we have an RODC.

[parameter(Mandatory,Position=1,ValueFromPipeline)]

[ValidateScript({(Get-ADDomainController -Identity $_).IsReadOnly})]

[String]$Rodc

Principal This parameter defines the user or group that is added to the ManagedBy attribute. It has to be a DistinguishedName. The parameter validation uses the –Identity parameter of Get-ADObject, which only accepts a distinguished name and will check whether the user or group exists in Active Directory. The ManagedBy attribute should be populated with a domain local group.

[parameter(Mandatory,Position=2)]

[ValidateScript({Get-ADObject -Identity $_})]

[String]$Principal

The function has a Begin statement block to perform further validation before each RODC object is processed. In the following script, we check that the object supplied to the Principal parameter is a User or Group object. If it isn’t, we Break out of the function.

     Begin {

        #Get the supplied AD Object

        $ADObject= Get-ADObject -Identity $Principal -ErrorAction SilentlyContinue

 

        #Check that $Principal is a user or group

        If (($ADObject.ObjectClass -ne "user") -and ($ADObject.ObjectClass -ne "group")) {

 

            #Write a message to the host

            Write-Host "$Principal is not a user or group"

            Break

        }  

     }  

Next, we enter the Process statement block. We iterate through each RODC that is passed into the function and use the Get-ADComputer and Set-ADObject cmdlets to update the ManagedBy attribute. On the associated computer account object, to our user or group DistinguishedName, the -Replace parameter makes use of a hash table that references our user or group principal.

Process {

#Set the ManagedBy attribute

Get-ADComputer -Identity $Rodc | Set-ADObject -Replace @{ManagedBy = $Principal}

}  

Here’s an example of how to use the function:

Get-ADDomainController -Filter {IsReadOnly -eq $True} |

Set-ADRodcManagedByAttribute -Principal "CN=RODC Admins,OU=Groups,DC=Fabrikam,DC=com"

In this command, we get all of the RODCs for the current domain and pipe them into the Set-ADRodcManagedByAttribute function. This updates the ManagedBy attribute of each corresponding computer object to the distinguished name of the RODC Admins domain local group. Of course, we could also pipe a specific list of RODCs into the function to meet a particular administrative requirement, or simply run the function by itself against a single RODC.

And that’s it. Next time out, I’ll talk about synchronizing our delegated RODCs administrators’ passwords to their respective RODCs.

~Ian

Thanks, Ian. Join us tomorrow when Ian returns for the final part of this series.

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 Network Adapters Not Bound to TCP/IP

$
0
0

Summary: Use Windows PowerShell to find network adapters that are not bound to TCP/IP.

Hey, Scripting Guy! Question I am troubleshooting a computer that will not connect to the network, and I suspect the protocol bindings.
           How can I find network adapters that are not bound to TCP/IP?

Hey, Scripting Guy! AnswerUse the Get-NetAdapterBinding Windows PowerShell function, filter on a display name of TCP,
           and see if the protocol is enabled, for example:

Get-NetAdapterBinding -DisplayName *tcp* | where {!($_.enabled)}

Weekend Scripter: Use PowerShell to Synchronize Delegated Admin Passwords

$
0
0

Summary: Microsoft PFE and Honorary Scripting Guy, Ian Farr, discusses using Windows PowerShell to synchronize delegated administrator passwords.

Microsoft Scripting Guy, Ed Wilson, is here. Guest blogger and Honorary Scripting Guy, Ian Farr, is back with us today for the conclusion of his series about read-only domain controllers (RODCs)...

Welcome to the final post in my semi-spontaneous series about managing and securing RODCs.

The first post discussed a function that analyses RODC authentication. The function reports on accounts that are authenticated by an RODC that aren’t revealed (that is, the account password or secret is not stored on the RODC). It helps you manage your password replication policies. For the full write up, see Use PowerShell to Work with RODC Accounts.

The second post discussed a function that checks whether a user is a member of a high-privileged group. It can be used in conjunction with the first function to see if your RODCs have authenticated high-privileged users. This helps identify and remove a potential means of compromising Active Directory. To read that post, see Use PowerShell to Search Active Directory for High-Privileged Accounts.

The third post discussed a function that assists in ensuring that we have low-privileged users delegated as RODC administrators. It populates the RODCs ManagedBy attribute with a designated User or Group. It can easily propagate administrative privilege to a large number of RODCs. Here is that post: Use PowerShell to Delegate Administrator of RODCs.

On to the last post...

This one discusses a function that synchronizes the passwords of our previously delegated administrators.

Why do such a thing?

Without access to an read-write domain controller (RWDC), an RODC is unable to authenticate users or computers if their passwords aren't already stored on the RODC. Here's a scenario:

  • An RODC becomes isolated (unable to communicate with a RWDC).
  • A delegated admin needs to do some work on the isolated RODC.
  • The delegated admin has never previously logged on to the RODC.
  • The delegated admin's password has never been prepopulated.

In this scenario, the delegated admin would not be able to get into the RODC until connectivity with a RWDC is resumed. If the admin's password had been prepopulated, the admin could have performed the work.

How does the function work?

The function uses functionality that was introduced in 2012 with the Active Directory Replication cmdlets—namely, the –PasswordOnly parameter of the Sync-ADObject cmdlet. However, before we get to that bit, we need to enumerate the ManagedBy attribute of the RODC’s computer object and check whether we are dealing with a user or group:

$ManagedByPrincipal= Get-ADComputer -Identity $Rodc -Property ManagedBy |
ForEach-Object {Get-ADObject -Identity $_.ManagedBy}

The value in ManagedBy is a DistinguishedName, so we can then use Get-ADObject to retrieve an object and store it in $ManagedByPrincipal. With this variable populated, we check the ObjectClass to see if we are dealing with a user object, a group object, or something else:

If (($ManagedByPrincipal.ObjectClass-ne "user") -and ($ManagedByPrincipal.ObjectClass -ne "group")) {

#Write a message to the host

Write-Host "$ManagedByPrincipal is not a user or group"

}   #End of If (($ManagedByPrincipal.ObjectClass-ne "user") -and ($ManagedByPrincipal.ObjectClass -ne "group"))

Else {...}

If we are dealing with a user or group, we now determine the exact ObjectClass in the Else script block. We use the Switch statement to check if we have a user or a group object. If a group is found, we enumerate the members and store the results in $Principals. If a user is found, we assign our original $ManagedByPrincipal to $Principals:

Switch ($ManagedByPrincipal.ObjectClass) {

"group" {

#Hold the enumerated ManagedBy group members in $Principals

$Principals = Get-ADGroupMember -Identity $ManagedByPrincipal -Recursive

}   #End of "group"

"user" {

#Hold single ManagedBy principal in $Principals (user object)

$Principals = $ManagedByPrincipal

}   #End of "user"      

}  

Finally, we loop through each element of $Principals and execute the following script, which synchronizes the user’s password to our RODC:

$Principals | ForEach-Object {

Get-ADObject -Identity $_.distinguishedName |

Sync-ADObject -Destination $Rodc -PasswordOnly -PassThru

}  

In this script, we get an object that represents the current iteration of $Principals with the Get-ADObject cmdlet and pipe that into the Sync-ADObject cmdlet with our RODC as the destination. The –PasswordOnly parameter synchronizes only the password, as you’d expect.

The function’s –Rodc parameter accepts pipeline input, so we can run a one-liner like this to sync the passwords to a number of RODCs:

            Get-ADDomainController -Filter {IsReadOnly -eq $True} | Sync-ADRodcManagedByPassword

    Note You should synchronize the passwords of delegated RODC administrative accounts on a regular basis, so that the RODCs have up-to-date passwords.

That’s it for the series…for now, anyway! We’ve looked at four functions to assist with the administration of RODCs:

I’ve put the functions from the series into a fledgling module to expedite their usage:
RODC Management PowerShell Module

I've also applied the functions in the following sample script, which produces CSV reports of RODC authentication and high privileged use:
Create RODC Password Replication Policy and High Privileged Usage Reports

TTFN!
~Ian

Thanks for this series on RDOC, Ian!  It has been a great and useful series. 

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

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Display Routing

$
0
0

Summary: Use Windows PowerShell to display networking routing information.

Hey, Scripting Guy! Question How can I use Windows PowerShell to display information about network connectivity issues related to
           the routing table on my server and permit me to sort the output?

Hey, Scripting Guy! Answer Use the Get-NetRoute Windows PowerShell function, and sort by interface index, nexthop, or other properties,
           for example:

Get-NetRoute | sort ifindex

Don’t Learn PowerShell, Use PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about getting started with Windows PowerShell.

Hey, Scripting Guy! Question Hey, Scripting Guy! I get it. I need to learn Windows PowerShell—I see it mentioned everywhere. The problem is that I don’t have five years to learn the stuff. And besides that, by the time that five years has passed, you guys will probably come out with at least two new versions of Windows PowerShell. So if I spend five years trying to learn Windows PowerShell 4.0, by the time I am done learning it, I will still be three or four versions behind. I feel like I can never catch up—like a hamster running around on a wheel. I never seem to make any progress. What can I do?

—GM

Hey, Scripting Guy! Answer Hello GM,

Microsoft Scripting Guy, Ed Wilson, is here. I just got back from the gym. Luckily, the gym I go to is open 24 hours a day, so I can get up early and get back to still start my day. I kind of know what you are talking about. I did three miles on the treadmill this morning—and in the end, I never really moved an inch of distance.

GM, I can see what you are talking about, but you are basing your argument on a false argument. You do not need to learn everything there is about Windows PowerShell to use it. In fact, the vast majority of IT pros never write a single Windows PowerShell script. The difference between Windows PowerShell and VBScript (or some other scripting language) is that Windows PowerShell is not only a scripting language. In fact, it is possible to use Windows PowerShell without learning Windows PowerShell at all. This is because Windows PowerShell is an interactive environment in addition to a scripting language. Your problem has given me a good reason to introduce Don't Learn PowerShell Week.

Windows PowerShell ISE: Not only for scripts

The Windows PowerShell ISE is not only for writing scripts. In fact, I use it nearly all the time. The reason is that it is a great interactive console, and if I have more than a single command I want to type, I can move to the script pane, type my commands, and then run them. I do not have to write a script. The Windows PowerShell ISE is shown here:

Image of Windows PowerShell ISE

The upper white box is the script pane. The bottom blue box is the interactive Windows PowerShell console. It is also where the output from the script pane appears. The right pane is the Command Add-on. By default, when the Windows PowerShell ISE first launches, the Command Add-on appears. If I close it by clicking the “X” in the upper-right corner of the Command Add-on or by clearing the Show Command Add-on menu item (as shown in the following image), the next time I launch the Windows PowerShell ISE, the Command Add-on does not open. If I later decide that I want the Command Add-on, I select Show Command Add-on in the View menu.

Image of menu

What good is the Command Add-on anyway?

The Command Add-on is a great tool because it permits me to build commands on the fly. It also permits me to find Windows PowerShell cmdlets without knowing anything about the cmdlet name or about Windows PowerShell verbs or nouns. For more experienced Windows PowerShell users, it is a great tool to use when demonstrating to beginners how Windows PowerShell works.

First find the command

Obviously, the first thing to do is find the appropriate Windows PowerShell command. Windows PowerShell commands are often cmdlets—as in a little command. Notice that by default, the Modulestext box is set to All. If I know what module contains the command I want to use, I can select that module from the drop-down list. But when starting out, I would not even know what a module is, and I would definitely not know which module might contain the command I am interested in using. So I leave Modulesset to All, and I begin typing in the Nametext box. As I type, the cmdlets filter out until I am left with only a few cmdlets, as shown here:

Image of Windows PowerShell ISE

I look at the commands, and I see that some of them contain the word VMProcessor. I might guess that it has something to do with a virtual machine (because of the letters VM). Other commands, such as Debug-Process, Start-Process, and Stop-Process appear to be self-explanatory: Debug-Process probably has something to do with debugging a process, and Start-Process and Stop-Process probably permit me to start or stop a process.

One of the nice things about Windows PowerShell is most of the cmdlet names tend to make sense. (This is unlike the old-fashioned type of command names, such as SC, which seem to have very little relationship to anything.)

If I select the Get-Process cmdlet from the filtered Command window, the bottom pane immediately changes to display the parameters for Get-Process. This is shown here:

Image of Windows PowerShell ISE

Each parameter set (ways of using the cmdlet) appears on a different tab. The default is Name, and it appears as the one that is automatically selected. I can add the target ComputerName. I can also choose to display file versioning or module information by selecting the FileVersionInfo or Module options. In addition, I can limit the information that is returned to a specific process by entering the process name in the Nametext box.

When I have completed my selections, I have three choices. I can run the command immediately and display the output from the command by pressing the Run button. This is shown here:

Image of Windows PowerShell ISE

Alternatively, if I press the Insert button, the command appears in the interactive Windows PowerShell command window, but it does not execute. This permits me to make changes to the command, or to add additional commands to the command line prior to running the command.

In the following image, I have cleared the output from the previous command by pressing the Window wiper, squeegee, which is located on the Add-ons menu. Notice that the Get-Process command appears on the first line in the Windows PowerShell console, but it has not yet run.

Image of Windows PowerShell ISE

If I want the command in the script pane, I need to click the Copy button to place the command on the clipboard. I then paste it into the script pane at the appropriate location. This is shown here:

Image of Windows PowerShell ISE

So, by using the Windows PowerShell Command Add-on pane, I can easily find, create, and execute Windows PowerShell commands on the fly without having an in-depth knowledge of Windows PowerShell.

GM, that is all there is to using the Show-Command command. Don’t Learn PowerShell Week will continue tomorrow when I will talk about more 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: Find PowerShell Commands

$
0
0

Summary: Learn how to easily find Windows PowerShell commands.

Hey, Scripting Guy! Question How can I use Windows PowerShell if I do not know the appropriate command to use or the available options?

Hey, Scripting Guy! Answer In the Windows PowerShell console, type Show-Command. In the dialog box that appears, type what you need—
           such as process or service name. The appropriate Windows PowerShell commands appear, and you can select
           and run the command you need.


Predict the Future with PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, discusses using Windows PowerShell to see what a command will do before it does it.

Hey, Scripting Guy! Question Hey, Scripting Guy! My football coach always said, “If you’re scared, admit you’re scared.” Well, Scripting Guy, in honor of my old coach, I am admitting I am scared. I do not know Windows PowerShell, but it seems that so many of the new products from Microsoft use it. It seems that there are some things that I have to use Windows PowerShell for—like I have no option. Maybe there is an option, but I can’t find it. So what do it do? I am afraid I will mess something up by typing stuff when I have no idea what it is going to do. Can you help me?

—TD

Hey, Scripting Guy! Answer Hello TD,

Microsoft Scripting Guy, Ed Wilson, is here. The other day I was talking to my mom on the phone, and she said, “I don’t like tea that has a string on it.”

"Hmmm." At least I get my love for tea honestly. We grew up in an international community, and our neighbors had lived all over the world, so it is no wonder that we like tea. But the string? I know what she means, she prefers loose leaf tea. I do too, but I have also had some excellent tea that came in nice tea bags, and the string makes it rather convenient. When you get right down to it, tea is tea—whether it is good tea or bad tea, the string doesn’t really matter.

TD, it’s not Windows PowerShell that is the problem. In fact, many of admin tools use Windows PowerShell under the covers, for example Server Manager and the Exchange Admin tools. The GUI in these cases is simply another way of interacting with Windows PowerShell.

But when I click, click, click through one of the GUI tools, do I really know what it is doing behind the scenes? Some “wizards” tell me that they will do this, that, and the other thing—but I am not clear about all of the steps or all of the things that will be set or unset or installed or configured.

So although it may seem like the GUI tools are safer, in reality they are not always safer. I have seen many websites that say something like the following: To fix this problem or install this software, click here, click here and here, and clear this box and that one.

But what all that means or does is not often fully described. So in the end, I am still doing something I do not understand, and I am making changes when I know not what they might do.

What if I run this command?

One really beneficial parameter with Windows PowerShell is -Whatif. It is a common parameter, but it is only available when a command will make a change of some sort. For example, -WhatIf is not available for Get-Service because all that command does is produce information about services that are configured on a system. But Stop-Service does have the –WhatIf parameter because it will make changes to the system.

In a similar fashion, Get-Item does not have a –WhatIf parameter because it only returns items, but New-Item does have a –WhatIf parameter because it makes something new, and as a result, it makes changes to a system.

If I am using the Command Add-on tool in the Windows PowerShell ISE, and if a cmdlet has the –WhatIf parameter, it will be available as a check box. The following example illustrates this.

I open the Windows PowerShell ISE, and in the Command Add-on I begin typing the word Process. I do not need to type it completely. In fact, as shown in the following image, after I have typed proc, I have filtered enough of the cmdlets to permit me to find what I want:

Image of Windows PowerShell ISE

I select Get-Process, use a wildcard character for the Name parameter, and press the Copy button. I then paste the command in the Script pane. I type a single space and then the pipeline character ( | ), which on my keyboard appears above the backslash key. This will take all of the process objects and send them to my next command. After I have typed the pipeline character, I press ENTER.

In the following image, notice that at the end of my first line, there is a red squiggle. This red squiggle is how Windows PowerShell tells me that I have an incomplete command. When I added the pipeline character at the end of the line, Windows PowerShell expects it to be followed with something else. This is not a problem right now because in the next step I will add an additional command. My Windows PowerShell ISE now appears as shown here:

Image of Windows PowerShell ISE

I go back to my Command Add-on pane, press the Down arrow a couple times until I select Stop-Process from the list of cmdlets. The first tab is for the Id set of commands, the second tab is for the InputObject set of commands, and the last tab is for the Name set.

It is the Name set that I want, so I click the that tab. The text box is where I can type the name of the process I want to stop. The bottom check box is for the WhatIf parameter. I select that box.

Warning  It is crucial that you select the WhatIf check box before proceeding. Otherwise, your system could become unstable or even shut down when you run the script. 

After I select the WhatIf check box, I press the Copy button and paste my command under the Get-Process * | command. This is shown here:

Image of Windows PowerShell ISE

Because the Stop-Process command is using –WhatIf, Windows PowerShell will prototype the results of the command for me, and let me know what would happen if I run the command. This single feature of Windows PowerShell will save hours of potential down time related to misconfiguration and inadvertent commands.

Now I run the command to see what will happen. To run the command, I press the green triangle in the menu (I can also press F-5). The output is shown here:

Image of command output

It appears that the preceding command would stop every process on my system. That is not what I want to do.

Note  This is another reason for running as a non-admin—a non-admin would not have rights to stop system processes. The computer may become unstable, but it would not immediately crash because Windows PowerShell only has rights to do whatever the currently logged-in user has rights to do. As a best practice, one should always log in to the system with a least privileged user account, and then elevate when a specific action requires elevated privileges.

I can also use –WhatIf to see if other commands would work. For example, I noted earlier that the default paramater for Stop-Process is –Id. So can I use a wildcard character for the –Id parameter? Obviously, I want to test this—otherwise, I would essentially be re-creating my previous command to stop all processes.

I click the Id tab, and I note that the WhatIf check box is cleared.

Note  When changing tabs in the Command Add-on pane, –WhatIf and other check boxes are sometimes cleared. Do not get click happy and accidently run a command without –WhatIf if that is not your intention.

When I run my new command, I see that it is not allowed. So I learned that I cannot use a wildcard character for a process ID (it expects an integer). This is shown here:

Image of error message

I go back to the Name tab and change it to a wildcard character. I ensure that the WhatIf box is selected, and I run it. Yep, I can use a wildcard character for Name. It provides the same output as my prior Get-Process * | Stop-Process –WhatIf command. This is shown here:

Image of command output

TD, that is all there is to using Windows PowerShell to see the results of a command before it runs. Don’t Learn PowerShell Week will continue tomorrow when I will talk about more way 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: Find What a PowerShell Command Does

$
0
0

Summary: Learn how to find out what a Windows PowerShell command does before it does it.

Hey, Scripting Guy! Question I found a Windows PowerShell command on the Internet that might be what I need, but how can I see what
           it does before it messes something up?

Hey, Scripting Guy! Answer You can add the –WhatIf parameter to all Windows PowerShell cmdlets that make changes automatically,
           for example:

Stop-Process –name MYPROCESS -WhatIf

Don’t Learn PowerShell: Use Cmdlets

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell cmdlets to do IT ops work.

Hey, Scripting Guy! Question Hey, Scripting Guy! I have been an IT pro for many years, and to be honest, I am really good at my job. Now it seems you guys are abandoning me. I have been a loyal Microsoft supporter for many years, and I even got my MCSE back on Windows 2000. Now it seems like you want me to learn command-line stuff like AS400 or VAX. I learned Windows because I like graphical tools. I am good with a mouse, but I hate to type. What gives?

—BV

Hey, Scripting Guy! Answer Hello BV,

Microsoft Scripting Guy, Ed Wilson, is here. One of the basic principles of Windows PowerShell is that it honors your learning. This actually plays out in many ways. From Windows PowerShell version to Windows PowerShell version, the things you learn in one version continue to work in the subsequent version. This means that, for example, the book I wrote on Windows PowerShell 1.0 is still valid. It is a basics of Windows PowerShell kind of book. Of course, we added new features and made things much easier in later versions, but the basic principles remain the same.

BV, there is another way in which Windows PowerShell honors your learning, and that is where your Windows admin skills come into play. It is a common saying that “PowerShell is PowerShell is PowerShell.” Actually, I made up that saying, but amongst people I know, it has become a common phrase.

What I mean by that, is that when properly implemented, Windows PowerShell cmdlets for one technology behave exactly the same as Windows PowerShell cmdlets for another technology. So if I understand the basics of Windows PowerShell, such as how to use a cmdlet, and how to pipeline the results from one cmdlet to another, theoretically, Windows PowerShell fades into the background and permits me to simply do my job. (Obviously there are some cmdlets that use unapproved verbs, don’t accept pipelined input, don’t emit objects, and the like, but I was talking theoretically.)

Because I know Windows PowerShell, it does not mean that I can, for example, create a new firewall rule if I don’t know anything about firewall rules. But if I do know something about firewall rules, I can certainly use Windows PowerShell to create a new firewall rule.

Creating new firewall rules

If I want to create a new firewall rule, the first thing I do is open the Windows PowerShell ISE with admin rights (I do this by holding down the Shift key while I right-click the shortcut to the Windows PowerShell ISE.) I then select Run as Administrator from the action menu. (I can also search for Windows_ISE and then right-click the search results and select Run as Administrator).

I do this because an ordinary user probably does not have rights to create or modify the Windows Firewall configuration. When I have the Windows PowerShell ISE open with admin rights, I type the word firewallin the Name text box of the Command Add-on. The results shows many Windows PowerShell cmdlets that are related to firewalls. This output is shown here:

Image of Windows PowerShell ISE

If I did not know anything about Windows PowerShell, I can still look over the output and see if there is anything that looks like it might help me create a new firewall rule. The command name I see is New-NetFireWallRule. When I click it, it says something about importing the module and its cmdlets.

I may not have any idea at all about this, but it does say click the Show Details button. And to be honest, the output message is a bit misleading. I mean, it talks about importing modules, and the button is called Show Details. I would imagine that when I click a button called Show Details, it might...well...you know...show details about what it was talking about—sort of a “For more information” button.

But that is not what happens. What really happens when I click the Show Details button is that it imports the module that contains the New-NetFireWallRule cmdlet and the other firewall cmdlets. It then displays the parameters of the cmdlet in such a way that I can create my command. But hey, I can certainly click the Show Details button because I know how to use a mouse. This is shown here:

Image of Windows PowerShell ISE

When I click the Show Details button, the parameters for the New-NetFireWallRule cmdlet appear. It is now "fill-in the blank" time. This is where knowledge of how to configure a new firewall rule would certainly come in handy. Here are the first details of my new firewall rule:

Image of Windows PowerShell ISE

Many of the parameters are configured directly from drop-down lists. This permits me to do a minimal amount of typing. In addition, it ensures that I am configuring the cmdlet in the proper manner. This is shown here where I specify the encryption requirements:

Image of Windows PowerShell ISE

When I have completed my configuration for the new firewall rule, I am permitted to select WhatIf (this is because running the command would make changes to my system). Selecting this is a really, really, really good idea! Here is that selection:

Image of Windows PowerShell ISE

Now I click Copy, and I paste my command into my Script pane. I then run the command by clicking the green triangle (or pressing the F-5 function key). The command and its output are shown here:

Image of error message

I can see that what I created is a one-line command. This means that I will need to use the scroll bar under the Script pane to see all of my command. I could also break it up by using the grave accent ( ` ) character which is line continuation. (But this is an advanced topic, and to be honest, I do not do that until I get the command to run properly in the first place.)

I made several errors in configuring my command, so my output pane is filled with red output. It is very important not to ignore this output because it tells me that I messed up, and it also tells me how to fix it.

It is entirely possible that an experienced Windows Firewall administrator would not have made the errors that I did. For example, the command tells me that I did not specify the address properly. I can use a specific IP address, a range, or even a subnet, but evidently not a generic wildcard character. It also says that I can use certain address keywords, such as LocalSubnet, DefaultGateway, or Intranet, in certain places.

I make the change, run it again, and I get another error message. This time it says that I have a mismatch between Authentication and between Encryption. So I follow the recommendations and fix it. Then it tells me that I have the wrong protocol, so I fix that. Eventually, I get it to where the command does not error out.

As shown here, it tells me that if I run the command, it will create the new rule:

Image of Windows PowerShell ISE

Cool. So like I said, Windows PowerShell honors your learning, and doing things like configuring a new Windows Firewall rule is easier if one knows what one is doing.

I now have a functioning new firewall rule. What do I do with it?

I can copy the one-line command and make a few changes to it, then create another rule. Or I can click the Refresh button, and use the Command Add-on to make a new rule, and then paste it under my previous command in the Script pane.

If I continue to do this, I can save the file and use it as a script to configure multiple computers. That is where the real power of this stuff comes into play. In addition, as opposed to clicking through the GUI tools (of the Firewall Admin tool, for example), I now have a record of all of the changes that I made. So if I did make a mistake while configuring it, I can go back to my file and see where I messed up. By saving my Windows PowerShell commands, I also document the changes I make. That is the Windows PowerShell advantage.

BV, that is all there is to using Windows PowerShell. Don’t Learn PowerShell Week will continue tomorrow when I will talk about more way 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: Automatically Find Options in PowerShell

$
0
0

Summary: Learn how to see available options in the Windows PowerShell ISE.

Hey, Scripting Guy! Question How can I easily see what options are available when I type in a cmdlet name in the Windows PowerShell ISE?

Hey, Scripting Guy! Answer Use IntelliSense. There are two ways to display IntelliSense:

1. From the Edit menu, select Start Intellisense.

2. Use the Ctrl-Space keyboard shortcut as follows:

        • In the Script pane of the Windows PowerShell ISE (the upper white box) type Get-Process.
        • Type a space after the final “s” in Get-Process.
        • From the Edit menu, select Start IntelliSense.
        • Choose the process name from the drop-down list that appears.

Don’t Learn PowerShell: Reaching Out

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about running commands on remote servers.

Hey, Scripting Guy! Question Hey, Scripting Guy! One of the things I really don’t understand is why Windows PowerShell is broken. I look at commands like you suggest, but they don’t work. Specifically, I wanted to see the status of services on my servers, but the commands just don’t work. What’s up with that?

—BB

Hey, Scripting Guy! Answer Hello BB,

Microsoft Scripting Guy, Ed Wilson, is here. This morning it is cold and raining, which would not be unusual winter weather for Charlotte, North Carolina—except the weather app on Bing said it was going to be sunny all day. It seems that Punxsutawney Phil is more accurate—and he is just a gopher. I wonder, at times, why the weather forecast remains a mystery and isn't updated. I can look outside and see that it is raining, and yet the app says sunshine. Hmmm...

BB, one thing that is not a mystery is why Windows PowerShell won’t work. There is always a reason, and in your case, there are a few likely suspects:

  1. Rights.
    The account you are using to make your remote command may not have rights on the destination server.
  2. Firewall.
    The port used by the command you are attempting to run may be blocked at the firewall.
  3. Services.
    Some commands rely on services, such as the Remote Registry Service or others that may not be running by default.

Because of these issues, I have pretty much quit using commands such as Get-Service –ComputerName MyRemoteServer. The command will fail by default unless you have made configuration changes on your servers—and I would not recommend making such changes due to the fact that you would be widening the attack surface on your servers.

A simple change

The solution is simple: change your command...just a little bit.

I add the command Invoke-Command. When I use Invoke-Command, the command uses WinRM (which is enabled by default on Windows Server 2012 R2. Windows PowerShell uses WinRM for remoting commands. The great thing about this is that it is already enabled on servers, and I do not need to do anything.

Note  If WinRm is not enabled, I use the Enable-PSRemoting command. I can test if WinRM is enabled and configured properly by using the Test-WsMan command.

The command to check the status of the BITS service on a remote server named S1, so the command would therefore be:

Invoke-Command -ComputerName S1 { Get-Service bits }

If I need to check the status of the BITS service on several remote servers, I can separate the computer names with a comma. The following command checks the status of the BITS service on the servers named S1, S2, and SGW.

Invoke-Command -ComputerName S1, S2, SGW { Get-Service bits }

The cool thing is that Windows PowerShell automatically adds a column named PSComputerName to the output. This is shown in the following image:

Image of command output

If I need to add different credentials, I use the –Credential parameter. This causes a dialog box to appear that prompts me to type my password. Here is the command:

Invoke-Command -ComputerName S1, S2, SGW  -Credential nwtraders\administrator { Get-Service bits }

The dialog box is shown here:

Image of dialog box

BB, that is all there is to using Windows PowerShell against remote servers. Don’t Learn Windows PowerShell Week will continue tomorrow when I will talk about more 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: Run Part of PowerShell Command

$
0
0

Summary: Learn how to run part of a command in the Windows PowerShell ISE.

Hey, Scripting Guy! Question I am having problems with a small part of a script that I am working on in the Windows PowerShell ISE—
           how can I test only that code?

Hey, Scripting Guy! Answer Highlight only the portion of the script you want to test, and press the F-8 key or the small green triangle on the
           toolbar (or select Run Selection from the File menu). Only the section of code that you highlighted will run.

Use PowerShell to View and Filter Information

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to view and filter information.

Hey, Scripting Guy! Question Hey, Scripting Guy! I am not a scripter—never have been, never will be. But over the years I have used lots of people's scripts to do different things. I actually got some of my favorite scripts from the Scripting Guys—scripts that create an HTA that allows me to filter and manipulate data.

The cool thing about this is that all I need to do is to double-click, and boom! It pops up and does what it needs to do. I would love to be able to use Windows PowerShell to do something like that, but I really don’t want to have to go to all the trouble of finding new scripts and all that. Besides, as I understand it, Windows PowerShell scripts are not double-clickable. Can you help?

—LT

Hey, Scripting Guy! Answer Hello LT,

Microsoft Scripting Guy, Ed Wilson, is here. One of the great things about Windows PowerShell is that it has a number of mechanisms for handling output. One can output a CSV file and open the file in Microsoft Excel. One can output XML and open the file in a browser. Or one can output text and view it in Notepad. There are even cmdlets that create HTML or send emails. One can also write scripts and present information in Windows Forms, WPF, or some other mechanism if one desires to do so.

As for clickability...

I wrote a script that creates a shortcut to a Windows PowerShell script and calls Windows PowerShell to launch the script, so it is possible to have clickability if one wants it. In fact, I created a Start tile on my Surface that launches a Windows PowerShell script to display remaining battery life. So yeah, it is doable.

This requires a bit of work

By far, the easiest way to interact with and look at output is to use the Out-GridView cmdlet. What is so cool about this is that it permits me to filter my output, sort my output, and to view my output. So rather than having to use Windows PowerShell to filter the output that displays to the Windows PowerShell console, I can use a graphical tool to do this instead. It is great for administrators who don’t want to learn Windows PowerShell, but would still like to use Windows PowerShell to gather data.

In the example that follows, I pipe the output from Get-Process to the Out-GridView cmdlet:

get-process | Out-GridView

The grid control created by the command is shown here:

Image of grid

Now, I click Add criteria, and select the column I want to work with from the following drop-down list:

Image of menu

After I select ProcessName, I am provided with appropriate operators. I click the highlighted operator containsand change it to equals. This is shown in the following image:

Image of menu

I am interested in the instances of the iexploreprocess, so I type that into the text box to the right of the operator. As shown here, my output changes, and I am only looking at the instances of iexplore:

Image of output

If I want to sort by which process ID is using the largest working set of memory, I can click the button labeled WS(K). The output changes and will be sorted based on largest to least—or if I click again, it will sort from least to largest. This is shown here:

Image of output

There is a lot that we can do with the Out-GridView cmdlet, and this will get you started working with it. For more information, see this series of Hey, Scripting Guy! Blog posts.

LT, that is all there is to get you started using Windows PowerShell with the Out-GridView cmdlet. Don’t Learn Windows PowerShell Week will continue tomorrow when I will talk about more way 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: Find Assigned Virtual Machine Network Adapters

$
0
0

Summary: Learn how to find network adapters that are assigned to virtual machines.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find what network adapters are assigned to my virtual machines?

Hey, Scripting Guy! Answer Use the Get-VM cmdlet and pipe the results to the Get-VMNetworkAdapter cmdlet, for example:

Get-VM | Get-VMNetworkAdapter          

Note  You must run this command with elevated permissions.

Weekend Scripter: Control Processes with PowerShell

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to control processes.

Microsoft Scripting Guy, Ed Wilson, is here. This morning I am made a pot of Masala Chai. I found a pretty good recipe when I was doing a Bing search: Indian Masala Chai. One of my pet peeves is when people refer to it as Chai tea, which is rather silly because the word chai simply means tea, so they are literally saying "tea tea." Anyway, I spent a decent amount of time heating milk, finding spices, and making a nice pot of black Assam tea for the starter. It was a nice relaxing way to start a morning, and my efforts are rewarding.

That is the way it is with lots of things, a little bit of effort soon becomes very rewarding. This is especially true with Windows PowerShell. I probably use Windows PowerShell every day—on my laptop, on my Surface, on my servers.

Whenever I find myself doing the same thing over and over and over again, that is a good opportunity for me to investigate using the power of Windows PowerShell.

One thing I do every day is start the day by turning on my computer, logging in, and then launching the same three applications: Outlook, Lync, and Word. It is always the same three applications: Outlook, Lync, and Word. I may also open Internet Explorer, but that is always after I have launched Outlook, Lync, and Word.

And you know what? Those are also probably the three slowest applications to launch. This means that after I log in, I click and wait, wait, wait, wait, wait. I click again and wait and wait and wait, and click once more.

Finally I decided, that is stupid. You know why? Because I also always launch Windows PowerShell. So I wrote a very simple script that launches my three applications:

Start-Process outlook.exe

sleep -Seconds 3

Start-Process Lync.exe

sleep -Seconds 2

Start-Process Winword.exe -WindowStyle Minimized

I usually look at...no, I take that back, I always look at my email first. So I do not need to have Word (the process name is Winword) maximized. So I use the WindowStyle parameter to launch Word as minimized. I tried that with Lync, but for some reason it did not work, and Lync stayed maximized anyway. Oh well.

Another thing that did not work was using the –Wait parameter. The Start-Process cmdlet has a –Wait parameter that I wanted to use. I wanted it to suspend execution of the script until the application was fully launched. The problem is that Outlook and Lync never seem to complete launching—that is, they are always doing something in the background...syncing address lists, updating status, checking for new email and so forth and so on. So the –Wait parameter would simply hang the script.

To prevent that, I decided to give Outlook three seconds and Lync two seconds before launching the next process. In reality, on my poor old laptop, this is not nearly enough time. It seems that Outlook wants at least 10 seconds to become halfway usable, but there was no way I was going to wait around that long for the script to complete.

So what do I do with my script? Well, I put it in my easy-to-access folder, and I use the Task Scheduler to launch the script at logon, but I delay it for 15 minutes. This permits me to log on to my laptop, and then go make a pot of tea. This gives my laptop time to settle down, and my applications are waiting for me when I come back. Perfect solution! The script was easy to write, and I used the GUI to schedule my script because it is a one-off sort of thing.

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

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Start a Bunch of Processes

$
0
0

Summary: Learn how to start a bunch of processes by using Windows PowerShell.           

Hey, Scripting Guy! Question How can I use Windows PowerShell to start a whole bunch of processes for testing purposes on one of my systems?

Hey, Scripting Guy! Answer Use a Windows PowerShell range operator, such as 1..10, to specify how many processes you want to create.
           Then pipe the results to the Foreach-Object cmdlet, and in the script block, use Start-Process to create
           the commands you need. Here is an example:

1..10 | Foreach {Start-Process notepad}

You can simplify this command by using % for Foreach, and by simply calling the executable:

1..10 | % { notepad}

To check how many processes you created, use the Get-Process cmdlet:

(Get-Process notepad).count

Weekend Scripter: German PowerShell Community Conference

$
0
0

Summary: Windows PowerShell MVP, Tobias Weltner, talks about the Windows PowerShell Community Conference in Germany.

Microsoft Scripting Guy, Ed Wilson, is here. I'm drooling today because of the information in this blog post. Teresa and I love to go to Germany. Our last two major vacations have started and ended there. Tobias Weltner is our guest blogger today, and I won’t share his news. I will give you a sneak peak though. This photo was taken in 2006 in Essen, Germany. If you have a chance to go, you will love Essen. It is a beautiful city, and it is easy to get to via the trains.

Photo from Essen

Turning the keyboard over to Windows PowerShell MVP, Tobias Weltner…

Ready for a big scoop of Windows PowerShell wisdom? The third annual German PowerShell Community Conference is just ahead. It will take place April 22-23 in Essen, Germany. Six MVPs, three book authors, and Bruce Payette from the Windows PowerShell team will discuss top-notch topics, such as security and Just Enough Admin (JEA), desired state configuration deep dives, new class support in Windows PowerShell 5.0, and the all new example-based parsing.

Product-based solutions include Active Directory troubleshooting, Exchange Server, Lync, SharePoint, and virtualization. And thanks to OMI and OData, you’ll see how Windows PowerShell leverages even non-Windows systems (such as Linux) and devices (such as network switches). For the complete agenda, see PowerShell-Konferenz 2015 Zeitplan.

The conference fee includes lunch, snacks, coffee breaks, drinks, and an evening dinner. (Beverages with alcohol will be served the evening event.) There will be plenty of room to connect, discuss, and learn!

It’s a German conference, and roughly 2/3 of the presentations will be held in German. Be sure to bring some basic read-only German language skills.

Seats are limited, so sign up soon and support this great event: PowerShell-Konferenz 2015 Information.

Here is a more detailed English article about the event in PowerShell Magazine: Community Conference in Germany.

~Tobias

Thanks, Tobias. Readers, don’t be sad for Teresa and me because we will not be in Germany for this event. We will be in Charlotte, NC on those dates, attending PowerShell Summit NA 2015.

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: Open Fonts Dialog Box with PowerShell

$
0
0

Summary: Use a Windows PowerShell cmdlet to open the Fonts dialog box.

Hey, Scripting Guy! Question How can I use Windows PowerShell to open the Fonts dialog box so I don't have to mouse around trying to find it?

Hey, Scripting Guy! Answer Use the Show-ControlPanelItem cmdlet:

Show-ControlPanelItem fonts

Viewing all 2129 articles
Browse latest View live


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