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

Use PowerShell Desired State Configuration to Set Time Zone

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell Desired State Configuration to set the time zone.

Microsoft Scripting Guy, Ed Wilson, is here. The weather is cold today in Charlotte. Not exactly freezing, but cold enough to merit a nice cup of English Breakfast tea with bits of strawberry leaf, blueberry leaf, orange peel, hibiscus flower, and a cinnamon stick. The tea is robust, and it goes well with homemade blueberry scones. It is a good morning for reflection.

Believe it or not, time zone configuration is still an issue at times. Especially, when it comes to correlating logging, or running scheduled tasks or other such activities. What normally happens is that the person configuring the server simply forgets to change the time zone from the default setting (-8 GMT). Everything continues to hum along swimmingly until...boom!—it does not. Luckily, the Wave 9 release of the Desired State Configuration Resource Kit contains a TimeZone resource.

But before I get into that, I want to first do a little checking up on the time zone settings.

Working with time zones in Windows PowerShell

In my life as a computer professional, dates and times have been a continuous issue for me. I can reach all the way back to the days when a date was stored in three fields in a database, and a time was stored in three more fields. Creating a report mandated munging together these six fields.

Sure, the creation of a DateTime object has been great. Sure, using the Get-Date cmdlet is easy and wonderful. However, there are still issues and challenges. Time zones, for one, are a major pain— well, not a major pain, but they are not as simple as they could be.

Let's start with checking the date. It would appear that all I need to do is to run the Get-Date cmdlet in a remote session, and everything is groovy. So first I query Active Directory and return a list of computers. Next, I use the Invoke-Command cmdlet to run the Get-Date cmdlet inside a script block. Everything is easy, everything is good. Here is the command and the results:

PS C:\> $cn = (Get-ADComputer -Filter *).name 

PS C:\> icm -cn $cn {get-date}

Monday, January 5, 2015 1:52:02 PM

Monday, January 5, 2015 1:52:02 PM

Monday, January 5, 2015 1:52:02 PM

Monday, January 5, 2015 1:52:02 PM

Hmmm…I know that at least one of the remote servers is set to the wrong time zone, but using Get-Date does not tell me that. Why? Well, Windows PowerShell is smart. In this case, it is too smart because it automatically displays a remote date and time by using the local time zone information. Most of the time, this is great. Just not today.

The next thing I do is use Windows PowerShell remoting to figure out what time zones the remote servers are configured with. I call use the TimeZoneInfo .NET Framework class. Following is the command I use. (Note that I collected my server names in the previous command, and I stored the names in the $cn variable. This permits me to reuse it easily.)

PS C:\> icm -cn $cn -ScriptBlock {[timezoneinfo]::Local.DisplayName}

(UTC-08:00) Pacific Time (US & Canada)

(UTC-05:00) Eastern Time (US & Canada)

(UTC-05:00) Eastern Time (US & Canada)

(UTC-05:00) Eastern Time (US & Canada)

Ah! I see that one of my servers is in fact set to Pacific Time. If I want to get the actual display time from the remote servers, I need to use an old-fashioned command. To run this command, I am going to use the Invoke-Expression cmdlet. Invoke-Expression is not recommended because it can have unintended consequences if one is not careful.

Invoke-Expression executes a string as if it were a command. This is actually great for what I am about to do (which is a real left handed way of doing things such as creating a cmd prompt, and then running the time command). There is almost never a good reason for doing this.

   Note  The Windows PowerShell team has a blog post titled Invoke-Expression considered harmful.

PS C:\> icm -cn $cn -ScriptBlock {Invoke-Expression "cmd.exe /c time /t"}

11:01 AM

02:01 PM

02:01 PM

02:01 PM

The DSC TimeZone resource

Enter the world of Windows PowerShell Desired State Configuration (DSC). By using the TimeZone resource, I can create a simple script to set the time zone configuration on my local and remote servers easily.

   Note  Today’s script follows the same pattern as the SetPowerShellExecutionPolicy.ps1 script I wrote for yesterday’s post,
   Use DSC Resource to Configure PowerShell Execution Policy. Refer to that post for more details.

The first thing I do is use the Configurationkeyword and specify a name for my configuration. I next define a couple of parameters—one for the computers (target nodes) and one for the specific time-zone name. I then specifically import the DSC resource. This is required because the xTimeZone DSC resource is not a standard resource, and therefore, it is not automatically loaded. Here is that portion of the script:

#Requires -version 4.0

Configuration SetTimeZone

