Quantcast
Channel: Windows Server Blogs
Viewing all 2283 articles
Browse latest View live

The Basics of Windows PowerShell Workflow: When to Use It and Why

$
0
0

Summary: Guest blogger Jeff Wouters talks about the basics of Windows PowerShell 3.0 workflows: when to use it and why.

Microsoft Scripting Guy, Ed Wilson, is here. Today, The Scripting Wife and I are traveling on our way from Oslo, Norway, to Eindhoven, The Netherlands, where I will speak at the Dutch PowerShell User Group event tomorrow. Tonight, we will spend the night in a sleeper car on the train for the last part of the journey between Copenhagen, Denmark, and Utrecht in The Netherlands. I have ridden in a sleeper car before, but this will be Teresa’s first time and she is all excited. Once we arrive in Utrecht, Microsoft PFE Stefan Stranger will pick us up to take us the rest of the way to the User Group Event.

This leads to today’s guest blogger and the host for the User group event Jeff Wouters.

Photo of Jeff Wouters

Jeff Wouters (B ICT, MCITP, MCSA, MCSE) is a freelance Technical Consultant from The Netherlands with a main focus on high availability and automation using Microsoft and Citrix products by using technologies such as virtualization, redundancy, clustering, and replication. He also has a great passion for Windows PowerShell and is a founding member of the Dutch PowerShell User Group in 2012.

Jeff has been a speaker on IT events such as E2E Virtualization Conference (formerly known as PubForum), BriForum Chicago, and NGN (Dutch IT community). You can find Jeff on social media (Twitter @JeffWouters | Facebook @JeffWouters | LinkedIn @JeffWouters) and at his blog. He speaks and blogs mainly about Windows PowerShell and virtualization, but every now and then something else slips in that piques his interest.

Jeff is also a contributing author for a book project where 30+ authors from all over the world work together to create a Windows PowerShell deep-dive book that will be published in 2013.

Take it away, Jeff.

Back when Windows PowerShell 2.0 was introduced, it brought us remoting. Soon after, you could see lots of products starting to use this technology since it is very, very powerful.

Windows PowerShell 3.0 has brought us workflow. I dare to predict that this will have an even bigger impact than remoting had, and therefore, I had the idea to write a little blog post about it from my usual practical point of view… and put the subject on my “to write” list.

And then Ed’s mail came along asking if I would be interested in writing a guest post for the Hey, Scripting Guy! Blog. As soon as I read the mail I thought about my plan to write a Workflow post and thought that this would be a great subject for Ed’s blog.

And, so here I am … Jeff Wouters, PowerShell enthusiast, from The Netherlands and blogger at http://www.jeffwouters.nl.

What is workflow?

A workflow is basically a bunch of tasks executed in sequence that require some coordination because they may be executed across different devices. Or, at least that’s what the Help file says. I’ve found a few more practical applications for it that I’ll cover in this post.

By design, workflows are repeatable, interruptible, restartable, stoppable, parallelizable, and frequent—more about that in “Why use workflow?” later in this post.

Although workflow is very powerful, please understand that it is also very difficult. It is very easy to overcomplicate things and, as with all larger scripts, it’s smart to think about what you want your script to do, including its structure, before actually writing the script.

PowerShell has a core module named PSWorkflow, which simply makes use of the Windows Workflow Foundation. Workflow is not something native to Windows PowerShell—it simply makes very smart use of a technology that’s already there in the Windows operating system.

The power of workflow

To truly understand the power of workflow, I can only tell you to just start using it.

But, of course, that’s not something useful for this post because you want an example, right? Instead of giving you a bunch of code, I’ll simply give you an example that just about any Windows administrator knows: Server Manager.

In Windows Server 2012, they’ve totally rewritten the thing, and it has become a lot faster because it is now basically a GUI around (A LOT!) of Windows PowerShell and WMI code. It also allows you to manage your environment from that single console because it also uses workflow!

When you deploy a scenario-based solution from Server Manager, it will know, based on that scenario, which task to execute before the other. It will generate a workflow to accomplish the actual work and will let it loose on the target servers. So, WMI combined with Windows PowerShell and workflow and remoting brings some serious horse power to the table. 

Why use workflow?

Don Jones, Windows PowerShell MVP, has already covered that in one of his posts, so I’ll not be re-doing his work: http://powershell.org/wp/2012/08/30/powershell-workflow-when-should-you-use-it.

In my opinion, only situations for a deployment script and some basic maintenance/configuration scripts will allow you to use workflow in an easy and understandable way. You’ll see that in the scripts I’m providing in this post.

That’s why, as with all larger scripts, I advise you to chop your larger workflows up into smaller pieces.

With code, developers call this modular programming. When you do it in your mind, I call it modular thinking. So, when I start scripting, I think: Tasks > Workflows > Functions > Modules… in that order.
For me, personally, this has made my scripting life a whole lot easier. 

Don’t use workflow unless there is no other way … ?

I’ve seen someone write—don’t know for sure who it was—that you should only apply workflow when there is truly no other option available that fits your specific needs. I don’t agree with that up to a certain point and let me tell you why.

  1. When you can read functions, you can read workflows—it’s readable.
  2. Even at its basic level, workflow is very powerful.
  3. A lot of times using workflow will require much less code compared to not using it while it remains readable.
  4. It can seriously reduce execution times for your scripts.
  5. When you keep at the basics, while it still suits your needs, it isn’t that difficult… really!

Next to these things, the only true limitation to Windows PowerShell is your imagination. So, when you overcomplicate your scripts, it’s not the fault of Windows PowerShell. Saying that you should only apply workflow when there is no other option available is like saying only to use Windows PowerShell when there is no other option… that’s crazy, right?

Practical and simple workflow applications

When I need to deploy 50 virtual machines with the same configuration and named VM from 1 to 50, there are a couple of ways you can do this.

The first one could be to write 150 lines of code—not something I would like doing.

The second is to write a small loop:

1..50 | ForEach-Object { New-VM -Name VM$_ -MemoryStartupBytes 512MB –NewVHDPath "D:\Hyper-V\Virtual Hard Disks\VM$_.vhdx" -NewVHDSizeBytes 15GB }

With a loop, tasks are executed in sequence. This is where workflow can help you to seriously speed things up in an easy way. With workflow, you are able to use the -Parallel parameter with the ForEach cmdlet that allows for 5 parallel threads at a time. So, if your hardware can handle the load, then creating the virtual machines can become about 5 times faster!

The third way of doing this by using workflow:

workflow New-VirtualMachines

