Get started Bring yourself up to speed with our introductory content.

Creating PowerShell scripts for task automation

At a certain point, administrators who run PowerShell commands from the console will find it more efficient to develop a script that does not require manual intervention.

For new PowerShell users, it doesn't take much to graduate from command-line administration to writing complex...

workflows. It's just a matter of recognizing patterns.

Most IT administrators don't start creating PowerShell scripts until they get a feel for the running commands interactively from the console. They can type a PowerShell cmdlet to transfer files, ping computers and start virtual machines. At some point, these actions get repetitive. When that time comes, it's time to build a PowerShell script.

A script is the same as running a bunch of commands in the console, except it doesn't require admin involvement. It executes one time, and PowerShell runs the commands in sequential order.

For example, the Get-CimInstance cmdlet pulls operating system information from servers. After some testing, the administrator can produce a complex command that returns the desired information and save it to a text file for future use.

Get-CimInstance -CimSession (New-CimSession -Credential (Get-Credential) -ComputerName DC -SessionOption (New-CimSessionOption -Protocol Dcom)) -ClassName Win32_OperatingSystem -Property Caption,RegisteredUser,OSArchitecture | Select-Object Caption,RegisteredUser,OSArchitecture

It would be hard to remember and type this command every time. Saving commands to a text file is one step toward creating PowerShell scripts.

Saving commands to a text file is one step toward creating PowerShell scripts.

When run, the command asks for a credential, then presents the desired properties.

cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential

Caption             RegisteredUser OSArchitecture
-------             -------------- --------------
Microsoft Windows Server 2012 R2 Standard Windows User   64-bit

This approach works, but it's more beneficial to convert the command into a script that enables the admin to specify servers to query.

A good script builder can break any task down and see the variables that change with each execution. In this case, the only variable here is the server name. Everything else repeats and should be stored in the script.

In the example, the administrator has to type in credentials and the server names, but there's a way to script these manual tasks.

Keys to coding PowerShell tasks

Creating PowerShell scripts takes three steps.

  1. Eliminate all instances that require interaction, such as credential prompts.
  2. Separate everything from the original commands.
  3. Refactor the original commands to support any new parameters or variables.

Let's tackle the Get-Credential prompt first. To use the same credential every time to query the servers, save the credential to disk and read from it every time the script runs. To set this up, export the credential to an encrypted XML file and import it when the script runs.

Export the credential to disk using the following:

Get-Credential | Export-CliXml -Path C:\MyCredential.xml

To import the credential without specifying the username and password every time, use the following:

$credential = Import-CliXml -Path C:\MyCredential.xml

Next, separate the data that may change -- for example, server names -- and build a way to pass them into the script. For this functionality, use script parameters and create a param block followed by one or more parameters inside. Make a single parameter called ComputerName and allow it to accept multiple computer names.

param(
    [Parameter(Mandatory)]
    [string[]]$ComputerName
)

Next, put the script together and tighten the code, replacing the static server name reference with a variable. Save the script with a name, such as Get-ServerInformation.ps1.

param(
    [Parameter(Mandatory)]
    [string[]]$ComputerName
)

$credential = Import-CliXml -Path C:\MyCredential.xml
$cimSession = (New-CimSession -Credential $credential -ComputerName $ComputerName -SessionOption (New-CimSessionOption -Protocol Dcom))
Get-CimInstance -CimSession $cimSession -ClassName Win32_OperatingSystem -Property Caption,RegisteredUser,OSArchitecture | Select-Object Caption,RegisteredUser,OSArchitecture

All this work results in a finished PowerShell script that replaces the need to copy and paste a long command, enter server names, and input credentials manually. Creating PowerShell scripts in this fashion enables the admin to remove forced interactivity. Just execute the script and provide the server namesPS> .\Get-ServerInformation.ps1 -ComputerName SRV1,SRV2,SRV3

This was last published in March 2018

Dig Deeper on Windows administration tools

Join the conversation

1 comment

Send me notifications when other members comment.

Please create a username to comment.

What are some ways you learned how to create a PowerShell script?
Cancel

-ADS BY GOOGLE

SearchServerVirtualization

SearchCloudComputing

SearchExchange

SearchSQLServer

SearchEnterpriseDesktop

SearchVirtualDesktop

Close