{

    Param

    (

        #Target nodes to apply the configuration 

        [String[]]$NodeName = ((Get-ADComputer -Filter *).name),

        [Parameter(Mandatory = $true)]

        [ValidateNotNullorEmpty()]

        [String]$SystemTimeZone

    )

    Import-DSCResource -ModuleName xTimeZone

Now I define my action for each node. To do this, I use the Nodekeyword, and I specify the computer names stored in the $NodeName variable that I populated with my Get-ADComputer command. I call the xTimeZone resource, and I specify my time zone. Here is that portion of the code:

Node $NodeName

    {

        xTimeZone TimeZoneExample

        {

            TimeZone = $SystemTimeZone

        }

    }

I call the configuration and specify an output path for the creation of the MOF files. I also specify my time zone via the SystemTimeparameter. This value takes the ID property that is available from the following command:

[timezoneinfo]::Local.id

If I want an enumeration of all of the available time zones, I can use GetSystemTimeZonesstatic method as shown here:

[timezoneinfo]::GetSystemTimeZones().id

The last thing I need to do is to start the actual DSC configuration. To do this, I use the Start-DSCConfiguration cmdlet while specifying the path that I used earlier in addition to a few parameters:

SetTimeZone -output C:\serverConfig -SystemTime "Eastern Standard Time"

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

The complete configuration script is shown here:

#Requires -version 4.0

Configuration SetTimeZone

{

    Param

    (

        #Target nodes to apply the configuration 

        [String[]]$NodeName = ((Get-ADComputer -Filter *).name),

        [Parameter(Mandatory = $true)]

        [ValidateNotNullorEmpty()]

        [String]$SystemTimeZone

    )

    Import-DSCResource -ModuleName xTimeZone

 

    Node $NodeName

    {

        xTimeZone TimeZoneExample

        {

            TimeZone = $SystemTimeZone

        }

    }

}

 

SetTimeZone -output C:\serverConfig -SystemTime "Eastern Standard Time"

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

As shown here, when I run the script for the first time, a series of progress bars appear that state it is initializing the resource:

Image of command output

As the script runs, the verbose output lets me know what is going on with the script. This is shown here:

Image of command output

The last thing I do is press the UP arrow to see if my times are now correct. Here are the results:

Image of command output

That is all there is to using Windows PowerShell DSC to set the time zone.  DSC Week will continue tomorrow when I will talk about more way cool stuff.

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

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Find Time Zone Names with PowerShell

$
0
0

Summary: Find time zone enumeration names with Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to enumerate the names of time zones that are configured on my computer?

Hey, Scripting Guy! Answer Use the System.TimeZoneInfo .NET Framework class, and use the GetSystemTimeZones static method
           to obtain the list. You want the ID property for enumeration values and the DisplayName property to see
           the standard display name values. Here is an example:

[timezoneinfo]::GetSystemTimeZones() | select displayname, id

Use Desired State Configuration to Create System Restore Point

$
0
0

Summary: Microsoft Scripting Guy Ed Wilson talks about using Windows PowerShell Desired State Configuration to create a system restore point.

Microsoft Scripting Guy, Ed Wilson, is here. It is cold outside again. I nearly froze this morning when I headed to the gym for an easy walk on the treadmill. But it is a good way to wake up early in the morning. The good thing is the gym is open 24 hours a day, so it makes an early morning workout pretty easy. The bad thing about early morning workouts is, well, they happen early in the morning.

One thing that happens easily and does not require me to get up before the chickens, is Desired State Configuration (DSC). I can easily schedule DSC to happen whenever I want. After I have created my MOF files, all I need to do to reapply a DSC configuration is run the Start-DSCConfiguration command. I can schedule that command in the task scheduler in less than 30 seconds, and I can set my schedule to repeat as often as I want it to.

But that is not what I want to talk about today. I want to talk about using DSC to create a system restore point. One thing to remember about restore points is that they only work on the client workstation. they do not work on the server operating system.

Use PowerShell DSC to create a restore point

After I call the Configurationkeyword to create a new configuration script, I create my parameters. I use a filter with the Get-ADComputer cmdlet so that I return only Windows 8.1 and Windows 8 workstations. I store the resulting names in the $NodeName variable. Here is this portion of the script:

#Requires -version 4.0

Configuration CreateSystemRestorePoint

{

    Param

    (

        [String[]]$NodeName = (

        (Get-ADComputer -Filter "OperatingSystem -like 'Windows 8*'").name)

    )

The next thing I do is import the DSC resource. I have to do this because the xWindowsRestore DSC module is not standard. Here is the command:

Import-DSCResource -ModuleName xWindowsRestore

Now I specify the nodes for which I want to create configuration MOF files. I do this by using the Nodekey word. I then call the xSystemRestorePoint DSC resource (from the xWindowsRestore module), and I specify the name for the action. This is shown here:

  Node $NodeName

    {

         xSystemRestorePoint SystemRestorePointExample

I need to specify a few parameter values. I set the name for the Description, specify the type of restore, and ensure that this resource will be present (which means create a new restore point). This section of the script is shown here:

{

            Description = "Modify system settings"

            RestorePointType = "MODIFY_SETTINGS"

            Ensure = "Present"

        }

I call the CreateSystemRestorePoint configuration and specify an output folder location. If I do not specify an output folder location, the MOF files will be created in the current working directory. Lastly, I call Start-DSCConfiguration and point to the location for the MOF files. This causes the configuration to take place. Here is that portion of the script:

CreateSystemRestorePoint -output C:\serverConfig

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

Here is the complete script:

#Requires -version 4.0

Configuration CreateSystemRestorePoint

{

    Param

    (

        [String[]]$NodeName = (

        (Get-ADComputer -Filter "OperatingSystem -like 'Windows 8*'").name)

    )

    Import-DSCResource -ModuleName xWindowsRestore

 

    Node $NodeName

    {

         xSystemRestorePoint SystemRestorePointExample

        {

            Description = "Modify system settings"

            RestorePointType = "MODIFY_SETTINGS"

            Ensure = "Present"

        }

    }

}

 

CreateSystemRestorePoint -output C:\serverConfig

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

When I run the script, I see that the MOF file is created for the Windows 8* type of workstation, and then each action DSC performs appears as a verbose statement. This is shown in the following image:

Image of command output

I check to ensure that the checkpoint was actually created. I use the Get-ComputerRestorePoint cmdlet to do this. Here is the command and results:

PS C:\> Get-ComputerRestorePoint 

CreationTime    Description       SequenceNumber    EventType   RestorePoint Type

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

12/8/2014 3:08:24 PM   Scheduled Checkpoint         22          BEGIN_SYSTEM_C... 7  

1/2/2015 1:31:39 PM    Scheduled Checkpoint          23          BEGIN_SYSTEM_C... 7  

1/6/2015 2:10:39 PM    Modify system settings          24          BEGIN_SYSTEM_C... M...

Cool. It worked.

That is all there is to using DSC to create a system restore point. Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

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

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Find Related PowerShell Commands

$
0
0

Summary: Learn how to find related Windows PowerShell commands.

Hey, Scripting Guy! Question How can I find related commands in Windows PowerShell?

Hey, Scripting Guy! Answer Use the Get-Command cmdlet and sort by the ModuleName property.
           For example, to find commands that use the Get verb, use the following command:

Get-Command –Verb get | Sort modulename

Configure System Restore by Using PowerShell DSC

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell Desired State Configuration to configure a system restore.

Microsoft Scripting Guy, Ed Wilson, is here. It is nearly the weekend in Charlotte, North Carolina. I decided to arise early, grab my Surface Pro 3, and head upstairs to check my email sent to scripter@microsoft.com while I sip a cup of Earl Gray tea. I usually like Fridays because I try to avoid Friday meetings, and it means that I have all day to complete my projects for the weekend.

By using the xWindowsRestore module from the DSC Resource Kit, I can easily enable or disable System Restore on my client workstations running Windows 8.1 or Windows 8. I can enable it per drive, but I cannot set the amount of drive space that is used by System Restore. To do that, I need to use the SystemRestoreConfig WMI class that is found in the Root/Default WMI namespace. A command to query this WMI class is shown here:

Get-CimInstance -Namespace root/DEFAULT -ClassName SystemRestoreConfig

The thing that is really cool, is that the script to configure a Windows restore is very similar to the one I wrote yesterday to create a system restore point: Use Desired State Configuration to Create System Restore Point.

In fact, the first portion of the script is exactly the same. I call the Configuration keyword, retrieve my list of client workstations, and import the xWindowsRestore module. This is shown here:

Configuration ConfigureSystemRestore

{

    Param

    (

        [String[]]$NodeName = (

        (Get-ADComputer -Filter "OperatingSystem -like 'Windows 8*'").name)

    )

    Import-DSCResource -ModuleName xWindowsRestore 

For the nodes, I then call the xSystemRestore provider and ensure that the system restore is Present (which means “Turn it on”), and I specify the drive. Here is that section of the script:

Node $NodeName

    {

         xSystemRestore SystemRestoreExample

        {

            Ensure = "Present"

            Drive = "C:\"

        }

    }

The last thing I do is call the configuration, specify the output, and then use Start-DSCConfiguration to actually perform the configuration:

ConfigureSystemRestore -output C:\serverConfig

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

One thing that is pretty cool is that if I do not know what a particular DSC resource provides, I can highlight it and use the Start IntelliSensecommand from the Edit menu to tell me what it provides. I can also highlight the resource and press CTRL plus Spacebar because that is the keyboard shortcut for the Start IntelliSensecommand. Here is an example of using IntelliSense to tell me what a resource provides:

Image of command output

The complete configuration script is:

#Requires -version 4.0

Configuration ConfigureSystemRestore

{

    Param

    (

        [String[]]$NodeName = (

        (Get-ADComputer -Filter "OperatingSystem -like 'Windows 8*'").name)

    )

    Import-DSCResource -ModuleName xWindowsRestore

 

    Node $NodeName

    {

         xSystemRestore SystemRestoreExample

        {

            Ensure = "Present"

            Drive = "C:\"

        }

    }

}

 

ConfigureSystemRestore -output C:\serverConfig

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

That is all there is to using DSC to configure a system restore on a computer running Windows 8.1 or Windows 8. Join me tomorrow when I will talk about more cool Windows PowerShell stuff. 

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

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Find Restore Points with PowerShell

$
0
0

Summary: Learn how to use Windows PowerShell to find restore points.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find a list of restore points on my computers running
           Windows 8.1 or Windows 8?

Hey, Scripting Guy! Answer Use the Get-ComputerRestorePoint cmdlet.

Notes 

    • Start the Windows PowerShell console with Administrator rights to run this command.
    • New restore points are created via the CheckPoint-Computer cmdlet.

Weekend Scripter: Run a Scheduled Task to Check DSC

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about running a scheduled task to perform a consistency check for DSC.

Microsoft Scripting Guy, Ed Wilson, is here. One of the things I love to do is to automate things. Not only scripts. Not only Windows PowerShell. I also like to automate scheduled tasks. The current task scheduler is so much more powerful than the old-fashioned AT command that it is not funny. Well, maybe it’s funny, but it is also really cool.

One thing that is pretty neat, is that Windows uses scheduled tasks to manage Windows. And I have access to the same technology. For a single scheduled task on a single machine, I usually use the GUI tool. For more information, see  Use Scheduled Tasks to Run PowerShell Commands on Windows. IThe GUI tool t is pretty intuitive and pretty easy to use. For a truly one-off situation, it is the best tool to use (in my mind). But if I want to create the same scheduled task on a whole bunch of machines, I had better be looking at using Windows PowerShell.

In the old days, that would have meant interacting with the API (see How Can I Best Work with Task Scheduler?) or limiting myself to the AT command. The WMI classes simply interacted with the AT scheduler (see How Can I Create a Scheduled Task on a Number of Computers?), so it was not much better.

   Note  For some great information, see Using Scheduled Tasks and Scheduled Jobs in PowerShell.

Luckily, with Windows PowerShell Desired State Configuration (DSC), an automatic, consistency-check scheduled task is already present. This scheduled task is shown here:

Image of menu

The Consistencyscheduled task runs every 30 minutes by default. I can see this by clicking the Triggers tab, or I can use the Get-ScheduledTask cmdlet and find the information. This technique is shown here:

PS C:\> Get-ScheduledTask -TaskName consistency | fl *

State                 : Ready

Actions               : {MSFT_TaskExecAction}

Author                : SYSTEM

Date                  :

Description           :

Documentation         :

Principal             : MSFT_TaskPrincipal2

SecurityDescriptor    :

Settings              : MSFT_TaskSettings3

Source                :

TaskName              : Consistency

TaskPath              : \Microsoft\Windows\Desired State Configuration\

Triggers              : {MSFT_TaskTimeTrigger}

URI                   :

Version               :

PSComputerName        :

CimClass              : Root/Microsoft/Windows/TaskScheduler:MSFT_ScheduledTask

CimInstanceProperties : {Actions, Author, Date, Description...}

CimSystemProperties   : Microsoft.Management.Infrastructure.CimSystemProperties

 

PS C:\> (Get-ScheduledTask -TaskName consistency).triggers.repetition

 

Duration                      Interval                                  StopAtDurationEnd PSComputerName

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

                              PT1800S                                               False

Use PowerShell to run a scheduled task

Let's suppose I am checking for configuration drift and I notice that my Consistencytask has recently failed as shown here:

Image of menu

I can wait for another 30 minutes and hope that it runs successfully, or I can use the GUI and try to execute the task, or I can use the Start-ScheduledTask cmdlet. The Start-ScheduledTask cmdlet requires the task name and the task path. If I attempt to run the cmdlet with only the task name, and error occurs. Luckily, I can use the Get-ScheduledTask cmdlet to retrieve the path to the scheduled task. This command is shown here:

Start-ScheduledTask -TaskName consistency -TaskPath (Get-ScheduledTask -TaskName consistency).TaskPath

The previous command and associated output are shown here:

Image of command output

I go back to the task scheduler GUI tool and check the history. Now I see that the Consistencytask was queued, and then ran as I hoped:

Image of menu

The really cool thing is that the Start-ScheduledTask cmdlet accepts CIMSessionas a parameter. This means that I can easily create a CIM session to my remote computers, and kick off the Consistencytask. This technique is shown here (where I use the Get-ADComputer cmdlet to retrieve my computer names):

$cn = Get-ADComputer -Filter *

$cim = New-CimSession -ComputerName $cn.name -ea 0

Start-ScheduledTask -TaskName consistency -TaskPath (Get-ScheduledTask -TaskName consistency).TaskPath -CimSession $cim

   Note  The Get-ADComputer cmdlet comes from the Active Directory module. For more information,
   see Install Free PowerShell Remote Server Admin Tools.

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 Unblock Files in Folder

$
0
0

Summary: Learn how to use Windows PowerShell to unblock files downloaded from the Internet.

Hey, Scripting Guy! Question I downloaded a module from the Script Center Repository, and when I expanded and copied the files to
           my modules folder, I forgot to unblock them. Now every time I start Windows PowerShell, I get error
           messages and the modules don’t work. How can I easily fix this situation?

Hey, Scripting Guy! Answer Use the Get-ChildItem cmdlet to return a list of all files in your modules directory, and pipe them to
           the Unblock-File cmdlet, for example:

Get-ChildItem -Path 'C:\Program Files\WindowsPowerShell\Modules\' -Recurse | Unblock-File


Weekend Scripter: Where Is the DSC Documentation?

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about where to find documentation for Windows PowerShell Desired State Configuration (DSC).

Microsoft Scripting Guy, Ed Wilson, is here. One of the things that sometimes surprises me, is when I am talking to IT pros and I hear something like, “I really like Windows PowerShell, but I wish that there was more documentation about it.” This is, if you will, a “Hmmmmm” type of moment.

From where I sit, I would think that that perhaps the issue is not that there is no documentation, but that there is so much documentation, it is hard to find what one really wants or needs. Perhaps it all depends on one’s view of documentation.

Note  Stay tuned for a way cool post from the Scripting Manager about “the changing nature of documentation.”

Whenever I start looking for documentation for Windows PowerShell, the first thing I do is look at the Help files. When I am looking for something that is more of a concept than a specific cmdlet, I look for a Helpfile.

I like to use the Get-Help cmdlet, specify my category, and then specify something that will get me close to the topic I seek. Following is the command I use. (I can type this command in the Windows PowerShell console or in the execution pane of the Windows PowerShell ISE—either place works the same.)

get-help -Category HelpFile desiredstate

This command displays the about_Desired_State_Configuration topic. If I searched for DSC instead, I would still find the topic, but I would also have a few more items returned. Here is what I am talking about:

PS C:\> get-help -Category HelpFile dsc

 

Name                                    Category  Module                    Synopsis                                                  

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

about_Classes                                HelpFile           Describes how you can use classes to develop in Windows

about_Debuggers                           HelpFile           Describes the Windows PowerShell debugger.                

about_DesiredStateConfiguration   HelpFile          Provides a brief introduction to the Windows              

about_Windows_PowerShell_4.0    HelpFile           Describes new features that are included in               

about_Windows_PowerShell_5.0    HelpFile           Describes new features that are included in         

The about_Desired_State_Configuration Help topic is really pretty good, and it provides a great overview of how to create a configuration script and how to guard against configuration drift. It also lists the inbox DSC resources. But one of the best things about the Help topic is that at the bottom (and also near the top), it includes a link to the applicable TechNet Library section, Windows PowerShell Desired State Configuration. This topic, which is shown in the following image, offers good information about DSC, how to use it, and some great tips for using it in a real-world environment.

Image of webpage

These two resources are absolutely the place to get started when using Windows PowerShell DSC. They also constitute official Microsoft documentation about this feature.

Other resources for DSC documentation

There is a lot of documentation from Microsoft for Desired State Configuration in the form of blogs. The Hey, Scripting Guy! Blog, for example, has around 25 posts related to DSC. The PowerShell Team blog has nearly twice that number of posts tagged with DSC. But many of those posts are notices such as the DSC Resource Kit wave releases.

Speaking of the DSC Resource Kit wave releases, each resource module in the DSC Resource Kit includes sample scripts that illustrate how to use the resource. In addition, each resource includes documentation. The samples and sample documentation are available in each module folder.

The Microsoft Press book that I wrote, Windows PowerShell Best Practices, includes an entire chapter devoted to DSC. In that chapter, I include configuration scripts and talk about all of the standard DSC resource providers.

Channel 9 has recordings of TechEd presentation sessions about Windows PowerShell DSC. For example, there is a talk by Don Jones (A Practical Overview of Desired State Configuration) and there is a talk by Kenneth Hansen and Jeffrey Snover (Desired State Configuration in Windows PowerShell).

PowerShell.org has an entire forum devoted to Desired State Configuration, in which there are nearly 200 posts.

PowerShell Magazine has a number of very interesting articles about DSC.

There are also several videos on You Tube that talk about DSC.

So, there are lots of sources of documentation about using Windows PowerShell DSC.

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 Find Status of Scheduled Tasks

$
0
0

Summary: Use Windows PowerShell to find the status of scheduled tasks.

Hey, Scripting Guy! Question My laptop is acting strangely. Task Manager shows lots of processes running, but I have disabled everything I can see.
           How can I use Windows PowerShell to determine what scheduled tasks are running in the background?

Hey, Scripting Guy! Answer Use the Get-ScheduledTask cmdlet and sort by the state:

Get-ScheduledTask | sort state

Use PowerShell to Show Results of Scheduled Tasks

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to see the results of scheduled tasks.

Microsoft Scripting Guy, Ed Wilson, is here. It is snack time. For me, a perfect snack is a piece of biscotti and a cup of tea. Today, I am having such a snack—the tea is a nice green tea with a bit of jasmine flower in it. Lovely.

Something else that is lovely is using the cmdlets from Scheduled Tasks module. This module contains a number of very helpful cmdlets.

Note  For a great overview of the Scheduled Tasks module, see Windows 8.1 and the Land of Forgotten Modules: Part 5.

Working with scheduled tasks

The Task Scheduler is very sophisticated. It is so sophisticated that many applications use it to run things at various times. If I want to get an idea of the tasks that are ready to run, it is going to require a lot of clicking in the GUI. But with Windows PowerShell, it is a piece of cake. I type a command such as the following—and voila! Lots of information appears.

Get-ScheduledTask | where state -EQ 'ready'

The output is shown here:

Image of command output

There are lots of scheduled tasks that are actually ready to run. What I if I want to find out the results of the last time the task ran? I know where to go in the GUI, but what about using Windows PowerShell? I look at cmdlets from the Scheduled Tasks module, and I see some things that make sense. Here are the results:

PS C:\> Get-Command -Module ScheduledTasks -Verb get

CommandType     Name                                         ModuleName

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

Function        Get-ClusteredScheduledTask             ScheduledTasks

Function        Get-ScheduledTask                             ScheduledTasks

Function        Get-ScheduledTaskInfo                       ScheduledTasks

I suspect that I can use Get-ScheduledTaskInfo. So I give it a try. I know one of the scheduled tasks is Consistency.

Image of command output

Dude. How rude! I mean, I KNOW the task name is Consistency, I just wrote a blog post about it ( see Run a Scheduled Task to Check DSC). I use the Get-ScheduledTask cmdlet to prove this:

PS C:\> Get-ScheduledTask -TaskName consistency

TaskPath                                                          TaskName               State

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

\Microsoft\Windows\Desired State Configurat... Consistency          Ready

Yep. It is Consistency alright. What if I use the –TaskPath parameter? As shown here, it is now asking for the name. Dude...

Image of command output

I type the task name at the prompt, and finally I get the results of the last run. This is shown here:

Image of command output

If I am going to go to all that trouble, I may as well just pipe Get-ScheduledTask in the first place:

Get-ScheduledTask consistency | Get-ScheduledTaskInfo

Cool. If I can pipe the results from Get-ScheduledTask to Get-ScheduledTaskInfo, I can make myself a report by piping the results to Export-CSV:

Get-ScheduledTask | where state -EQ 'ready' | Get-ScheduledTaskInfo |
Export-Csv -NoTypeInformation -Path C:\fso\scheduledTasksResults.csv

Here is the output in Excel:

Image of command output

Sweet. That was easy.

That is all there is to using Windows PowerShell to find the results of scheduled tasks. Scheduled Tasks week will continue tomorrow when I will talk about more cool stuff.

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

Ed Wilson, Microsoft Scripting Guy

PowerTip: Use PowerShell to Show "Ready" Scheduled Tasks

$
0
0

Summary: Use Windows PowerShell to show all scheduled tasks that are ready to run.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find what scheduled tasks are ready to run on my system?

Hey, Scripting Guy! Answer Use the Get-ScheduledTask cmdlet, pipe the results to the Where-Object cmdlet, and
           filter on the state being ready, for example:

Get-ScheduledTask | where state -EQ 'ready'

Use PowerShell to Create Scheduled Tasks

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to create a scheduled task.

Microsoft Scripting Guy, Ed Wilson, is here. Today, it is cold, wet, and rainy—not exactly my favorite combination. In fact, I would rather have snow. At least then there would be an excuse for the dreariness. Oh well. Snow in the deep south is about as rare as—well...as rare as people who enjoy manually creating scheduled tasks.

Dude, creating scheduled tasks is boring. Not only that, it is easy to make a mistake. And when I am done creating a scheduled task, I am not really sure what it is going to do until it runs (or does not run) at the next scheduled time.

When I was consulting, I hated creating scheduled tasks because if I messed up, I had to drive across town to try to troubleshoot the thing. Often, my code was simply missing a comma, a quotation mark, or a space. Mistakes like that mean you cannot really bill the customer for it, which becomes a double whammy—the lost time and the lost billing. Luckily, with Windows PowerShell, it is much easier.

Note  The Scheduled Task module first appeared with Windows PowerShell 3.0 in Windows 8 and Windows Server 2012.

There are a few things that are required when it comes to creating a schedule task. One of these things is the action. What do I want the scheduled task to do? Without specifying an action, there is no reason to create a scheduled task.

Not only is this a requirement, but it can also be really frustrating. I need to get it exactly right. The graphical form can provide some clues. Here is the form for creating a new scheduled task action:

Image of menu

The action that I want is to start a program. In the New-ScheduledTaskAction cmdlet, this is the –Executeparameter, and I specify the name of the program I want to run. For me, that generally translates to PowerShell.exe. The Addarguments box translates to the –Argumentparameter. For me, this is everything I want to pass to the PowerShell.exe command. The Start in box translates to the –WorkingDirectory parameter of the cmdlet.

The hardest parameters to figure out are ­Execute and Argument. But I use the Run dialog box to see if I have my command working properly. Because the Run dialog box is not resizable (in fact, it doesn’t even scroll), it is frustrating to use.

So I type my commands in Notepad until I have something that works the way I want it to. Typing the command in Notepad provides me the chance to scroll and see exactly what I am typing, and it provides a convenient way for me to store my working command for later reference and reuse. In addition, by using Notepad, I can work with a long command and then use CTRL-A and CTRL-C to select and copy my command. I then use CTRL-V to paste it into the Run dialog box.

By directly executing my command line, I can fine tune the command easily and quickly. Following is the command I decided to use. (This is a single-line command that wraps in this post.)

Powershell -NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"

I need to break-up the command for the Execute and Argument parameters. If I do not do this, when the scheduled task runs, an error message will pop up and ask me how I want to execute the program. Frustrating, but hey, not a biggie. Here is the command from my Windows PowerShell script:

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' `

  -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'

Now I create a trigger. I want the command to run each day at 9:00 A.M. so that it will dump the previous day's events from the application log. To create the new trigger, I use the New-ScheduledTaskTrigger cmdlet:

$trigger =  New-ScheduledTaskTrigger -Daily -At 9am

One thing that is a bit confusing is that if I want my scheduled task to run, I need to register it. So, rather than using the New-ScheduledTask cmdlet, I use the Register-ScheduledTask cmdlet. I also provide it a name and a description, for example:

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "AppLog" -Description "Daily dump of Applog"

When I do this, it creates the new scheduled task, and it marks it as ready to execute. I can see it in the Task Scheduler GUI tool in the root folder. The task is shown here:

Image of menu

Following is the complete script:

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' `

  -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'

$trigger =  New-ScheduledTaskTrigger -Daily -At 9am

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "AppLog" -Description "Daily dump of Applog"

Here are several things to keep in mind:

  • This script requires admin rights to create a new scheduled task.
  • The script will run in the context of the user who created the scheduled task.
  • The script uses absolute paths for the output CSV file.
  • The script overwrites all existing CSV files with the same name.
  • Be very careful with spaces in the argument portion of the script. It may look like it will work, but it might not if you press ENTER to break up the line of code.
  • The previous script is three lines of code, but I added a line break for the first line of code.

The script is shown here inside the Windows PowerShell ISE:

Image of command output

That is all there is to creating and registering a new scheduled task with Windows PowerShell. Scheduled Task Week will continue tomorrow when I will talk about more cool stuff.

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

Ed Wilson, Microsoft Scripting Guy

PowerTip: Find Scheduled Tasks with PowerShell

$
0
0

Summary: Use Windows PowerShell to find the location of scheduled tasks.

Hey, Scripting Guy! Question How can I use Windows PowerShell to easily look for scheduled tasks in the graphical tool?

Hey, Scripting Guy! Answer Use the Get-ScheduledTask cmdlet and search on the TaskPath property. Related scheduled tasks are
           grouped together and TaskPath provides that location. Here is an example:

Get-ScheduledTask | where taskpath -match 'powershell'

Use PowerShell to Configure Scheduled Task

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to configure a scheduled task.

Microsoft Scripting Guy, Ed Wilson, is here. This morning is a coffee morning. I don’t have a lot of coffee mornings, but occasionally I break down and desire a raw coffee jolt. When I do, I use my French press, some spring water, my rotary bean grinder, and usually some sort of special beans. Usually, that translates into a nice Kona bean. It seems to take me nearly a half hour to make a decent cup of coffee. Luckily, I can almost do it in my sleep—which is a good thing.

Because I do not make much coffee, I feel no need to automate the process. But if I did, I would probably invest in one of those big programmable machines. I would sync it with my alarm clock so the coffee would be available for me when I wake up—sort of like a nice hotel with someone who brings coffee or hot cocoa to your door with your wake-up call.

After a scheduled task is created, there are still many configurable items. Luckily, I can use Windows PowerShell to make these configuration changes. Even better, introduced in Windows 8 and Windows Server 2012, there is the Scheduled Task module that makes these changes a breeze.

Note  See yesterday's post, Use PowerShell to Create Scheduled Tasks, for a basic introduction to scheduled tasks and the Scheduled Task module.

Using Windows PowerShell to provide configuration options for a scheduled task is really easy. Basically, there is one cmdlet to create the configuration options and one cmdlet to apply the configuration options (actually, they are advanced functions, not really cmdlets):

  • New-ScheduledTaskSettingsSet
  • Set-ScheduledTask

The first thing I do is use New-ScheduledTaskSettingsSet to create my configuration options. I store the resulting object in a variable. As shown in the following results, there are many potential options available:

Image of command output

I want to permit my AppLogtask (which I created yesterday) to do the following:

  • Start if my laptop is on battery power
  • Not stop if my laptop transitions to battery
  • Start hidden
  • Have an execution time limit of five minutes
  • Restart three times if something happens to stop the task

Here is the command that does all this (this is a single-line command that wraps on the blog page):

$settings = New-ScheduledTaskSettingsSet –AllowStartIfOnBatteries – DontStopIfGoingOnBatteries -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -RestartCount 3

After I create my task settings object, I use Set-ScheduledTask to apply the new settings. The cool thing is that I can apply the new settings even if the scheduled task is currently running. The only catch is that the new settings only take place the next time the task runs. It does not modify the behavior of a currently executing task. Here is the command I use:

Set-ScheduledTask -TaskName applog -Settings $settings 

That is it. Two lines of code really. Pretty cool. When I execute the script, it provides a minimal amount of output, but it does not echo the new settings. Here is what the script looks like after it runs.

Image of command output

That is all there is to using Windows PowerShell to configure a scheduled task. Scheduled Task Week will continue tomorrow when I will talk about more cool stuff.

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

Ed Wilson, Microsoft Scripting Guy 


PowerTip: Use PowerShell to Disable Scheduled Task

$
0
0

Summary: Learn how to use Windows PowerShell to disable a scheduled task.

Hey, Scripting Guy! Question How can I use Windows PowerShell to disable a scheduled task?

Hey, Scripting Guy! Answer Use the Disable-ScheduledTask cmdlet from the Scheduled Task module, for example:

Disable-ScheduledTask -TaskName applog

Note  This cmdlet was introduced in Windows 8 and Windows Server 2012, and it requires admin rights.

Use PowerShell to Create Scheduled Tasks Folders

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to create a folder for scheduled tasks.

Microsoft Scripting Guy, Ed Wilson, is here. Today I have several meetings, and I am really looking forward to them. One of my meetings is with the Windows PowerShell team. I have a meeting with them every other week, and it is always a lot of fun. They are great people! My other meeting is with the team working with the Microsoft Ignite Conference in Chicago. That is probably all I can say right now. But suffice it to say, that I get to attend fun and exciting meetings. That is why I, as opposed to some people I know, love to have meetings—they are productive, and they are with absolutely awesome people. Hmmm, I wonder if that is a pattern...

You know what else is productive and awesome? Using Windows PowerShell to work with scheduled tasks (OK, that was not the greatest "segue." Word keeps wanting to change that to "Segway." Oh well.)

Creating a task folder

When I look at the Task Scheduler tool, I see lots of folders that contain hundreds of scheduled tasks. On my computer, it is 180 scheduled tasks as shown here:

PS C:\> (Get-ScheduledTask).count

180

But trying to find the scheduled tasks can be hit or miss. Here is a view of the tool:

Image of menu

A better way to work with the scheduled tasks I create, is to create my own folders that I can use to group them together. The problem is that there is no New-ScheduledTaskFolder function or cmdlet available. Therefore, I need to revert to using the Schedule.Service COM API. This is actually pretty easy to do. There are four steps involved:

  1. Create the Schedule.Service object.
  2. Connect to the schedule service.
  3. Create a folder object.
  4. Create a new folder.

To create an instance of the Schedule.Service object, I use the New-Object cmdlet, and I specify that I want to create a new COM object. I use a variable to store the returned object. This is shown here:

$scheduleObject = New-Object -ComObject schedule.service

Now that I have an instance of the Schedule.Service object, I connect to the Task Scheduler service. Because no object returns from this command, I do not need another variable. Here is the command:

$scheduleObject.connect()

I need to create a folder object to gain access to the method required to create a new folder. Therefore, I use the GetFoldermethod from the schedule object I have stored in the $scheduleObject variable. I need to retrieve the root folder, and I can use the path “\” to do this. Because this command returns a TaskFolder object, I need a variable to hold the returned object. For this purpose, I use the $rootFolder variable. Here is the command:

$rootFolder = $scheduleObject.GetFolder("\")

Now, I can call the CreateFoldermethod from the TaskFolder object. I specify the name of the folder that I want to create. This command is shown here:

$rootFolder.CreateFolder("PoshTasks")

When I run the command, I see that the new folder appears off the root. The following image illustrates the results:

Image of menu

The complete script is shown here:

$scheduleObject = New-Object -ComObject schedule.service

$scheduleObject.connect()

$rootFolder = $scheduleObject.GetFolder("\")

$rootFolder.CreateFolder("PoshTasks")

Deleting a task folder

If I want to delete a task folder, I call the DeleteFoldermethod. The DeleteFoldermethod requires the name of the folder, and I also need to pass a $null as the second parameter. Other than that, the code is exactly the same as that I used to create a folder. Here is a script to delete the folder I just created:

$scheduleObject = New-Object -ComObject schedule.service

$scheduleObject.connect()

$rootFolder = $scheduleObject.GetFolder("\")

$rootFolder.DeleteFolder("poshTasks",$unll)

That is all there is to using Windows PowerShell to create and delete folders for scheduled tasks. Scheduled Task Week will continue tomorrow when I will talk about more cool stuff.

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

Ed Wilson, Microsoft Scripting Guy 

PowerTip: Use PowerShell to Enable Scheduled Task

$
0
0

Summary: Use Windows PowerShell to enable a scheduled task.

Hey, Scripting Guy! Question How can I use Windows PowerShell to enable a scheduled task?

Hey, Scripting Guy! Answer Use the Enable-ScheduledTask function from the Scheduled Task module, for example:

Enable-ScheduledTask -TaskName applog

Note  This command uses the Scheduled Task module (which was introduced in Windows 8 and
Windows Server 2012), and it requires admin rights.

Use PowerShell to Create Scheduled Task in New Folder

$
0
0

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to create a new scheduled task in a specific folder.

Microsoft Scripting Guy, Ed Wilson, is here. Today I want to combine several of the scripts I have discussed this week based on scheduled tasks. Specifically, I am going to do the following:

  1. Check to see if a specific scheduled task exists. If it does, delete it.
  2. Check to see if a specific folder for scheduled tasks exists. If it does, do not create it.
  3. Create and register a new scheduled task in that specific folder.
  4. Modify the settings on that newly created scheduled task.

To do this, I am going to combine the various pieces of script I have used this week. To make the script a bit easier to read, I am putting the script into functions. These are not advanced functions, and they do not have good function names. The value of today’s exercise is to show how to combine various pieces of script to perform a specific task. More complex tasks are actually the norm for IT pros, so knowing how to put stuff together to accomplish a more complex process is valuable. Let's dive in...

Group script together in functions

The first thing I do is take my basic script from Use PowerShell to Create Scheduled Tasks Folders, and turn it into a simple function. My function accepts a single parameter, and that is the new folder name (or folder path). Because the CreateFolder method generates an error if a folder exists, I decide to add a bit of script to check to see if the folder exists before I attempt to create it. However, the GetFolder method generates an error if the folder does not exist. Hmm...

I decided to use a simple Try/Catch/Finally routine to do my folder check. To ensure that I enter the Try/Catch routine, I change the ErrorActionPreference to “Stop” instead of “Continue”, which is the default. I then set this value back in my Finally block. Here is the complete function:

Function New-ScheduledTaskFolder

    {

     Param ($taskpath)

     $ErrorActionPreference = "stop"

     $scheduleObject = New-Object -ComObject schedule.service

     $scheduleObject.connect()

     $rootFolder = $scheduleObject.GetFolder("\")

        Try {$null = $scheduleObject.GetFolder($taskpath)}

        Catch { $null = $rootFolder.CreateFolder($taskpath) }

        Finally { $ErrorActionPreference = "continue" } }

Now I need to create the function that will create and register my new scheduled task. I used the script from Use PowerShell to Create Scheduled Tasks. The only thing I did to modify it was to put it in a function and create two input parameters: TaskName and TaskPath. Here is the function:

Function Create-AndRegisterApplogTask

{

 Param ($taskname, $taskpath)

 $action = New-ScheduledTaskAction -Execute 'Powershell.exe' `

  -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'

 $trigger =  New-ScheduledTaskTrigger -Daily -At 9am

 Register-ScheduledTask -Action $action -Trigger $trigger -TaskName `

  $taskname -Description "Daily dump of Applog" -TaskPath $taskpath

}

To completely automate creating a scheduled task, often we modify the scheduled task settings after it is created. To do this, I use the script from Use PowerShell to Configure Scheduled Tasks. Once again, all I did was plop the script in a function and create two input parameters. These are the same parameters I used in the previous function: TaskName and TaskPath. Here is the function:

Function Create-NewApplotTaskSettings

{

 Param ($taskname, $taskpath)

 $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `

    -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -RestartCount 3

 Set-ScheduledTask -TaskName $taskname -Settings $settings -TaskPath $taskpath

}

After I have created my three functions, I create an entry point to the script. It is here that I define my two input parameters, and I check to see if the scheduled task previously exists. This is because I first created the scheduled task in the root folder, but now I want to create it in my new scheduled task folder (I do not know of a way to move a scheduled task from one folder to another, so it was easier to delete and re-create it.) Here is the command I use to do that:

If(Get-ScheduledTask -TaskName $taskname -EA 0)

  {Unregister-ScheduledTask -TaskName $taskname -Confirm:$false}

Now I simply call the function to create the new scheduled task folder, call the function to create the new scheduled task, and call the function to configure the task. Here is that script:

New-ScheduledTaskFolder -taskname $taskname -taskpath $taskpath

Create-AndRegisterApplogTask -taskname $taskname -taskpath $taskpath | Out-Null

Create-NewApplotTaskSettings -taskname $taskname -taskpath $taskpath | Out-Null

The complete script is shown here:

Function New-ScheduledTaskFolder

    {

     Param ($taskpath)

     $ErrorActionPreference = "stop"

     $scheduleObject = New-Object -ComObject schedule.service

     $scheduleObject.connect()

     $rootFolder = $scheduleObject.GetFolder("\")

        Try {$null = $scheduleObject.GetFolder($taskpath)}

        Catch { $null = $rootFolder.CreateFolder($taskpath) }

        Finally { $ErrorActionPreference = "continue" } }

    

Function Create-AndRegisterApplogTask

{

 Param ($taskname, $taskpath)

 $action = New-ScheduledTaskAction -Execute 'Powershell.exe' `

  -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-1)) | Export-Csv -Path c:\fso\applog.csv -Force -NoTypeInformation}"'

 $trigger =  New-ScheduledTaskTrigger -Daily -At 9am

 Register-ScheduledTask -Action $action -Trigger $trigger -TaskName `

  $taskname -Description "Daily dump of Applog" -TaskPath $taskpath

}

 

Function Create-NewApplotTaskSettings

{

 Param ($taskname, $taskpath)

 $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `

    -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -RestartCount 3

 Set-ScheduledTask -TaskName $taskname -Settings $settings -TaskPath $taskpath

}

### ENTRY POINT ###

$taskname = "applog"

$taskpath = "PoshTasks"

If(Get-ScheduledTask -TaskName $taskname -EA 0)

  {Unregister-ScheduledTask -TaskName $taskname -Confirm:$false}

New-ScheduledTaskFolder -taskname $taskname -taskpath $taskpath

Create-AndRegisterApplogTask -taskname $taskname -taskpath $taskpath | Out-Null

Create-NewApplotTaskSettings -taskname $taskname -taskpath $taskpath | Out-Null

Here is what the script looks like in my Windows PowerShell ISE:

Image of command output

Because I am planning to use this script for automation purposes, there is no output. So when I run the script, I do not see anything. I instead open the Scheduled Task tool to ensure that it is there and ready. As you can see here, it worked perfectly.

Image of menu

Now you have some good ideas for using Windows PowerShell for scheduled tasks. Scheduled Task Week will continue tomorrow when I will talk about more cool stuff.

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

Ed Wilson, Microsoft Scripting Guy

PowerTip: Use PowerShell to Delete Scheduled Task

$
0
0

Summary: Use Windows PowerShell to delete a scheduled task.

Hey, Scripting Guy! Question How can I use Windows PowerShell to delete a scheduled task?

Hey, Scripting Guy! Answer Use the Unregister-ScheduledTask function. By default, this command will prompt for confirmation. Therefore,
           if you want to use a Windows PowerShell script to remotely delete the scheduled task, you will need to supply
           confirmation in the command. Here is an example:

Unregister-ScheduledTask -TaskName applog -Confirm:$false

Note  This command was introduced in Windows 8 and Windows Server 2012 in the Scheduled Task module,
and it must be run with admin rights.

Viewing all 2129 articles
Browse latest View live


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