{

  $VMs = 1..50

  foreach -parallel ($VM in $VMs)

  {

    New-VM -Name VM$VM -MemoryStartupBytes 512MB –NewVHDPath "D:\Hyper-V\Virtual Hard Disks\VM$VM.vhdx" -NewVHDSizeBytes 15GB

  }

Execution time of the first script was about 9 minutes in my environment; execution time of the workflow script was about 2 minutes! But, for all of you that are thinking this is rather static, workflows accept parameters just like functions do. The following workflow accepts both the virtual macine name, number of to create virtual machines, and the VHD size as input by parameter:

workflow New-VirtualMachines

{

  [CmdletBinding()]

  Param (

    [Parameter(Mandatory=$true,Position=0)]$VMName,

    [Parameter(Mandatory=$true,Position=1)]$VMCount,

    [Parameter(Mandatory=$true,Position=2)]$VHDSize

  )

  $VMs = 1..$VMCount

  foreach -parallel ($VM in $VMs)

  {

    New-VM -Name $VMName$VM -MemoryStartupBytes 512MB -NewVHDPath "D:\Hyper-V\Virtual Hard Disks\$VMName$VM.vhdx" -NewVHDSizeBytes $VHDSize

  }

}

You can simply call this workflow the same way you would a function:

New-VirtualMachines -VMName VM -VMCount 50 -VHDSize 15GB

Even at a basic level, it’s easy, fast, readable, and reusable!

And then there is the second most common use case I see for workflow: Executing tasks in sequence. Some time ago, I wrote a maintenance script for one of my customers and all it had to do was accomplish a few tasks:

Number

Wait for number

Target

Task

1

 

WEB01

Stop MyApp service

2

1

WEB01

Stop MyAppQueue service

3

1,2

FS01

Remove MyAppQueue.xml

4

1,2

FS02

Remove MyAppQueue.xml

5

4,5

WEB01

Start MyAppQueue service

6

5

WEB01

Start MyApp Service

Back then I didn’t have workflow, so there was quite a lot of code. Now, with workflow, it looks like this:


Workflow Refresh-MyApp

{

  sequence

  {

    Invoke-Command -ComputerName WEB1 {Stop-Service -Name MyApp -Force}

    Invoke-Command -ComputerName WEB1 {Stop-Service -name MyAppQueue

    -Force}

    parallel

    {

      Invoke-Command -ComputerName FS1
      {

        Remove-Item -Path "D:\MyApp\Files\MyAppQueue.xml" –Force

      }

      Invoke-Command -ComputerName FS2

      {

        Remove-Item -Path "D:\MyApp\Files\MyAppQueue.xml" –Force

      }

    }

    Invoke-Command -ComputerName WEB1 {Start-Service -Name MyAppQueue}

    Invoke-Command -ComputerName WEB1 {Start-Service -Name MyApp}

  }

}


Note  I’m using Invoke-Command here since I find it to be easy, readable, and it fits my needs in that specific situation. I prefer to do it this way above the way workflow offers natively, but I won’t cover the native way in this post.

As you can see, some of the tasks are executed in sequence and will wait for each other. But since the deletion of the files are both depended on the same previous steps and are not depended on one another you can execute these in parallel.

Function vs. workflow

What’s the difference? No, wait…that’s the wrong question because they are two separate things. What’s the same? Yes, that’s the one!

When you know how a function is written, you already know mostly how a workflow is written. It uses the same syntax and accepts parameters the same way as a function does. The Windows PowerShell product group is nothing if not consistent.

Compare the virtual machine deployment workflow a few lines earlier with this VM Deployment function:

function New-VirtualMachines

{

  [CmdletBinding()]

  Param (

    [Parameter(Mandatory=$true,Position=0)]$VMName,

    [Parameter(Mandatory=$true,Position=1)]$VMCount,

    [Parameter(Mandatory=$true,Position=2)]$VHDSize

  )

  $VMs = 1..$VMCount

  foreach ($VM in $VMs)

  {

    New-VM -Name $VMName$VM -MemoryStartupBytes 512MB -NewVHDPath "D:\Hyper-V\Virtual Hard Disks\$VMName$VM.vhdx" -NewVHDSizeBytes $VHDSize

  }

}

As you may have noticed, there are only two:

  1. Replace “workflow” with “function” in the 1st line.
  2. Remove -Parallel from the 10th line. Functions don’t know -Parallel, only workflow does.

Go crazy with the basics

A function can call a workflow, and a workflow can call a function. But as a function can call a function, a workflow can also call a workflow—still following? This is where it can suddenly become overcomplicated and where workflow allows for check pointing. 

Also, remember your resources. When you create 5 VHDX files at the same time by using ForEach -Parallel, then suddenly your environment can become sloooooow. So, think before you script. And, if you truly want to overcomplicate things, here’s something you’re gonna love. Within a sequence block, you can have a parallel block. And, within that parallel block you can have a sequence block, and so on and so forth.

Just to give you an idea, I’ve taken the Refresh-MyApp workflow I used earlier in this script and added a few things to it—just to give you an idea of how easy it is to overcomplicate things:

Workflow Refresh-MyApp

{

  sequence {

    Invoke-Command -ComputerName WEB1 {Stop-Process -Name MyApp -Force}

    Invoke-Command -ComputerName WEB1 {Stop-Process -Name MyAppQueue -Force}

    parallel {

      Invoke-Command -ComputerName FS1 {Remove-Item -Path "D:\MyApp\Files\MyAppQueue.xml" –Force}

      Invoke-Command -ComputerName FS2 {Remove-Item –Path "D:\MyApp\Files\MyAppQueue.xml" –Force}

      sequence {

        parallel {

          Invoke-Command -ComputerName FS1 {Stop-Process -Name MyAppFSQueue}

          Invoke-Command -ComputerName FS2 {Stop-Process -Name MyAppFSQueue}

        }

        Invoke-Command -ComputerName FS1 {Remove-Item –Path "D:\MyApp\Log\Queue.log" –Force}

        Invoke-Command -ComputerName FS2 {Remove-Item –Path "D:\MyApp\Log\Queue.log" –Force}

        parallel {

          Invoke-Command -ComputerName SQL1 {Stop-Process -Name mssqlserver -Force}

          Invoke-Command -ComputerName SQL2 {Stop-Process -Name mssqlserver -Force}

          Invoke-Command -ComputerName SQL3 {Stop-Process -Name mssqlserver -Force}

        }

        parallel {

          Invoke-Command -ComputerName SQL1 {Start-Process -Name mssqlserver -Force}

          Invoke-Command -ComputerName SQL2 {Start-Process -Name mssqlserver -Force}

          Invoke-Command -ComputerName SQL3 {Start-Process -Name mssqlserver -Force}

        }

        sequence {

          Invoke-Command -ComputerName FS1 {Start-Process -Name MyAppFSQueue}

          Invoke-Command -ComputerName FS2 {Start-Process -Name MyAppFSQueue}

        }

      }

    }

    Invoke-Command -ComputerName WEB1 {Start-Process -Name MyAppQueue}

    Invoke-Command -ComputerName WEB1 {Start-Process -Name MyApp}

  }

  Send-MailMessage -From "MyApp@domain.com" -To "servicedesk@domain.com" -Subject "MyApp maintenance completed" -Body "The MyApp maintenance script has run."

}

Here’s a table that explains the inner relationships of the script.

Number

Wait for number

Target

Task

1

 

WEB1

Stop process MyApp

2

 

WEB1

Stop process MyAppQueue

3

1-2

FS1

Remove MyAppQueue.xml

4

1-2

FS2

Remove MyAppQueue.xml

5

1-4

FS1

Stop process MyAppFSQueue

6

1-4

FS2

Stop process MyAppFSQueue

7

1-6

FS1

Remove Queue.log

8

1-7

FS2

Remove Queue.log

9

1-8

SQL1

Stop process mssqlserver

10

1-8

SQL2

Stop process mssqlserver

11

1-8

SQL3

Stop process mssqlserver

12

1-11

SQL1

Start process mssqlserver

13

1-11

SQL2

Start process mssqlserver

14

1-11

SQL3

Start process mssqlserver

15

1-14

FS1

Start process MyAppFSQueue

16

1-15

FS2

Start process MyAppFSQueue

17

1-16

WEB1

Start process MyAppQueue

18

1-17

WEB2

Start process MyApp

19

1-18

-

Send email

The goal of this post

My only goal with this post is to show you just how easy workflow can be. I hope that you can see the power of workflow—even at a basic level. The similarities with functions make it easy to learn and use and its power for executing tasks in parallel. It is, well, unparalleled. Maybe it can help you with your scripting challenges endeavors—I think it can. If you’re new to workflow, start with the basics as shown in this post and go from there.

Happy scripting!

~Jeff

Thank you, Jeff—excellent job.

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: Identify Disconnected PowerShell Sessions

$
0
0

Summary: Learn how to identify Windows PowerShell 3.0 disconnected sessions.

Hey, Scripting Guy! Question How can I find out which Windows PowerShell 3.0 sessions are disconnected?

Hey, Scripting Guy! Answer Use the Get-PSSession cmdlet and look for sessions that have a state of disconnected, as shown here.

PS C:\> Get-PSSession

 

 Id Name            ComputerName    State         ConfigurationName     Availability

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

  1 Session1        dc3             Opened        Microsoft.PowerShell     Available

  3 Session2        dc2             Disconnected  Microsoft.PowerShell          None

Exploring the PowerShell PSDiagnostics Module

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about exploring the Windows PowerShell PSDiagnostics module.

Microsoft Scripting Guy, Ed Wilson, is here. Let’s see, so today is November 23, 2012, which means that the Scripting Wife and I are in The Netherlands, and today, we are at the day-long Dutch PowerShell Group meeting. We get to see Jeff Wouters (yesterday’s guest on the Hey, Scripting Guy! Blog) and Stefan Stranger, who is a Microsoft PFE, as well as dozens of other way-cool Windows PowerShell people.

A quick look at the PSDiagnostics module

The PSDiagnostics module contains 10 functions that are useful when it comes to troubleshooting Windows PowerShell. To see the functions, use the Get-Command cmdlet, as shown here.

PS C:\> gcm -module psdiagnostics

CommandType     Name                                               ModuleName

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

Function        Disable-PSTrace                                    PSDiagnostics

Function        Disable-PSWSManCombinedTrace                       PSDiagnostics

Function        Disable-WSManTrace                                 PSDiagnostics

Function        Enable-PSTrace                                     PSDiagnostics

Function        Enable-PSWSManCombinedTrace                        PSDiagnostics

Function        Enable-WSManTrace                                  PSDiagnostics

Function        Get-LogProperties                                  PSDiagnostics

Function        Set-LogProperties                                  PSDiagnostics

Function        Start-Trace                                        PSDiagnostics

Function        Stop-Trace                                         PSDiagnostics

Unfortunately, there is absolutely no Help whatsoever when it comes to the PSDiagnostics module. This means that we are pretty much left to guess what it does and how it might be useful. So, what do the PSDiagnostics functions do? Typically, the way to find out about a function is to use Get-Help. Here is the output from Get-Help for the Enable-PSTrace function.

PS C:\> help Enable-PSTrace

NAME

    Enable-PSTrace

SYNTAX

    Enable-PSTrace [-Force] [-AnalyticOnly]

ALIASES

    None

REMARKS

    None

Hmm … that is not too enlightening. Well, one thing that is cool about Windows PowerShell functions is that there is a Function: PowerShell drive. Because, there is a Function: PowerShell drive, it means I can easily look at the content of a function to get a better idea of what it does. This is shown here.

Image of command output

What does the Enable-PSTrace function do? Well, it calls the Set-LogProperties function and passes either the Windows PowerShell analytic logs or the analytic and the debug logs so they can be enabled. So, we need to look at the Set-LogProperties function and see what it does. This is shown here.

Image of command output

The Set-LogProperties function is a bit longer, but one thing is clear—it calls Wevtutil and will enable the logs. From looking at it, it will also set backup, maximum log size, and other things as well.

Note   I wrote a couple of Hey, Scripting Guy! Blog posts that talked about using Wevtutil last year. One post was Automatically Enable and Disable Trace Logs using PowerShell and the other was Use PowerShell to Clear All Logs.

The Get-LogProperties function displays information about various diagnostic logs. It works as shown here.

PS C:\> Get-LogProperties Microsoft-Windows-PowerShell/Admin

Name       : Microsoft-Windows-PowerShell/Admin

Enabled    : True

Type       : Admin

Retention  : True

AutoBackup : False

MaxLogSize : 1048985600

Unfortunately, it does not accept wild cards, and when receiving wild cards in a log name, it paints the screen red, as shown here.

Image of command output

Of course, I can obtain the log names from the Event Viewer utility. All I need to do is to right-click the log, select Properties, and I can cut and paste the log name. The property page is shown here.

Image of Log Properties dialog box

But, dude, this is Windows PowerShell. And with Windows PowerShell, I do not need to supply cryptic, long, convoluted log path names because I can use the Get-WinEvent cmdlet to find my Windows PowerShell log names, and then I can pass the information to the Get-LogProperties function. This is shown here.

PS C:\> Get-WinEvent -ListLog *powershell* | Foreach {Get-LogProperties $_.logname}

Name       : Windows PowerShell

Enabled    : True

Type       : Admin

Retention  : False

AutoBackup : False

MaxLogSize : 15728640

 

Name       : Microsoft-Windows-PowerShell/Admin

Enabled    : True

Type       : Admin

Retention  : True

AutoBackup : False

MaxLogSize : 1048985600

 

Name       : Microsoft-Windows-PowerShell/Operational

Enabled    : True

Type       : Operational

Retention  : False

AutoBackup : False

MaxLogSize : 15728640

If I want to look at only one log, I use the Where-Object to filter out the results. This is shown here.

PS C:\> Get-WinEvent -ListLog *powershell* | where logname -match admin | %{Get-LogPr

operties $_.logname}

Name       : Microsoft-Windows-PowerShell/Admin

Enabled    : True

Type       : Admin

Retention  : True

AutoBackup : False

MaxLogSize : 1048985600

If you are wondering why I use the Get-LogProperties function instead of the Get-WinEvent cmdlet, here is the output from Get-Winevent.

PS C:\> Get-WinEvent -ListLog *powershell* | where logname -match admin

LogMode   MaximumSizeInBytes RecordCount LogName

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

Retain            1048985600           0 Microsoft-Windows-PowerShell/Admin

I see that both tell me the retention method and the maximum log size. But the Get-LogProperties function also tells me if the log is enabled, and if it has autobackup set.

Join me tomorrow when I will talk some more about using the functions from the PSDiagnostics module.

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 All Events from All Logs Related to PowerShell

$
0
0

Summary: Learn how to use the Get-WinEvent cmdlet to return all events from all logs related to Windows PowerShell.

Hey, Scripting Guy! Question How can I easily find events from all the event logs—both standard and the ETW logs that are related to Windows PowerShell?

Hey, Scripting Guy! Answer Use the Get-WinEvent cmdlet and use a wild card pattern for the provider name, as shown here.

Get-WinEvent -ProviderName *powershell*

Note   You may want to run the command with Admin rights because some logs require Admin rights for access.

 

Weekend Scripter: Working with Windows Error Reporting

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell 3.0 to configure Windows Error Reporting settings on Windows 8.

Microsoft Scripting Guy, Ed Wilson, is here. Well, yesterday was awesome—the Scripting Wife and I spent the day with the Dutch Windows PowerShell User group. It was an all-day user group meeting, and I made two presentations and got to listen to several other awesome sessions. It was fun, educational, and very productive.

On the train from Oslo to Norway, I spent part of the time playing around with various Windows PowerShell cmdlets—just to see what they do and to figure out how I might use them. One thing I saw was the Windows Error Reporting module. I also saw that it has three cmdlets exposed. Unfortunately, as of yet, there is no Help for this module. But hey, this is Windows PowerShell—and PowerShell is PowerShell is PowerShell! Therefore, it should just work.

Exploring the WindowsErrorReporting module

The Windows Error Reporting module contains three cmdlets. I found this by using the Get-Command cmdlets as shown here.

Note   I do not need to type the entire module name—only enough to be specific; the good thing is I can use wild cards.

PS C:\> Get-Command -Module windowserror*

CommandType     Name                                               ModuleName

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

Cmdlet          Disable-WindowsErrorReporting                      WindowsErrorRe...

Cmdlet          Enable-WindowsErrorReporting                       WindowsErrorRe...

Cmdlet          Get-WindowsErrorReporting                          WindowsErrorRe...

What is nice about this module is that I can use it to skip a step in configuring a new installation of Windows 8 because one of the steps is setting Windows Error Reporting. With a single Windows PowerShell command, I can completely skip this step.

Finding the current Windows Error Reporting setting

One way to see what the current Windows Error Reporting setting is, is to search for “Windows Error Reporting” in Windows Search, and then select the Problem Reporting Settings program that results from the search. The settings page is shown here.

Image of Problem Reporting Setting page

This is all well and good, but I prefer to use Windows PowerShell. Because Windows PowerShell always runs on my system, it is far easier than grabbing the mouse, trying to find the charms that appear and disappear, and then selecting Search and looking through a list of programs—none of which seem to contain the Windows Error Reporting moniker.

To find the current Windows Error Reporting setting, I only need to type Get-WindowsErrorReporting, as shown here.

PS C:\> Get-WindowsErrorReporting

Enabled

Note   To retrieve the Windows Error Reporting setting does not require Admin rights. To enable or to disable the Windows Error Reporting settings does require Admin rights.

Disabling or enabling Windows Error Reporting

To disable Windows Error Reporting, I use the Disable-WindowsErrorReporting cmdlets. The cmdlets return a Boolean value, True / False, depending upon the success or failure of the command in making the change. In the following command, I successfully disable Windows Error Reporting on my laptop.

PS C:\> Disable-WindowsErrorReporting

True

Disabling the Windows Error Reporting settings in this way corresponds with the Never check for solutions (not recommended) setting that appears in the following image.

Image of Problem Reporting Setting page

I can also use the Get-WindowsErrorReporting cmdlets to ensure that the command successfully completed, as shown here.

PS C:\> Get-WindowsErrorReporting

Disabled

Enabling Windows Error Reporting through Windows PowerShell

I can also use Windows PowerShell to enable Windows Error Reporting by using the Enable-WindowsErrorReporting cmdlets, as shown here.

Image of Problem Reporting Setting page

Well, I need to go. We are spending the day with the Windows PowerShell User Group Leader, Jeff Wouters, for the Dutch Windows PowerShell User Group. We are heading out to Friesland to see some of the really cool black horses—they are Teresa’s favorites. I imagine we will also have a good time discussing Windows PowerShell as well. See you tomorrow as we head back to Dortmond to see, once again, Klaus Schulte on our way to Geneva. “Have laptop … will travel.” Take care, and have a wonderful day.

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 Disable Quickly All Net Adapters

$
0
0

Summary: Use Windows PowerShell 3.0 to quickly disable all network adapters on a laptop.

Hey, Scripting Guy! Question How can I easily disable all network adapters on my Windows 8 laptop with Windows PowerShell 3.0?

Hey, Scripting Guy! Answer Use the Get-NetAdapter cmdlets to retrieve all network adapters and pipe the results to the Disable-NetAdapter cmdlets. Make sure you suppress the confirmation prompts, as shown here.

Get-NetAdapter | Disable-NetAdapter -Confirm:$false

Note   The above command requires Admin rights.

 

Weekend Scripter: The Easy Way to Manage Disk Drives

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell 3.0 to manage disk drives on his Windows 8 laptop.

Microsoft Scripting Guy, Ed Wilson, is here. Today, the Scripting Wife and I are back in Dortmund, Germany. We will spend the day with Windows PowerShell Guru Klaus Schulte. Our first day in Germany was spent in Dortmund where we had dinner at the Florian tower with Klaus, his lovely wife, Susanne, his daughter, Micah, and two sons, Janus and Marcos. The Florian tower is in the Westfalenpark, which has a great botanical garden, lots of jogging trails, and neat places for walking. The Florian tower is shown here.

Image of Florian tower

Checking the status of disk drives by using Windows PowerShell

During our European trip, I am using an external disk drive I purchased to store all of the pictures I have been taking. My new camera stores both RAW and JPG picture formats, so each picture I take consumes nearly twice the space. My laptop drive is small, and therefore, I thought an external drive would be a perfect solution for the trip.

The drive and my laptop both support USB 3.0, so speed works really well. However, there is one problem—external disks, such as the USB key fobs, appear removable to Windows. The big disk drive appears as a fixed disk, so I must go into Disk Manager to mount and dismount the drive. If I do not dismount the drive prior to shutting the laptop down, it searches forever on boot up, looking for the external drive that is missing. Using Disk Manager is a bit slow and involves the following steps.

  1. I have to go to the Start screen.
  2. Scroll over to Find and click the Administrative Tools tile.
  3. Locate and click the Computer Management MMC.
  4. Find the Storage section, and click Disk Management.
  5. After Disk Management appears, right-click the offline drive.
  6. Make it online.

Of course, there is an easier way, just type diskmgmtin the Windows PowerShell console, and the Disk Management MMC appears. Of course, one must remember that the MMC for Disk Management is diskmgmt.

Disk Management is shown here and shows my offline disk drive.

Image of Computer Management

An easier way to check on the status of disk drives is to use the Get-Disk function (cmdlet) on Windows 8 (and also on Windows Server 2012). To do this, I only need to type Get-Disk, and a list of drives is displayed in the Windows PowerShell console. This is shown here (without my extra drive plugged in).

PS C:\> Get-Disk

Number Friendly Name  Operational Status  Total Size Partition Style

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

0      INTEL SSDSA2BW160G3L      Online       149.05 GB MBR

Note  Using the Get-Disk function (cmdlets) requires Admin rights. If you run Get-Disk without Admin rights, the rather cryptic error message “Access to a CIM resource was not available to the client" appears.

When I add in my external USB disk drive and re-run the command, I see that the new drive is offline, as shown here.

PS C:\> Get-Disk

Number Friendly Name  Operational Status  Total Size Partition Style

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

0      INTEL SSDSA2BW160G3L                     Online         149.05 GB MBR

1      SAMSUNG HN-M101MBB USB Device            Offline        931.51 GB MBR 

Bring on all offline disk drives

It is easy to bring online all offline disk drives. All I need to do is to use the Get-Disk function to retrieve all disk drive information, pipe the results to a Where-Object cmdlet to filter out for isoffline disk drives. I do this first to ensure I retrieved the intended disk drive, as shown here.

Note   I have used the new Windows PowerShell where object syntax, but this command only works on Windows 8 and Windows Server 2012, so it is not an issue. Oh, by the way, ? is an alias for the Where-Object and has been since Windows PowerShell 1.0.

PS C:\> Get-Disk | ? isoffline

Number Friendly Name  Operational Status  Total Size Partition Style

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

1      SAMSUNG HN-M101MBB USB Device            Offline        931.51 GB MBR

Perfect! Now I only need to retrieve the command, and then pipe the disk object to the Set-Disk function and specify that I want the value of the IsOfflineproperty to be False in order to bring the drive online, as shown here.

Get-Disk | ? IsOffline | Set-Disk -IsOffline:$false

After I run the command, the new disk drive springs to life, and Windows Explorer opens to reveal the drive contents, so I know it worked. BUT, if I were not certain, I could always reuse the Get-Disk cmdlet, as shown here.

PS C:\> Get-Disk

Number Friendly Name  Operational Status  Total Size Partition Style

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

0      INTEL SSDSA2BW160G3L                     Online         149.05 GB MBR

1      SAMSUNG HN-M101MBB USB Device            Online         931.51 GB MBR

OK. Everything looks groovy. But to be sure, I want to view all the information about my newly “installed” drive. So I pipe the results to the Format-List cmdlet (fl is an alias for this cmdlet). The command and the associated results appear in the following image.

Image of command output

Writing to read-only drives

For some reason, the first time I did this, the drive came online as read-only. When I attempted to dump my pictures from my camera, I obviously did not have a very good experience. I finally figured it out. One of the interesting things about the Set-Disk cmdlet is that there are four parameter sets to bring a drive online or offline. These parameter sets are shown here.

Set-Disk [-Number] [-AsJob []] [-CimSession

] [-IsOffline ] [-ThrottleLimit ]

[]

 

Set-Disk [-AsJob []] [-CimSession ] [-IsOffline

] [-ThrottleLimit ] -Path []

 

Set-Disk [-AsJob []] [-CimSession ] [-IsOffline

] [-ThrottleLimit ] -UniqueId []

 

Set-Disk [-AsJob []] [-CimSession ] [-IsOffline

] [-ThrottleLimit ] -InputObject

[]

Another four parameter sets permit making a drive read-only or not. These are shown here.

Set-Disk [-Number] [-AsJob []] [-CimSession

] [-Guid ] [-IsReadOnly ] [-Signature ]

[-ThrottleLimit ] []

 

Set-Disk [-AsJob []] [-CimSession ] [-Guid

] [-IsReadOnly ] [-Signature ] [-ThrottleLimit

] -Path []

 

Set-Disk [-AsJob []] [-CimSession ] [-Guid

] [-IsReadOnly ] [-Signature ] [-ThrottleLimit

] -UniqueId []

 

Set-Disk [-AsJob []] [-CimSession ] [-Guid

] [-IsReadOnly ] [-Signature ] [-ThrottleLimit

] -InputObject []

Unfortunately, there are no parameter sets that permit bringing a disk online AND making it read-write at the same time. So if the drive comes online in read-only fashion, I need to use the Set-Disk cmdlet a second time to make it read-write. This is shown here.

Get-Disk -FriendlyName *usb* | Set-Disk -IsReadOnly:$false

Of course, I can combine the two commands as a series when bringing the drive online, as shown here.

Get-Disk | ? IsOffline | Set-Disk -IsOffline:$false

Get-Disk | ? IsReadOnly | Set-Disk -IsReadOnly:$false

When I am finished uploading pictures to my drive, and I want to put the drive away, I run the command shown here to take the drive offline, so I can unplug it. Here is the command I use.

Get-Disk -FriendlyName *usb* | Set-Disk -IsOffline:$true

See you tomorrow as the Scripting Wife and I travel to Cern to visit the Particle Accelerator. My blog post will discuss using the CIM cmdlets to explore WMI classes—it's good 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. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Find the Status of Disk Drives in Windows 8 with PowerShell

$
0
0

Summary: Learn how to use Windows PowerShell 3.0 to find the status of disk drives on Windows 8.

Hey, Scripting Guy! Question How can I check on the status of disk drives on my computer running Windows 8?

Hey, Scripting Guy! Answer Use the Get-Disk cmdlet, as shown here.

PS C:\> Get-Disk

Number Friendly Name  Operational Status  Total Size Partition Style

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

0      INTEL SSDSA2BW160G3L                     Online         149.05 GB MBR

1      SAMSUNG HN-M101MBB USB Device            Offline        931.51 GB MBR


The Visit to the Oslo PowerShell User Group

$
0
0

Summary: Ed Wilson talks about the first ever Dutch Windows PowerShell User Group.

Well, things have been very busy for Teresa and me. In Oslo, we met up with Windows PowerShell MVP Jan Egil Ring. We went out for a nice dinner and got to see the state theatre, the Parliament building, and other cool and interesting things in Oslo. Here is a picture of Jan and me.

JanEdOslo

My presentation for the Oslo Windows PowerShell user group was at the university where they have an awesome facility. Teresa was busy showing off her Windows Surface to the members of the group – many who had never seen the device. They were soon filled with envy and stated verbally that they wanted one. Here is Teresa and a few of her new found friends as they pass around the device and put it through its paces.

RunAndTeresaSurfaceOslo

The meeting was sold out, and the room was filled.

OsloPUG

I started the meeting with Highway to PowerShell, and soon had everyone in great spirits.

Some of the questions I received during the meeting involved managing a domain from a non-domain joined device (such as a Windows RT surface), or how to determine all the permissions a user in Active Directory possesses and where those permissions arise from (for example, from a group membership or from direct assignment). There were also questions about the upper limitation of concurrent CIM sessions, as well as resource utilization during a CIM session.

Dear Santa, “I’ve been good this year, really!”

Use PowerShell 3.0 and the CIM Cmdlets to Explore WMI Classes

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell 3.0 and the CIM cmdlets to explore WMI classes.

Microsoft Scripting Guy, Ed Wilson, is here. Today, the Scripting Wife and I are on the train from Dortmund to Geneva. Teresa was really smart and found tickets for us to tour the Particle Accelerator at Cern. This is a nice train ride, and in addition to being a great place to work, the scenery outside is wonderful as well.

While in Dortmund, we had time to spend the day with Windows PowerShell Guru Klaus Schulte. In addition to talking about Windows PowerShell, we walked around Dortmund taking pictures. Here is a photo of the Scripting Wife, Klaus, and his wife, Susanne, during our walk.

Photo of Teresa, Klaus, and his wife, Susanne

One of the cool things about Dortmund is they have one of the nicest burger places I have ever seen; not that we ate there, but it just looked cool, as shown here.

Photo of burger place

One of the problems with traveling on a train is how expensive wireless Internet is, and I just do not want to pay that much. This means I am limited to resources on my laptop. In the old days, I used to install the WMI SDK on my laptop so that I would have ready information about the classes. These days the WMI SDK is incorporated with the Windows Platform SDK (or maybe we call it something else), and this takes a whole lot of disk space that I really do not have. Luckily, I do not need to invest this much disk space to just find out things like writable properties or implemented methods of WMI classes. The Get-CIMClass cmdlet does an excellent job of exposing just the information I need.

Exploring WMI classes

Many WMI classes have writable properties. To see these, I need to look for the write qualifier. Well, I do not exactly have to do this—I can use the WbemTest utility to find this information. So, I type WbemTest in my Windows PowerShell console. When WbemTest opens, I have to click connectto connect to the root/cimv2 WMI namespace. Once this connects, I can now click Open Class and type Win32_Computersystem, for example. Now I have the Object Editor for Win32_ComputerSystem. I have to look at every single property individually to see the qualifiers. If a property does not possess the writequalifier, it is read-only, as shown here.

Image of Property Editor

Using the old Get-WmiObject cmdlets and piping the results to Get-Member is misleading because it reports all properties as Get;Set (but I know from WbemTest that the name property is read-only). This is shown here.

PS C:\> Get-WmiObject win32_computersystem | get-member -Name name

   TypeName: System.Management.ManagementObject#root\cimv2\Win32_ComputerSystem

 

Name MemberType Definition

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

Name Property   string Name {get;set;}

 Using the CIM classes to find WMI Writable properties

The easy way to find WMI class information is to use the Get-CimClass cmdlet. For example, to see all of the writable properties from a WMI class, such as the Win32_ComputerSystem WMI class, I can use the following code.

Get-CimClass win32_computersystem | select -ExpandProperty cimclassproperties |

where qualifiers -match 'write' | Format-table name, qualifiers

The command and associated output is shown in the following image.

Image of command output

Using Get-CimClass to find WMI methods

In the same way that I can find writable WMI properties, I can also find implemented WMI methods. A WMI class may have five methods and only three of them might have the implemented qualifier. This is because all WMI classes inherit from other WMI classes that inherit from other WMI classes (and so on and so on). Therefore, an abstract may have a SetPowerStatemethod, but the dynamic WMI class I want to use may not implement the method (indeed, I know of no WMI class that implements the SetPowerState method).

So, in the same way I looked for the write qualifier for cimclassproperties, I look for the implemented qualifier for the cimclassmethods property, as shown here.

Get-CimClass win32_computersystem | select -ExpandProperty cimclassmethods |

where qualifiers -match 'implemented' | Format-Table name, qualifiers

The code to look at the implemented methods of the Win32_ComputerSystem WMI class (along with the associated results) is shown here.

Image of command output

Well, the Scripting Wife just came back to our seats with tea and chocolate (I did not ask her to find a snack, she just did it because she is nice). I guess I need to put the laptop up for a bit. Join me tomorrow when I will talk about using Windows PowerShell and WMI to view or to set power plans. It’s cool.

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

The First-Ever Dutch PowerShell User Group

$
0
0

Summary: Ed Wilson speaking at the first-ever Dutch Windows PowerShell User Group.

The Scripting Wife and I left Oslo and traveled to Copenhagen via train. There we boarded a sleeper train, and woke up the next day in The Netherlands. We were met in Utrecht at the train by Microsoft PFE Stefan Stranger, and shuttled immediately to the first ever Dutch Windows PowerShell User Group. We arrived just in time for Stefan to make his presentation. He made an excellent presentation about using Visual Studio Team Services for source control for Windows PowerShell. He has written a module that permits checking scripts in and out directly from within the Windows PowerShell ISE. Here is a picture of Stefan. Stefan did a great job, and I have asked him to think about writing up his technique and his module into a guest Hey, Scripting Guy! blog post.

SteffanStranger

Next up was Jaap Brasser who spoke about querying Active Directory from Windows PowerShell. It was an excellent presentation and was very well received. I also asked Jaap if he would like to write up a guest blog post.

JaapInDPUG

We headed out to lunch at the Eindhoven football stadium. One of the things that was really cool, in addition to the lunch, was that we were permitted to go out into the stadium and take a couple of pictures. Here is the stadium.

EinhovenFootball

Upon returning from lunch, it was time for me to speak – I had the remainder of the afternoon and did two sessions. Of course, I began the presentation with Highway to PowerShell … here is a picture of the sold out standing room-only training room (you can see Highway to PowerShell playing on the screen on my laptop, if you look closely).

DPUG1

During the presentation, I received several really cool questions. The thing I was most impressed about (and I wished I had taken a picture) was when I asked how many people use Windows PowerShell every day – over two-thirds of the room raised their hand. When I asked how many occasionally used Windows PowerShell the remainder of the room raised their hand. Everyone in the room at least used Windows PowerShell occasionally. There were no total noobs in the room. Way cool!!!

Server for NFS Diagnostics

$
0
0

In this post, we will discuss the instrumentation available in Server for NFS in Windows Server 2012 and how it can be used to detect and diagnose any deployment and operational issues.

Event Viewer

There are quite few changes in the Server for NFS event model for Windows Server 2012. In the previous releases of Windows Server, Server for NFS logged events in to the System channel. In Windows Server 2012, Server for NFS logs the events into its own channel. The event IDs are unchanged; however event channels and provider GUIDs are different. The following figure displays the layout of the event channel, where Server for NFS logs events.



Activity Logging

Server for NFS logs the events for some of the NFS operations into Operational channel which includes:

  • Read and Write
  • Lock and Unlock
  • Mount and Unmount
  • Create and Delete

The activity logging can be enabled using the PowerShell cmdlet Set-NfsServerConfiguration.

For example, the following command enables the activity logging for mount, read, and write operations.


PS C:\> Set-NfsServerConfiguration –LogActivity mount,read,write
The activity logging can also be enabled through the Services for Network File System management snap-in. Follow these steps to enable Activity Logging in Server for NFS.
  1. Open Server Manager and then click Services for Network File System (NFS) from the Tools menu.
  2. In Services for Network File System, right-click on Server for NFS and select Properties.
  3. Switch to Activity Logging tab and select the activities you want to be logged.

 Identity Mapping Events

Server for NFS logs identity mapping related events into the IdentityMapping channel. The following are some of the critical events to watch for when local file based identity mapping is configured as the identity mapping source.

Event ID

Level

Message

Resolution

4025

Error

A duplicate ID value was found when loading . The file will not be used as a mapping source

Server for NFS performs some validations against the passwd and group files. This event is logged if multiple user accounts in the passwd file have the same user identifier (UID) or multiple group accounts in the group file have the same group identifier (GID). To resolve this issue, edit the passwd/group files to change the UID/GID on the conflicting user/group account having this issue. Use Get-NfsMappedIdentity PowerShell cmdlet to retrieve the list of users/groups having the UID/GID mentioned in the event.

4026

Error

A duplicate name was found when loading . The file will not be used as a mapping source

Edit the file specified in the event and remove the duplicate account name.

4027

Error

A syntax error was found on line when loading . The file will not be used as a mapping source

The passwd/group file specified in the event is not following the correct syntax required by Server for NFS. Edit the file and check for any errors at the line number mentioned.

4029

Warning

Mapping source update detected. File not found

Server for NFS looks for the passwd and group files at following location,  %windir%\system32\drivers\etc. Make sure that the files are present at this location and NfsService has permission to read these files.[MCJ1] 

4030

Error

has no data. The file will not be used as a mapping source.

The passwd/group file is empty. Make sure that you have right files stored at location %windir%\system32\drivers\etc or remove the files from this location if it was not intended to use mapping files as identity mapping source.

4032

Error

. Memory allocation failed when processing the file. It will not be used as a mapping source.

The system is overloaded and there is not enough memory available to process the request. Close some of the applications that are not required to free the memory.

4033

Error

. Failed to process the file. The file will not be used as a mapping source.

Unexpected error encountered while opening the file specified in the event. Check the file for correct syntax.

 

The following are some of the critical events when the identity mapping store is Active Directory, Active Directory Lightweight Directory Services or other RFC2307 compliant LDAP store.

Event ID

Level

Message

Resolution

4012

Error

Active Directory Domain Services(R) contains multiple users which match attribute .  Only one Windows(R) user should be associated with each UNIX UID. With multiple Windows users associated with one UNIX UID, Server for NFS cannot determine which Windows user is requesting access to files.  No Windows users associated with the same UNIX UID will be able to access files through Server for NFS. Try removing the duplicate UNIX UID entries.

Event 4012 indicates that the configured identity mapping store contains multiple user accounts that have an identical value for attribute uidNumber (the value is given in the event message text).

 Run the following PowerShell command to find out the user accounts having identical value for attribute uidNumber.

 Get-NfsMappedIdentity –AccountType user –Uid

 Then correct the value of the uidNumber attribute of the user accounts using the following PowerShell command.

 Set-NfsMappedIdentity –UserName -UId

4013

Error

Active Directory Domain Services(R) contains multiple groups which match attribute .  Only one Windows(R) group should be associated with each UNIX GID. With multiple Windows groups associated with one UNIX GID, Server for NFS cannot determine which Windows group to use to grant access to files.

 Try removing the duplicate UNIX GID entries.

Event 4013 indicates that the configured identity mapping store contains multiple group accounts that have an identical value for attribute gidNumber (the value is given in the event message text).

 Run following PowerShell command to find out the group accounts having identical value for attribute gidNumber.

 Get-NfsMappedIdentity –AccountType group –Gid

 Use following PowerShell command to correct the value of the gidNumber attribute of the group account.

 Set-NfsMappedIdentity –GroupName -GId

4014

Error

Active Directory Domain Services(R) contains multiple users which match attribute .  Only one Windows(R) user should be associated with each sAMAccountName. With multiple Windows users associated with one sAMAccountName, Server for NFS cannot determine which Windows user is requesting access to files.  No Windows users associated with the same sAMAccountName will be able to access files through Server for NFS. Try removing the duplicate sAMAccountName entries.

Event 4014 indicates that the configured identity mapping store contains multiple users that have an identical value for attribute sAMAccountName (the value is given in the event message text).

 Try removing the duplicate user accounts having identical sAMAccountName.

4015

Error

Active Directory Domain Services(R) contains multiple groups which match attribute .  Only one Windows(R) group should be associated with each sAMAccountName. With multiple Windows groups associated with one sAMAccountName, Server for NFS cannot determine which Windows group to use to grant access to files. Try removing the duplicate sAMAccountName entries.

Event 4015 indicates that the configured identity mapping store contains multiple groups that have an identical value for attribute sAMAccountName (the value is given in the event message text).

 Try removing the duplicate group accounts having identical sAMAccountName.

4016

Error

Server for NFS could not connect to the Lightweight Directory Access Protocol (LDAP) server for domain . Without a connection to the LDAP server, Server for NFS cannot query for Windows-to-UNIX user account mappings and cannot grant file access to any user. Verify that Server for NFS is configured to use the appropriate LDAP server using the Nfsadmin command-line tool.

Event 4016 indicates that Server for NFS is not configured to use either Active Directory Domain Services (AD DS) or any other LDAP store or User Name Mapping as a Windows-UNIX identity mapping source.

 Use Set-NfsMappingStore PowerShell cmdlet to set the identity mapping store for the Server for NFS.

4017

Error

Server for NFS could not find any Lightweight Directory Access Protocol (LDAP) accounts which match attribute . Without attribute , Server for NFS does not know the corresponding Windows user account for the Unix user and cannot grant file access to the UNIX user.%n%n Verify that the LDAP server is configured with the appropriate attributes.

Event 4017 indicates that Server for NFS could not find any Lightweight Directory Access Protocol (LDAP) accounts that match the attribute specified in the event message text.

 Add the necessary account information to the LDAP store by using New-NfsMappedIdentity or set-NfsMappedIdentity cmdlet. Then use Resolve-NfsMappedIdentity cmdlet to verify that Server for NFS is able to resolve the user account using the attribute specified in the event text.

 

The following are some of the critical events when the identity mapping store User Name Mapping (UNM) server.

Event ID

Level

Message

Resolution

1005

Error

Server for NFS could not obtain mapping information from User Name Mapping.  Server for NFS will make another attempt after minutes. Without any mapping information, Server for NFS will not be able grant file access to users. Verify the User Name Mapping service is started on the User Name Mapping server, and User Name Mapping ports are open on firewalls.

Event 1005 indicates that Server for NFS cannot obtain mapping information from User Name Mapping (UNM) server. Incorrect settings in User Name Mapping source could cause this. Use Set-NfsMappingStore PowerShell cmdlet to configure User Name Mapping server. Get-NfsMappingStore cmdlet can be used to retrieve the current configuration. Use Resolve-NfsMappedIdentity cmdlet to verify that Server for NFS can obtain the mapping information from UNM server.

1006

Error

Server for NFS is not configured for either Active Directory Lookup or User Name Mapping. Without either Active Directory Lookup or User Name Mapping configured for the server, or Unmapped UNIX User Access configured on all shares, Server for NFS cannot grant file access to users. Configure Server for NFS for either Active Directory Lookup or User Name Mapping using the Nfsadmin command-line tool, or Unmapped UNIX User Access using the Nfsshare command-line tool.

Event 1006 indicates that Server for NFS is not configured for either Active Directory Lookup or User Name Mapping.

If you have configured shares on the Server for NFS to use ‘Unmapped UNIX User Access’ mode, you may ignore this event.  Otherwise, to solve this problem, configure Server for NFS to use an identity mapping source using Set-NfsMappingStore PowerShell cmdlet. To verify that the mapping store is configured correctly, use Get-NfsMappingStore cmdlet.

1056

Error

Server for NFS could not obtain updated mapping information from User Name Mapping.  Server for NFS will continue to use the mapping information it has and make another attempt after minutes. If this problem persists, Server for NFS mapping information may become significantly out-of-date and may not be able grant file access to users. Verify that the User Name Mapping service is started either locally or on the remote server, and that User Name Mapping ports are open on firewalls.

Event 1056 indicates that Server for NFS cannot obtain mapping information from User Name Mapping (UNM) server. Incorrect settings in User Name Mapping source could cause this. Use Set-NfsMappingStore PowerShell cmdlet to configure User Name Mapping server. Get-NfsMappingStore cmdlet can be used to retrieve the current mapping store configuration. Use Resolve-NfsMappedIdentity cmdlet to verify that Server for NFS can obtain the mapping information from UNM server.

 

Admin Channel Events

The Server for NFS logs critical events that need admin’s intervention into Admin channel. Following are some of the critical events and recommended resolution steps.

Event ID

Level

Message

Resolution

1059

Error

Server for NFS could not register with RPC Port Mapper on all requested port/protocol combinations.  Server for NFS will attempt to continue but some NFS clients may not function properly. Network File System (NFS) clients discover NFS servers by querying the port mapper for a remote server (also known as Portmap and Rpcbind).  NFS clients may not be able to discover and communicate with Server for NFS on this computer.

These events indicate that other programs might be using some of the TCP/IP ports that are required by Server for.

 Determine if Server for NFS has registered all protocols

 To determine the ports and transports that Server for NFS uses, at an elevated command prompt on the affected server, type rpcinfo.

 Server for NFS registers on port 2049 for udp, tcp, udp6, tcp6

 Make this TCP/IP port available and restart Server for NFS.

 To make TCP/IP port 2049 available and restart Server for NFS, use the following procedure:

 1. At an elevated command prompt, type “netstat -a -b –o” to display all connections with their associated executables and processes.

 2. Resolve port allocations conflicting with the NFS ports identified in Step 1 by stopping conflicting services, or programs.

 3. Type “nfsadmin server stop”.

 4. Type “nfsadmin server start”.

 

1060

Error

Server for NFS could not register the Network File System (NFS) protocol on the specified port (%5). Status: %6.  Server for NFS is will attempt to continue.  At least one successful NFS port registration is required to start Server for NFS but some NFS clients may not function properly without this specific port registration. Verify that no other programs have registered with RPC Port Mapper with the following parameters. Program Name:%1 Program Number%2 Version:%3 Protocol: %4 Port:%5

1064

Warning

Server for NFS cannot initialize the volume with drive letter %1 for sharing. Network File System (NFS) shared resources on the volume will not be available to NFS clients. Windows(R) may be low on system resources.  Try increasing available system resources by closing programs, then restart Server for NFS manually.

Event 1064 indicates that Server for NFS cannot provision the volume for sharing; therefore, shared resources on the volume will not be available to NFS clients. The likely cause is that the computer is short of resources.

 To resolve this issue increase available system resources using the following procedure:

 1. Close all programs and stop unnecessary services on the affected server.

 2. At an elevated PowerShell prompt , type “nfsadmin server stop”.

 3. Type “nfsadmin server start”.

 To verify Server for NFS is sharing files, use the following procedure:

 1. On the affected server, type Get-NfsShare.

 2. Verify that the list of shared resources is correct.

1069

Error

Server for NFS could not establish a connection with configured NIS server

Event 1069 indicates that Server for NFS is unable to access the Network Information Service (NIS) store where the netgroup configuration is stored. The most likely causes are:

 • NFS server is not configured appropriately to access NIS based netgroups.

 • There is a network connectivity issue between the Server for NFS and the NIS server.

 If Server for NFS is unable to access the netgroup store, determine if the location of the NIS NetGroup Source is accurate by using the following procedure:

 1. At PowerShell prompt on the affected server, type Get-NfsNetgroupStore.

 2. Verify that the NISDomain, and NISServer  are configured correctly.

 3. Verify that network connectivity exists between the Server for NFS and the NIS server where netgroups are configured as follows:

 • Use the rpcinfo.exe tool to verify that the NIS server is accessible over the network. To check if the source computer is accessible and the NIS service is registered on the source computer, type the following command, where is the name of the NIS server: rpcinfo . 

• The NIS service should appear in the output of this command as RPC program number 100004 and protocol version 2.

 Verify Server for NFS is configured appropriately to access NIS server

 Verify that Server for NFS is correctly configured to access the NIS server as follows:

 1. In PowerShell window, run Get-NfsServerConfiguration cmdlet.

 2. Verify that Protocol for NIS is UDP, TCP, or both, and is compatible with the protocol allowed at the NIS source computer as determined from the output of the command rpcinfo.exe .

 To verify that issue is resolved, use Get-NfsNetGroup cmdlet. You should be able to retrieve the netgroups from the netgroup store.

1071

Warning

Server for NFS was unable to obtain security information for the configured UnmappedUnixUserUsername user account %1. Check that the user account %1 is valid and meets all configured security policies. There may be additional information in the Windows Security event log. Server for NFS will attempt to revert to the default anonymous account. MSV Status: %2, SubStatus: %3S4U Status: %4, SubStatus: %5

Event 1071 indicates that Server for NFS was unable to obtain a logon token for the account used to process anonymous logons or for UNIX UIDs that do not have an explicit mapping. The event message details the account that led to the problem report. Ensure that the account is valid and can be used to perform a successful logon.

 

 

1072

Warning

Server for NFS was unable to obtain security information for the GSS user account %1. Check that the user account %1 is valid and meets all configured security policies. There may be additional information in the Windows Security event log. MSV Status: %2, SubStatus: %3 S4U Status: %4, SubStatus: %5

Event 1072 indicates Server for NFS was unable to obtain a logon token for the account used to access the NFS server when using an RPCSEC_GSS based identity. The event message details the account that led to the problem report. Ensure that the account is valid and can be used to perform a successful logon.

1073

Warning

Server for NFS was unable to obtain or refresh security information for the user account %1. Check that the user account %1 is valid and meets all configured security policies. There may be additional information in the Windows Security event log.%n%nMSV Status: %2, SubStatus: %3%nS4U Status: %4, SubStatus: %5

Event 1073 indicates Server for NFS was unable to refresh an access token. The event message details the account that led to the problem report. Ensure that the account is valid and can be used to perform a successful logon.

 

4021

Error

The Server for NFS was unable to begin monitoring of NFS related cluster events (%1). The Server for NFS will continue in a non-clustered mode.

These events indicate that either the Cluster Service is not running or the computer is low on resources.

 Determine if the Cluster Service is running as follows:

 1. At command prompt on the affected server, type services.msc.

 2. Check if Cluster Service is running.

 

4022

Error

The Server for NFS thread monitoring NFS related cluster events ended unexpectedly (%1). The Server for NFS will continue in a non-clustered mode.

4023

Warning

Server for NFS encountered an error condition when checking for the presence of Failover Clustering (%1) and will continue to operate but in a non-clustered configuration only. To re-detect Failover Clustering and allow Server for NFS to operate in a clustered configuration, Server for NFS should be restarted using either the Services for Network File System (NFS) administrative tool or nfsadmin server stop and nfsadmin server start

 

Performance Counters

 Server for NFS-NFSv4 Statistics

This performance counter set includes performance counters related to compound requests processed by Server for NFS. It also includes a performance counter indicating the count of virtual servers hosted by Server for NFS.

Name

Description

Total Compound Requests

Total number of compound requests processed by Server for NFS since startup

Successful Compound Responses

Total number of compound requests succeeded since Server for NFS started

Failed Compound Responses

Total number of compound requests failed since Server for NFS started

Total Virtual Servers

Current count of virtual servers hosted by the Server for NFS. This counter is incremented when virtual server is successfully started and decremented on virtual server stop. This counter will be set to one in non-cluster case. In case of cluster, there will be one instance of virtual server per Server for NFS resource.

 

Server for NFS-Netgroup

Name

Description

Failures Communicating With NIS

Number of time the Server for NFS failed to communicate with the NIS server.

 

Server for NFS-User Mapping

LDAP refers to Active Directory, Active Directory Lightweight Directory Services or any other RFC 2307-based LDAP Store. UNM Server refers to User Name Mapping server.

Name

Description

Total LDAP Requests

Number of LDAP query requests made by the Server for NFS since startup.

Total LDAP successes

Count of LDAP lookup requests which resulted in successful UID/GID to account name or account name to UID/GID lookup.

Total LDAP Failures

Count of LDAP lookup requests which failed to retrieve the identity mapping information from LDAP store.

Total LDAP Requests Per Second

Number of LDAP lookup requests performed  per second by the Server for NFS.

Total UNMP Requests

Number of user name mapping lookup requests performed by the Server for NFS since startup.

Total UNMP Failures

Count of user name mapping lookup request issued by the Server for NFS which resulted in failure. The failure reason could be anything like mapping does not exist or communication failure with the UNM server.

Total UNMP Successes

Count of mapping lookup request made against UNM Server which resulted in successful mapping information.

Total UNMP Requests Per Second

Count of UNMP mapping lookup requests issued by the Server for NFS per second.

Average LDAP Lookup Latency

Average amount of time taken by Server for NFS to resolve UID/GID to account name from the LDAP mapping store and vice versa. It is the total time spent doing the lookup in the LDAP mapping store divided by the total number of mapping lookup requests made to the LDAP mapping store.

Maximum LDAP Lookup Latency

Maximum amount of time taken by Server for NFS to resolve the identity mapping in the LDAP mapping store.

Average UNMP Lookup Latency

Average amount of time taken by Server for NFS to resolve the UID/GID to account name from UNMP mapping store and vice versa. It is basically the total time spent doing the lookup in the UNMP mapping store divided by the total number of mapping lookup requests made by the server to the UNMP mapping store.

Maximum UNMP Lookup Latency

Maximum amount of time spent by Server for NFS to resolve the identity mapping from the UNMP mapping store.

 

Server for NFS-NFSv4 Read Write Statistics

Name

Description

Total cached MDL Reads

Number of times the read operation is performed using a memory descriptor list (MDL) from the system cache manager.

Total Fast IO Reads

Number of times the read operation is performed using buffered IO from the system cache manager.

Total Unstable Writes

Count of NFS unstable writes performed by Server for NFS.

Average Fast IO Read Latency

Average time taken by Server for NFS to perform read operation using buffered IO from the system cache manager. It is the total time taken by the server performing all buffered IO reads divided by the number of buffered IO reads performed so far.

Average Non Fast IO Read Latency

Average amount of time taken by Server for NFS to perform read operations using IRP based IO.

 

Server for NFS-NFSv4 Request/Response Sizes

Name

Description

Maximum Size of NTFS Reads

Maximum size in bytes of the read request performed by Server for NFS.

Minimum Size of NTFS Reads

Minimum size in bytes of the read request performed by Server for NFS.

Maximum Size of NTFS Writes

Maximum size in bytes of the write request performed by Server for NFS.

Minimum Size of NTFS Writes

Minimum size in bytes of the write request performed by Server for NFS.

Maximum Compound Request Size

Maximum size in bytes of the NFS compound request.

Average Compound Request Size

Average size in bytes of the NFS compound request.

Maximum Compound Reply Size

Maximum size in bytes of the NFS compound reply.

Average Compound Reply Size

Average size in bytes of the NFS compound reply.

Maximum Compound Operations in Request

Maximum number of operations in a single NFS compound request.

Average Compound Operations in Request

Average number of operations in NFS compound request.

 

Server for NFS-NFSv4 Throughput

Name

Description

NFS Compounds Processed/Sec

Number of NFS compound requests processed per second.

 

Server for NFS-NFSv4 Operation Statistics

Server for NFS- NFSv4 Operation Statistics performance counter set is reported for each compound operation. There is one instance of the following of performance counters for each compound operation in the Server for NFS-NFS v4 implementation.

Name

Description

Count Of Operations Processed

Count of this NFS4 compound operations processed by the Server for NFS so far.

% Operations At Dispatch

This counter is not used in the current release.

Average Number of Times Operation requeued

Average Number of times this compound operation was re-queued for processing by the worker thread.

Reply Packet Not Cached Count

Number of times reply packet was not cached when requested by the client.

Average latency

Average amount of time taken by the server to execute this compound operation. This includes time taken to decoding the request and executing the operation.

 

Server for NFS -Session and Connection Statistics

Name

Description

Active Sessions Count

Number of active sessions with Server for NFS.

Active Connections Count

Number of active connections with Server for NFS.

Total Bad Session Requests

Number of session requests (OP_CREATE_SESSION) received by the Server for NFS so far with invalid arguments to operation.

KRB5 RPCSEC_GSS Requests Count

Number of requests received by Server for NFS with krb5 RPCSEC_GSS authentication.

KRB5I RPCSEC_GSS Requests Count

Number of requests received by Server for NFS with krb5i RPCSEC_GSS authentication.

KRB5P RPCSEC_GSS Requests Count

Number of requests received by Server for NFS with krb5p RPCSEC_GSS authentication.

AUTH_NONE Requests Count

Number of requests received by Server for NFS with AUTH_NONE authentication.

AUTH_UNIX Requests Count

Number of requests received by Server for NFS with AUTH_UNIX authentication.

Client With Sessions

Current count of clients that have session established with Server for NFS.

Total Client With Sessions

Number of clients that have created a session to Server for NFS since startup.

Number of times admin forcefully closed a session

Number of sessions force-closed by an administrator (Disconnect-NfsSession cmdlet).

Number Of Times Admin Revoked State

Number of open/lock states force-closed by an administrator (Revoke-NfsOpenFile / Revoke-NfsClientLock cmdlets).

Lease Expiry Revoke State Count

Number of open/lock states revoked by Server for NFs due  to the lease expiry.

Client Sessions Using Back Channel

Number of client sessions using back channel.

Clients Requesting SP4_MACH State Protection

Number of clients requesting SP4_MACH state protection.

Clients Requesting SP4_NONE State Protection

Number of clients requesting SP4_NONE state protection.

Clients Requesting SP4_SSV State Protection

Number of clients requesting SP4_SSV state protection.

Clients Requesting Bind Principal To State

Number of clients requesting bind principal to state.

Clients Requesting Persistent Session

Number of clients requesting a persistent session.

Number of clients requesting READW_LT

Count of requests for READW_LT.

Number of clients requesting WRITEW_LT

Count of requests for WRITEW_LT.

Special Anonymous State ID Use Count

Count of requests for special anonymous state ID.

Special Read Bypass State ID Use Count

Count of requests for special read bypass state ID.

Special Current State ID Use Count

Count of requests for special current state ID.

 

Group Policy in Windows Server 2012: Overview

$
0
0

Now that Windows 8 and Windows Server 2012 have been released, we’d like to share with you some of the exciting enhancements that we’ve added for Group Policy.

While we hear plenty of great things from people who use Group Policy, we also hear complaints. By far the largest complaint we hear about Group Policy has to do with troubleshooting GP. Our main goal for Server 2012 was to improve the troubleshooting experience.

We added 3 new features to make your life as a GP admin easier. In the next week we’ll detail each of these improvements in their own blog post, but for now here’s a quick overview.

· Remote GP Update: Allow you to remotely update policy on one client computer or an entire OU, through the GPMC or through Powershell

· GP Results Report improvements: We’ve changed the layout and added a bunch of new information to the results report, including relevant events, specific callouts for disabled user/computer sections, extension processing time, and more!

· Infrastructure Status: We’ve made it easy to check in on replication status to make sure GPOs are propagating properly.

If you just can’t wait to learn more, there’s additional documentation of new features here: http://technet.microsoft.com/en-us/library/hh831791.aspx

RemoteFX Features for Windows 8 and Windows Server 2012

$
0
0

Hi, I’m Shanmugam Kulandaivel, a senior program manager on the Remote Desktop Virtualization team. As most of you know, both the Windows 8 and Windows Server 2012 operating systems are available in multiple editions.  I’d like to use this blog post to provide details on the features of Microsoft RemoteFX® that are supported in each edition of Windows 8 and Windows Server 2012. 

Before I provide the details, I’d like to start with a summary:

  • Client computers (the endpoint PC that you are accessing the remote computer from) running any edition of Windows 8 or Windows Server 2012 support all RemoteFX features, including the ability to connect to RemoteApp, redirect USB devices by using  RemoteFX USB Redirection, and support WAN networks.

 

  • Remote computers (the virtual machine or desktop you are accessing) running Windows 8 Enterprise provide the best user experience and support all management features. Therefore, Windows 8 Enterprise is the only supported edition for use with Windows Server 2012 virtual desktop collections (VDI).

With that summary in mind, let’s first look at the features that Windows 8 and Windows Server 2012 editions support when running on client computers, and then we’ll look at the features that Windows 8 and Windows Server 2012 support when running on remote  computers.

RemoteFX features on client computers

Client computer refers to the computer that the user is physically logged on to. Users use Remote Desktop Connection (RDC) on the client computer to connect to remote computers. The following table lists the features that are supported on client computers running any one of the different editions of Windows 8 and Windows Server 2012.

 

* Requires that the remote computer be configured with RemoteFX vGPU.

The key takeaway is that users can use any edition of Windows 8 or Windows Server 2012 on their client computers and experience all the new features of RemoteFX.

RemoteFX features on remote computers

Remote computers are the computers that users connect to. Remote computers can be a physical computer, a Remote Desktop Session Host server, or a virtual machine. The following table lists the features that are supported on remote computers running any one of the different editions of Windows 8 and Windows Server 2012.

 

While this might seem like lot of specifics to remember, in reality, the feature differentiation is very simple. You just need to remember the following summary when deciding which edition to use for your virtual machine-based desktop deployment:

  • Client computers running any edition of Windows 8 or Windows Server 2012 support all RemoteFX features, including the ability to connect to RemoteApp, redirect USB devices by using RemoteFX USB Redirection, and support WAN networks.

 

  • Remote computers running Windows 8 Enterprise provide the best user experience and support all management features. Therefore, Windows 8 Enterprise is the only supported edition for use with Windows Server 2012 virtual desktop collections (VDI).

I hope this information is useful and answers the questions that you have on this topic. If you have more questions, please feel free to post a new thread in the RDS & TS forum.


PowerTip: Open Windows 8 Control Panel Items from PowerShell

$
0
0

Summary: Learn how to open Windows 8 Control Panel items from within Windows PowerShell.

Hey, Scripting Guy! Question How can I open a Control Panel item, such as Windows Firewall, from within Windows PowerShell?

Hey, Scripting Guy! Answer Use the Show-ControlPanelItem cmdlet. To get a list of openable Control Panel items, use the Get-ControlPanelItem cmdlet, as shown here.

Show-ControlPanelItem *firewall*

Get-ControlPanelItem 'Windows Firewall'

Next Stops for the Windows Server 2012 Community Roadshow: United States, Australia, Singapore, Malaysia, and Japan! (And we’ve added dates in February!)

$
0
0

Hi, this is
Christa Anderson, Community Lead for the Windows Server and System Center Group, back with this week’s updates on the next stops in the Windows Server 2012 Community Roadshow. This time, I’m happy to announce we’ve got four more events in the United States, new cities in Australia, and events in Singapore, Kuala Lumpur and Tokyo.

Register now for an event in Houston, Texas on November 27

Register now for an event in Austin, Texas on November 29

Register now for an event in San Antonio, Texas on November 30

Register now for an event in Parramatta, NSW Australia on December 3

Register now for an event in Brisbane, QLD Australia on December 5

Register now for an event in Singapore on December 5

Register now for an event in Kuala Lumpur, Malaysia on December 6

Register now for an event in Redmond, Washington on December 7

Register now for an event in Tokyo, Japan on December 8

                                             

As always, seating is limited, so reserve your spot now to get free technical Windows Server 2012 training from Microsoft MVPs, some of the smartest people in the business! We continue to schedule events in many more cities to deliver training and more events are submitted each week. If you don’t see an event coming to a city near you in the list on the Web site, please request it here: https://ws2012rocks.msregistration.com/CityRequest.aspx. If you’re an MVP who’d like to present about Windows Server 2012 for the roadshow, then you’re welcome to create an event on the same site.

Due to continuing demand, we’ve extended the roadshow into February. Please check the site to find an event date in a city near you. For more information on the Roadshow, to register,
or to find out if there is an event coming to a city near you, go to ws2012rocks.msregistration.com

I hope you can join us!

Christa Anderson

Community Lead, Windows Server and System Center Group

Stay tuned for a three part blog series on 3 new features in Windows Server 2012 Group Policy

$
0
0

Hey everyone,

The Group Policy team has a series of blog posts lined up, Group Policy in Windows Server 2012: Overview to cover 3 new features in Windows Server 2012 that should make your life as a Group Policy admin easier. In the next week they will detail each of these improvements covering:

  • Remote GP Update: Allow you to remotely update policy on one client computer or an entire OU, through the GPMC or through Powershell
  • GP Results Report improvements: We’ve changed the layout and added a bunch of new information to the results report, including relevant events, specific callouts for disabled user/computer sections, extension processing time, and more!
  • Infrastructure Status: We’ve made it easy to check in on replication status to make sure GPOs are propagating properly.

If you miss hearing from this team, let them know.... They have been a little quiet lately. So, give them a warm welcome back by shooting over to their blog and posting some comments.

Let them know what topics you would like to hear from them on. I think you GP Admins can probably think of lots of topics you would like to hear more from them on. 

Hope everyone in the US at least enjoyed the holiday last week,

Kevin Beares
Senior Community Lead
Windows Server and System Center Group

Use PowerShell and WMI or CIM to View and to Set Power Plans

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, shows how to use Windows PowerShell and WMI or CIM cmdlets to view and to set power plans on his laptop.

Microsoft Scripting Guy, Ed Wilson, is here.

Tomorrow, the Scripting Wife and I are at the Microsoft Technology User Group in Oslo, Norway. I will be talking about using Windows PowerShell 3.0 to manage a remote Windows 8 workstation. Last night we were in Stockholm with the Stockholm PowerShell User Group, and today is a travel day.  

We are taking the beautiful train from Stockholm to Oslo. In addition to being a great way to travel, it provides stunning views, and a comfortable compartment within which to write Hey, Scripting Guy! Blog posts.

All these trains, user group presentations, and more trains, got me to thinking: I like to have my laptop running full power when making a user group presentation—of course, I am always plugged in to power while doing so. When I am on a train, or in a plane, I generally am running on battery (although most of the trains we have been riding on also have power at the seat). So, when plugged into electricity, I want to run the laptop on full power; when running on battery, I want to run the laptop on maximum conserve power. I think this calls for a quick Windows PowerShell script. But first, I need to spend a bit of time talking about WMI, CIM, and the Win32_PowerPlan WMI class.

Detecting laptop power plans

Windows 7 introduced the Win32_PowerPlan WMI class. This WMI class resides in the Root\Cimv2\Power WMI namespace. Because this is not the default Root\Cimv2 namespace, this means that any script or code to query from this class must include the Root\Cimv2\Power namespace in the code. To enumerate the available power plans on the laptop, I can use either Get-WmiObject, or, in Windows PowerShell 3.0, I can use the Get-CIMInstance class. Either one works and using one as opposed to the other, in this case, is a simple matter of substituting one name for the other. The Get-WmiObject command is shown here, where gwmi is an alias for the Get-WmiObject cmdlet, -NS is a parameter alias for –NameSpace, select is an alias for the Select-Object cmdlet, ft is an alias for the Format-Table cmdlet, and –a is a partial parameter for –autosize.

gwmi -NS root\cimv2\power -Class win32_PowerPlan | select ElementName, IsActive | ft -a

ElementName      IsActive

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

Balanced            False

High performance     True

Power saver         False

An expanded version of the command is show here. This is still a single-line command with complete cmdlet names and parameter names. I have broken it at the pipe character for readability:

Get-WmiObject -Namespace root\cimv2\power -Class win32_PowerPlan |

Select-Object -Property ElementName, IsActive |

Format-Table -Property * -AutoSize

If I do a direct substitution, from the short form of the command to Get-CimInstance, an error arises when I run the code. This is because Get-CimInstance does not have a parameter alias NS for the NameSpace parameter (by the way, Get-CimInstance uses –classname instead of –class for the complete parameter name as well). The error is shown here.

Image of command output

The easy solution: Just use –N instead of the parameter alias –NS. This technique is shown here.

PS C:\> Get-CimInstance -N root\cimv2\power -Class win32_PowerPlan | select ElementNa

me, IsActive | ft -a

 

ElementName      IsActive

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

Balanced            False

High performance     True

Power saver         False

Making a particular power plan active

To make a particular power plan active, I only need to call the Activatemethod from a specific instance on a Win32_PowerPlan WMI class. What this means is that I return a specific power plan via the Win32_PowerPlan WMI class, and then call the Activatemethod. This is really easy by using the Get-WmiObject cmdlet—it is a bit more difficult by using the CIM classes.

Note  The new way to work with WMI classes is to use the new CIM interface. The OLD WMI COM interface is now legacy. This means that you should begin learning the new CIM cmdlets, and, as far as possible, use them instead of the legacy methods. The CIM cmdlets are much more powerful, and once mastered, they are actually easier to use and to understand. For a good overview of the CIM cmdlets see this article.

I will illustrate each technique in the following sections.

Using Get-WmiObject

First, by using the Get-WmiObject cmdlet, I add a filter that returns only one power plan. In this case, I want to return only the Power Saver power plan. I store the returned object in a $p variable. Once I have done this, I call the Activatemethod, as shown here.

$p = gwmi -NS root\cimv2\power -Class win32_PowerPlan -Filter "ElementName ='Power Saver'"

$p.Activate()

I can certainly use the following query to confirm that the change worked, but it is obvious when the laptop screen dramatically dims. J

gwmi -NS root\cimv2\power -Class win32_PowerPlan -Filter "IsActive = 'true'"

If I am in doubt, I can also verify in the Power Options dialog box, as shown here.

Image of Power Options dialog box

Using the CIM cmdlets to set the power plan on my laptop

The procedure to set the power plan on my laptop is exactly the same whether I use the CIM cmdlets or whether I use the Get-WmiObject cmdlet—I must return an instance of the power plan, and I must make it active.

However, the CIM cmdlets do not permit calling methods from “de-serialized” or “non-live” objects. It is not a good idea and can actually lead to potential instability. The old WMI COM interface does permit this calling of methods from the non-live objects. When I use Get-WMiObject and return a list of processes (via Win32_Process), the process objects are no longer live. In fact, I could stop processes, or start new processes, and the changes are not represented in the variable containing the returned process objects.

This is something people often forget. If I then take one of these offline processes and attempt to terminate the process, and the process no longer exists, then an error arises. By using CIM, this problem never happens because I cannot call methods on the returned objects. Instead, I must use the Invoke-CimMethod cmdlet. The cmdlet is easy to use, and I will follow the same procedure I used with Get-WmiObject.

$p = Get-CimInstance -Name root\cimv2\power -Class win32_PowerPlan -Filter "ElementName = 'High Performance'"          

Invoke-CimMethod -InputObject $p -MethodName Activate

Note  One thing I should mention is that the new CIM interface is AMAZINGLY FAST! Whereas the call using Get-WmiObject took nearly 10 seconds to return, the Invoke-CimMethod call returned immediately.

Join me tomorrow when I will write the actual script that will set the appropriate power plan for my laptop.  

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

Revenge of Y2K and Other News

$
0
0

Hello sports fans!

So this has been a bit of a hectic time for us, as I'm sure you can imagine. Here's just some of the things that have been going on around here.

Last week, thanks to a failure on the time servers at USNO.NAVY.MIL, many customers experienced a time rollback to CY 2000 on their Active Directory domain controllers. Our team worked closely with the folks over at Premier Field Engineering to explain the problem, document resolutions for the various issues that might arise, and describe how to inoculate your DCs against a similar problem in the future. If you were affected by this problem then you need to read this post. If you weren't affected, and want to know why, then you need to read this post. Basically, we think you need to read this post. So...here's the link to the AskPFEPlat blog.

In other news, Ned Pyle has successfully infiltrated the Product Group and has started blogging on The Storage Team blog. His first post is up, and I'm sure there will be many more to follow. If you've missed Ned's rare blend of technical savvy and sausage-like prose, and you have an interest in Microsoft's DFSR and other storage technologies, then go check him out.

Finally...you've probably noticed the lack of activity here on the AskDS blog. Truthfully, that's been the result of a confluence of events -- Ned's departure, the Holiday season here in the US, and the intense interest in Windows 8 and Windows Server 2012 (and subsequent support calls). Never fear, however! I'm pleased to say that your questions to the blog have been coming in quite steadily, so this week I'll be posting an omnibus edition of the Mail Sack. We also have one or two more posts that will go up between now and the end of the year, so there's that to look forward to. Starting with the new calendar year, we'll get back to a semi-regular posting schedule as we get settled and build our queue of posts back up.

In the mean time, if you have questions about anything you see on the blog, don't hesitate to contact us.

Jonathan "time to make the donuts" Stephens

Viewing all 2283 articles
Browse latest View live


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