Getting information about Run As Accounts for services and scheduled tasks
On a default Windows installation there is a number of Windows services and scheduled tasks. These are configured to run with a specified set of credentials like LocalSystem, LocalService or NetworkService. New services is typically created when installing applications, which in a domain environment often require a domain account configured as the run as account. The same requirement is true for scheduled tasks, in example a scheduled script which requires specific credentials.
A good practice is keeping track of these run as accounts, as they could potentially be a security threat. For instance a bad practice would be to configure a service or scheduled task to run as an Administrator account, when there is no need for it to run with administrative privileges.
In order to gather information about run as accounts for services and scheduled tasks I`ve created an advanced function in Windows PowerShell, named Get-RunAsAccount. The function uses Windows Management Instrumentation (WMI) to gather information about services, and schtasks.exe to gather information about scheduled tasks.
The Get-ScheduledTask function, which is a wrapper function around schtasks.exe, is created by PowerShell MVP Claus Nielsen. A two part series about managing scheduled tasks is available on the PowerShell Magazine:
- Managing scheduled tasks in your environment – Part I
- Managing scheduled tasks in your environment – Part II
The article series also provides a function for changing the username and password for a scheduled task.
Get-RunAsAccount
More than one item may be specified on the –Computername parameter, for example “Computer-A, computer-B”, thus we use a foreach construct to loop through to the $computername variable.
PROCESS {
foreach ($computer in $computername) {
Get-RunAsAccountWorker -computername $computer
}
}
Next, we set up basic error handling by using a try/catch block, where we start by sending a ping request using Test-Connection, and attempting a connection to the target computer using WMI.
try {
if ((Test-Connection -ComputerName $computername -Count 1 -Quiet) -and ($computersystem = Get-WmiObject -Class win32_computersystem -Computername $computername -ErrorAction stop)) {
Write-Verbose "Connected to computer $computername"
$connectivity = "Success"
$output = @()
If the Test-Connection cmdlet fails, the “else” script block on line 116 will be executed, populating a hash-table for the output variable where the Connectivity property is set to “Failed (ping)”. If the WMI connection fails, an exception is generated and the code in the catch block on line 132 is executed. If the connection succeed we write a message which will be shown if the –Verbose parameter is specified, informing the user that we successfully connected to the computer.
We populate the $connectivity variable which will be used later on, and we set up an empty array for the matching services and scheduled tasks found on the target computer.
Next we gather all services on the computer. Notice that we specify a filter for Get-WmiObject, which performs a wildcard match using the provided RunAsUser parameter value. If the parameter isn`t specified, all services will be returned.
$services = Get-WmiObject win32_service -filter "(StartName Like '%$runasuser%')" -ComputerName $computername -ErrorAction Stop | Select-Object name,startname
if ($services) {
foreach ($service in $services) {
Write-Verbose "Processing service $($service.name)"
$outputservice = @{}
$outputservice.Computername = $computersystem.name
$outputservice.Connectivity = "Success"
$outputservice.Type = "Service"
$outputservice.Name = $service.name
$outputservice.RunAsAccount = $service.startname
$output += $outputservice
}
}
If any services is found, a foreach construct will loop through all the services found, generate a hash-table with information about the service and add it to the $output variable created earlier. The same procedure is then repeated for gathering information about scheduled tasks, using Claus` Get-ScheduledTask function. One difference is that we first check if the RunAsUser parameter is specified, and then run the Get-ScheduledTask function with the correct parameters:
if ($RunAsUser) {
$tasks = Get-ScheduledTask -ComputerName $computername -RunAsUser $RunAsUser | Select-Object taskname,runasuser
}
else {
$tasks = Get-ScheduledTask -ComputerName $computername | Select-Object taskname,runasuser
}
if ($tasks) {
foreach ($task in $tasks) {
Write-Verbose "Processing task $($task.taskname)"
$outputtask = @{}
$outputtask.Computername = $computersystem.name
$outputtask.Connectivity = "Success"
$outputtask.Type = "ScheduledTask"
$outputtask.Name = $task.taskname
$outputtask.RunAsAccount = $task.runasuser
$output += $outputtask
}
}
In the end we output the gathered information. We first check if there is any information populated in the $output variable, as this might be empty if the RunAsAccount parameter is specified, and no services or scheduled tasks running as the specified account is found. If any information is found, we do a foreach loop to output each entry (a hash-table containing either service or task information) to the pipeline:
if ($output) {
foreach ($ht in $output) {
New-Object -TypeName PSObject -Property $ht
}
}
else {
$outputinfo = @{}
$outputinfo.Computername = $($computername)
$outputinfo.Connectivity = "Success"
$outputinfo.Type = $null
$outputinfo.Name = $null
$outputinfo.RunAsAccount = $null
New-Object -TypeName PSObject -Property $outputinfo
}
If the $output variable is empty we create a single object which indicates that we have successfully connected to the computer, but not found any matching services or scheduled tasks.
As a general recommendation in PowerShell; Always output the information as objects. This leaves it up to the consumer of the script or function to decide what to do next. For example he or she might decide to insert the information to a SQL-table, generate an HTML report or export the information to a CSV-file.
We will end the walkthrough by looking at some example usage:
We start by dot-sourcing the function into our current PowerShell session. There is a number of ways to define the function, have a look at the bottom of this article for more information.
Next we run the function without specifying a computer name, which means it will run on the local computer:
In the example above we specified “demo” as the value for the RunAsUser parameter. In this case “demo” is the name of the Active Directory domain, and thus all services and scheduled tasks running under a domain account will be returned.
In the next example the input for the computername parameter is gathered from a text-file, and the RunAsUser we`re looking for is “administrator”:
In the last example we`re retrieving all computer accounts in Active Directory which has the word “server” as part of the OperatingSystem property. We`re then “renaming” the name property of the computer accounts to “computername” using Select-Object, which in turn will make Get-RunAsAccount able to bind to the computername parameter when we pipe all the computer account objects to it:
We could also choose to export the information to a comma separated file:
Which in turn can be opened and customized in Microsoft Office Excel:
You can download the function from here. Feel free to leave a comment if you encounter a bug or have suggestions for improvement.
Demos, slides and videos from Nordic Infrastructure Conference 2012 sessions
On January 13th – 14th the Nordic Infrastructure Conference (NIC) was arranged in Oslo, Norway for the first time. The goal for the conference is creating a premier event for all IT-professionals in the Nordics, and the first edition of NIC was a great success with a number of excellent speakers.
Demos, slides and videos from my 3 sessions at the NIC conference is now available:
|
Session |
Description |
Slides |
Demos |
Video |
|
Introducing PowerShell 3.0 |
Since Windows 7 and Windows Server 2008 R2, Windows PowerShell has been a part of the core operating system, meaning we will see the next version of PowerShell in Windows 8. In this session we will look at what`s new in Windows PowerShell 3.0, based on the Windows Developer Preview released at the BUILD conference in September. You will get to see new features in PowerShell itself, as well as new modules for managing Windows 8 and Windows Server 8. |
|||
|
Practical PowerShell for the Windows Administrator |
Have you ever needed to perform the same task on more than one server? In this session you will see demos on how you can manage Windows systems using Windows PowerShell. You will get to see different techniques for remote management, demos of managing Hyper-V with and without System Center Virtual Machine Manager as well as several other demos. |
|||
|
Preparing for Office 365 |
In this session we will look at how you can prepare your organization for Office 365, ranging from technical requirements for clients and servers to identity management. The session will focus on the core infrastructure of the Office 365 service. |
Other PowerShell-related sessions at the conference was An introduction to WMI And PowerShell and WMI Eventing with PowerShell by PowerShell MVP Thomas Lee.
All the other sessions from the conference is available for viewing here.
2012 Microsoft MVP Award
On January 1st last year I was awarded the Microsoft MVP Award for my contributions in the PowerShell community. The MVP Award is valid for 1 year, and is based on the contributions for the past year. On January 1st this year I was re-awarded for my 2nd year as an MVP:
Dear Jan Egil Ring,
Congratulations! We are pleased to present you with the 2012 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in PowerShell technical communities during the past year.
I feel very honored to be part of this outstanding community, and I look forward to an exciting year coming with a new release of Windows and PowerShell.
Resources
Introducing the PowerShell Network Adapter Configuration module
For a Windows administrator, working with network adapters is a common task. A common approach many companies use is configuring servers with static IP addresses (IPv4) and clients using DHCP. The IP address is just one of many properties of a network adapter, as we also have properties like subnet mask, default gateway, DNS server search order and so on. Configuring these properties is usually performed during the initial setup of a computer, either manually or by a deployment mechanism.
The configuration of a network adapter is mostly static, however, from time to time some properties might need to be changed. In example the subnet on a network is expanded to meet new requirements, and thus the subnet mask property must be updated on computers not using DHCP. Another scenario is the setup of new DNS servers, with a decision not to keep the existing DNS servers` IP addresses. I recently faced the last scenario, where several hundred servers configured with static IP addresses needed to have their DNS configuration updated. Using Windows PowerShell the task can be automated, even if we need to perform the task on 10, 100 or 1000 servers. However, the more computers a script is run against, the more important it is to implement proper error handling and logging to keep track of which computers is updated.
The above task is just one of many potential tasks for configuring a network adapter. Since I was unable to find any existing PowerShell module/library for working with network adapters on Windows systems, I decided to create a project on Codeplex:
The PowerShell Network Adapter Configuration module
The PowerShell Network Adapter Configuration (PSNetAdapterConfig) module is a PowerShell module for working with network adapters on Windows-based computers. The module is using Windows Management Instrumentation (WMI) to retrieve and configure properties of network adapters.
The current release of the module makes use of the following WMI-classes:
The module currently contains 4 functions:
- Get-DNSServerSearchOrder – get the DNS client settings for a network adapter (the property name is DNSServerSearchOrder)
- Get-NetConnectionId – get the name of a network adapter (the property name is NetConnectionId)
- Set-DNSServerSearchOrder – change the configured DNSServerSearchOrder. This function contains two parameter sets, one for replacing the current DNSServerSearchOrder property value, the other for adding/removing IP addresses from the current value
- Set-NetConnectionId – change the name of a network adapter. In example, change the name from “Local Area Connection” to “Server VLAN 42”
I will add functions to the module when I find time, but I also hope that people in the community will contribute by either improving the existing functions, providing suggestions or creating new functions.
When downloading a PowerShell module from the internet (typically a zip-file), beginners often get into problems because they don`t know that the file first needs to be unblocked (Right-click the zip-file->Properties->Unblock). To overcome this challenge I created a Windows installer (MSI) file which is easy to install and does not need to be unblocked:
The default install path is %userprofile%\Documents\WindowsPowerShell\Modules, and the user have the option to override the module path.
The installer was created using Windows XML Installer (Wix), based on Chad Miller`s blog-post Building A PowerShell Module Installer.
When the module is installed, we can use Import-Module to import the module, and Get-Command to list the available commands:
As we can see there is also an alias for each of the commands (functions).
By using Get-Help we can see available parameters along with their descriptions, as well as several examples:
The functions supports both ValueFromPipeline and ValueFromPipelineByPropertyName, which means we can leverage the PowerShell pipeline. Have a look at example 3 on the above image to see how computers can be retrieved from Active Directory using Get-ADComputer, and then piped directly into the Set-DNSServerSearchOrder function.
The functions outputs PowerShell objects, which mean we can use regular PowerShell techniques to work with the data, in example converting the objects to HTML or CSV. I typically use Export-Csv to output the data to CSV-files which in turn can be converted to Excel spreadsheets:
The functions is using a try/catch construct, using the following logic:
- Ping the computer, if unsuccessful the property “Connectivity” on the output object is set to “Failed (ping”)
- Connect to the computer using WMI, if unsuccessful the property “Connectivity” on the output object is set to “Failed (ping”)
- The property “Connectivity” on the output object is set to “Successful” if step 1 and 2 succeeds
- Retrieve or change the applicable properties using WMI
When working with a large number of computers we can use Sort-Object in PowerShell to filter the output objects based on the Connectivity property, or the sorting functionality in Microsoft Excel if the output objects is piped to a CSV-file.
The final example I will show is using the Set-NetConnectionId function. On a test-computer we have a network adapter named “Local Area Connection 5”:
Using Set-ConnectionId we can specify the subnet for which network adapter to perform the change on (the above network adapter has an IP address of 192.168.56.10) and specify the new name of the network connection:
When the command has run we can see that the connection name for the adapter has changed:
One additional feature that might be included to this function is the ability to provide a hash-table with a mapping of subnets and NetConnectionIds, which will make it easy to create a consistent naming convention for network adapters.
As a final note, all functions has a Logfile parameter, allowing us to log error message to the specified file.
Requirements
- Windows PowerShell 2.0
- ICMP (ping) and WMI firewall openings from the computer running the module to the target computers
- Administrator permissions on the target computers
To avoid the firewall requirements, a workaround is running the functions from a PowerShell script locally on target computers using a software distribution product like System Center Configuration Manager.
Another option is to run the functions over PowerShell remoting.
Download and feedback
The module is available for download on the Codeplex project site http://psnetadapterconfig.codeplex.com. Please use the Discussions and Issue Tracker sites on the project site to report bugs and feature requests.
Resources
The functions is too long to walkthrough in a blog-post, so I will direct you to the following resources to get started working with advanced functions and modules in PowerShell:
An Introduction to PowerShell Modules by Jonathan Medd.
An Example ScriptModule and Advanced Function by Don Jones.
Ten tips for better PowerShell functions by James O`Neill.
Maximize the reuse of your PowerShell by James O`Neill.
Test-Connection error handling gotcha in PowerShell 2.0
The Test-Connection cmdlet in Windows PowerShell was introduced in version 2.0, with the purpose of sending ICMP echo request packets ("pings") to one or more computers as stated in the cmdlet`s documentation.
The cmdlet has a number of useful parameters, for example –Count to specify the number of request packets to send (the default is 4) and –Quiet to suppress errors and make the cmdlet return either true or false:
The –Quiet parameter is very useful when writing a script or function where you only want to perform an operation if the target computer responds to ping requests. A basic example of using this technique:
if (Test-Connection -ComputerName doesntexist -Count 1) { #Proceed with script operation }
A few weeks ago I stumbled upon a problem when trying to use a try/catch block in a PowerShell function. What I wanted to do was to catch a ping exception when using Test-Connection. Here is the code I was running:
try { Test-Connection -ComputerName doesntexist -Count 1 -ErrorAction stop } catch [System.Net.NetworkInformation.PingException] { 'Catched PingException' } catch { 'General catch' }
To my surprise, the PingException wasn`t catched:
I then tried setting up a new System.Net.NetworkInformation.Ping object, to see if the PingException catch worked when using the object`s Send-method:
This worked, so the problem seemed to be related to the Test-Connection cmdlet.
Earlier this week I attended the PowerShell Deep Dive conference in Frankfurt, which was part of The Experts Conference 2011. In the evening the organizers set up a Script Club, where the attendees could explore various PowerShell features together, as well as getting assistance in problem solving. Together with PowerShell MVP Jeff Hicks I sat down and looked into the issue with Test-Connection. As we couldn`t figure out why the PingException catch block didn`t work as expected, we got assistance from a PowerShell team member who was attending the conference, Jason Shirk.
Jason explained to us that there is a bug with Test-Connection`s ErrorAction parameter in PowerShell 2.0, which is resolved in PowerShell 3.0 (not in CTP 1). This means my example above will work in the next version of PowerShell. Until then, Jason showed us a workaround for PowerShell 2.0:
try { Test-Connection -ComputerName doesntexist -Count 1 -ErrorAction stop } catch [System.Management.Automation.ActionPreferenceStopException] { try { throw $_.exception } catch [System.Net.NetworkInformation.PingException] { 'Catched PingException' } catch { 'General catch' } }
The workaround is to go into the inner exception of ActionPreferenceStopException to perform the PingException catch.
Many thanks to Jason Shirk for the assistance. For others, I would highly recommend to attend the next PowerShell Deep Dive. In addition to great presentations, you also get to network with other PowerShell enthusiasts, as well as attending the very fun and exciting Script Club in the evenings.
Related resources
What`s New in Windows PowerShell 3.0
Since the release of Windows 7 and Windows Server 2008 R2, Windows PowerShell is included in the operating system and enabled by default. This means Windows PowerShell 3.0 will be available in the next version of Windows.
A preview version for developers of the next Windows version was released a few weeks ago, which means we also got a preview of Windows PowerShell 3.0. The preview version of the client operating system is available here, while the server version is available on MSDN.
Earlier this week the PowerShell team announced that a Community Technology Preview (CTP 1) is available for download, which means we can also try out PowerShell 3.0 on computers running Windows 7 and Windows Server 2008 R2. The current version of the Windows Management Framework includes Windows PowerShell 2.0, Windows Remote Management (WinRM) 2.0 and Background Intelligent Transfer Service (BITS) 4.0, while the new Windows Management Framework CTP contains Windows PowerShell 3.0, Windows Management Instrumentation (WMI) and Windows Remote Management.
Some of the most important new features in PowerShell 3.0 is listed in the previous mentioned announcement from the PowerShell team, but there is also a huge number of other new features.
A great number of persons in the PowerShell community has already started to discover and write about the new features. One of them is the new Windows PowerShell Web Access in the next version of Windows Server, which I`ve previously written an article about.
Instead of listing all the articles I`ve discovered so far in this article, I posted them as a TechNet Wiki article as part of the existing PowerShell V3 Guide:
TechNet Wiki: PowerShell V3 Guide
TechNet Wiki: PowerShell V3 Featured articles
I would like to encourage you to contribute to the TechNet Wiki article when you discover new writings about Windows PowerShell 3.0.
Windows PowerShell Web Access
In the Windows Server Developer Preview (“Windows 8 Server”) released recently, a preview version of Windows PowerShell 3.0 is also included. In addition to the many news in the next version of PowerShell which I won`t cover in this article is a brand new feature named Windows PowerShell Web Access. As the name indicates this makes it possible to use Windows PowerShell using a browser from a computer, in addition to mobile devices.
Installation, configuration and user experience
Windows PowerShell Web Access is available as a feature in the new Server Manager:
After the feature is installed, some additional steps which is described in %systemroot%\Web\PowerShellWebAccess\wwwroot\README.txt is required:
To complete the installation of Windows PowerShell Web Access, please perform the
following tasks:1) Open a Windows PowerShell console with elevated user rights.
To do this, right click on PowerShell.exe, or a Windows PowerShell shortcut,
and then click “Run as administrator.”2) Be sure your Windows PowerShell environment is configured to run scripts.
For more information, see “Running Scripts from Within Windows PowerShell”
(http://technet.microsoft.com/en-us/library/ee176949.aspx).3) Run the following script:
${env:\windir}\Web\PowerShellWebAccess\wwwroot\setup.ps1
This is typically C:\Windows\Web\PowerShellWebAccess\wwwroot\setup.ps1
4) Create a server certificate.
For a test server, you can create a self-signed certificate by using the
Web Server (IIS) management console:(${env:\windir}\system32\inetsrv\InetMgr.exe)
From within the IIS management console, open the Web Servers parent node.
This is typically the node immediately under the Start Page node.In the results pane, select “Server Certificates” on the center pane, then
select “Create Self-Signed Certificate.”5) Create an SSL binding.
In the IIS management console, select “Default Web Site,” and then click
“Bindings” on the “Actions” menu. Click “Add,” select “https” on
the “Type” pull-down menu, and then in the “SSL certificate” list, select the
certificate that you created in step 4.For more information about how to create a server certificate and an SSL binding,
see “How to Set Up SSL on IIS 7″
(http://learn.iis.net/page.aspx/144/how-to-set-up-ssl-on-iis-7).
The setup.ps1 script will create a new Web Application Pool and a new Web Application in Internet Information Services:
$ErrorActionPreference = ‘stop’
$wwwroot = “${env:\windir}\Web\PowerShellWebAccess\wwwroot”
if (!(Test-Path $wwwroot))
{
Write-Error “PowerShell Web Access has not been installed on this machine”
}
#
# Copy localized files to neutral location
#
foreach ($target in ($wwwroot,”$wwwroot\bin”))
{
foreach ($culture in (“en”,”en-us”,”qps-ploc”))
{
$source = “$target\$culture”
if (Test-Path $source)
{
copy “$source\*” $target
}
}
}
#
# Setup ASP.NET application
#
Import-Module WebAdministration
if (Get-WebApplication -name “pswa”)
{
Write-Error “The Windows PowerShell Web Access application (pswa) already exists on this machine”
}
New-WebAppPool “pswa”
New-WebApplication -Name “pswa” -Site “Default Web Site” -PhysicalPath $wwwroot -ApplicationPool “pswa”
If the script runs successfully, it returns the following output:
PS C:\> C:\Windows\Web\PowerShellWebAccess\wwwroot\setup.ps1
Name State Applications
—- —– ————
pswa Started
Path : /pswa
ApplicationPool : pswa
EnabledProtocols : http
PhysicalPath : C:\Windows\Web\PowerShellWebAccess\wwwroot
The final configuration step is to create and add a binding to a certificate as described in the link provided in the readme.txt file.
When done, you can access the feature by using the URL https://<servername>/pswa :
Specify credentials and a computer name to connect to, then hit the “Sign in” button. Another connection type available is “Connection URI”:
The options available under “Advanced Options”:
The available authentication types:
After signing in, you`ll be presented with a console looking like this:
The console host is called “ServerRemoteHost”:
Tab-completion works just like in the regular Windows PowerShell console host, and we also have access to the history by pressing the up and down arrows. To logoff, there is a Logoff-button in the bottom right corner.
The PowerShell Web Access also works perfectly fine on mobile devices. I`ve tried it on a Windows Phone 7 device, but unfortunately I don`t have any screen captures to share yet.
Congratulations to the Windows PowerShell team for providing this excellent new feature!
Note: Please be aware that this is a feature in a prerelease version of the next version of Windows Server, and thus the feature might be different in the final product.
Update 15.09.2011
Screen capture from PowerShell Web Access running on an Iphone:
Hyper-V: How to unbind a physical NIC from a Virtual Switch using WMI and PowerShell
If you`re not already familiar with networking in Microsoft Hyper-V I would recommend you to have a look at this whitepaper from Microsoft, which described how networking works in Hyper-V.
The following solution will describe a problem which might occur when configuring virtual networks in Hyper-V. Consider the following scenario:
- You`re about to configure a new external virtual network in Hyper-V using Hyper-V Manager remotely from another computer. This is a common scenario when working with the Core edition of Windows Server 2008/2008 R2.
- When selecting the physical NIC to bind to the new virtual network, you choose the adapter which you are remotely connecting to the Hyper-V host through.
What happens in this scenario is that the Virtual Switch Management Service is binding the external Ethernet port for the selected NIC to the Microsoft Windows Virtualization network subsystem. What normally should happen next is that the converted Ethernet port should be bound to the new virtual switch you are creating. However, this never happens since the NIC you are remotely managing the Hyper-V host through is no longer available in the parent operating system. This leaves the NIC in an “orphaned” state, since you cannot use the NIC in the parent operating system, and it`s not in use by any virtual networks.
To resolve this issue, whether using the full GUI version or the Core version of Windows Server, you need to manually unbind the the Ethernet port. There is an UnbindExternalEthernetPort available on the Msvm_VirtualSwitchManagementService WMI class, which is fully documented in this article on MSDN.
To invoke the WMI method we can use Windows PowerShell. To ease the procedure I`ve created a PowerShell function you can use if you ever come into the need for manually unbinding an external Ethernet port in Hyper-V:
Function Select-List
{
Param ([Parameter(Mandatory=$true ,valueFromPipeline=$true )]$InputObject,
[Parameter(Mandatory=$true)]$Property)
begin { $i= @() }
process { $i += $inputobject }
end { if ($i.count -eq 1) {$i[0]} elseif ($i.count -gt 1) {
$Global:counter=-1
$Property=@(@{Label=“ID”; Expression={ ($global:Counter++) }}) + $Property
format-table -inputObject $i -autosize -property $Property | out-host
$Response = Read-Host “Select NIC to unbind”
if ($response -gt “”) {
$I[$response]
}
}
}
}
function Remove-HVExternalEthernetPort {
$ExternalEthernetPort = Get-WMIObject -class “Msvm_ExternalEthernetPort” -namespace “root\virtualization” | Select-List -Property name
$HVSwitchObj = Get-WMIObject -class “MSVM_VirtualSwitchManagementService” -namespace “root\virtualization”
if ($ExternalEthernetPort) {
$HVSwitchObj.UnbindExternalEthernetPort()
}
else {
throw “An error occured. Choose a valid ExternalEthernetPort from the provided list”
}
}
Note: The Select-List function is a modified version of the Select-List function available in the PowerShell Management Library for Hyper-V available on CodePlex (see link below).
You can either paste the function into a PowerShell session or save it into ps1-file and dot source it. When done you can invoke the function like this:
When you`ve entered the index number for the NIC you want to remove, a return value of 0 indicates the operation succeeded. Any other value indicates an error (look at the previous mentioned MSDN-article for more information).
More resources on managing Hyper-V using PowerShell
PowerShell Management Library for Hyper-V – this is an excellent PowerShell module for managing Hyper-V available on CodePlex
System Center Virtual Machine Manager 2012: Scripting
System Center Virtual Machine Manager 2008 R2: Scripting
How to automatically convert Windows PowerShell transcripts into script-files
In Windows PowerShell we can use the Start-Transcript cmdlet to record PowerShell sessions to a text-file. This will record both the commands you`ve run as well as the output from the commands.
Windows PowerShell MVP Jeffery Hicks recently wrote a great tip in his Friday Fun series on his blog, which tells you how to convert a PowerShell transcript into a PowerShell script file. That is, you`ll get a ps1-file which contains the commands extracted from the transcript. Combined with an object event which triggers when PowerShell exits, this can be set up to happen automatically. Jeff actually blogged another Friday Fun tip a couple years ago which describes how to set up such an object event.
Lets have a look at an example on how this would work. First we launch a new PowerShell session and executes a few commands:
When we exit PowerShell we`ll get two files in a specified log directory:
The transcript file (txt-file) contains all commands, errors and output from our session:
The PowerShell script file (ps1-file) contains a script header and the commands from our session:
This means that every PowerShell session automatically generates a PowerShell script file which can be the foundation for a new script.
To set this up you first need to copy the Export-Transcript PowerShell function from Jeff`s blog-post and add it to your PowerShell profile (Microsoft.PowerShell_profile.ps1), in addition to the following:
|
001
002 003 004 005 006 007 008 009 |
#Define variable for the transcript path, which we`ll use to generate the path to the ps1-file
$transcriptlog = ("C:\PS-logs\PS-Transcript_"+"{0:yyyy-MM-dd_HH-mm-ss}" -f (Get-Date)+".txt") Start-Transcript -Path $transcriptlog | Out-Null #Export transcript to ps1-file on exit Export-Transcript -Transcript $transcriptlog -Script (($transcriptlog.Replace("Transcript","Script")).Replace("txt","ps1")) } | Out-Null |
While this is very useful, there is a few gotcha`s to be aware of:
- This doesn`t work if your exiting PowerShell using the X button. The PowerShell.Exiting event is only triggered when using the exit command.
- This doesn`t work in the Windows PowerShell ISE, since that PowerShell host doesn`t support transcripts.
- If you`ve customized your PowerShell prompt, you`ll need to tweak the Export-Transcript function to match the last letter in your prompt.
Getting starting with Cisco UCS PowerShell Toolkit
Cisco – widely known as a networking infrastructure vendor – entered the blade server market in 2009. Their offering is called Unified Computing System, described by Gartner as a fabric-enabled, enterprise-class platform with good integration of networking, virtualization, management tools and storage. On the 2011 Gartner Magic Quadrant for Blade Servers they`re defined as a visionary vendor, and it will be interesting to see if they can challenge the 3 leaders Dell, IBM and HP.
The Cisco Unified Computing System is quite different from traditional blade systems, in that the server profiles (so called service profiles) is independent from the physical blade servers. An example to describe what this means is that a physical blade server might fail and be replaced, while the server profile keeps unique ID`s like MAC addresses, World Wide Names (WWN`s) and so on. If using boot from SAN rather than local disk drives, physical interaction is not required to get the system back online if a spare blade server is available.
The UCS core components
- Blade Chassis – Blade server enclosure
- Cisco UCS Manager – Embedded into the Fabric Interconnect. Provides management capabilities
- Cisco UCS fabric interconnect – Provides networking (Ethernet/Fibre Channel) and management for connected blades and chassis`
- Fabric Extenders – Provides connection between the interconnect fabric and the blade enclosures
A photo showing the Cisco Unified Computing System architecture is available here (cisco.com). In regards of management, all aspects of Cisco UCS can be managed through an XML API. This makes it possible for 3rd parties to offer management solutions, and integration with other products. An example of a 3rd party product is the Cisco UCS Iphone/Ipad application for managing and monitoring the system. Links for more information on the management model and the XML API is available in the resources section in the bottom of this article.
Cisco UCS PowerShell Toolkit
Based on a customer request from an early adaptor, Cisco provided PowerShell support for managing their UCS product through the XMP API. With the Microsoft automation strategy in mind, this was an excellent choice. It will make integration into products like System Center Orchestrator (formerly Opalis) very easy, and the also make the product attractive for enterprises. The PowerShell administration tool is available as a module part of the Cisco UCS PowerShell Toolkit.
A great way to learn using the Cisco UCS PowerShell Toolkit is downloading the Cisco UCS Emulator. This is a virtual machine image which can be imported into VMware Player or VirtualBox. When the VM is up and running you can access both the UCS Manager (http URL is shown when the VM has started) and the XML API. A great feature is that you can import the configuration from a production UCS to simulate administration changes in a lab environment.
Next, you can download the latest versions of both the Cisco UCS PowerShell Toolkit (aka UCSMPowerTool) and the PowerShell Toolkit User Guide from this website.
The installer will by default put the files in %programfiles%\Cisco\UCSMPowerToolkit:
CiscoUCSPS.dll is the assembly which can be imported as a module in Windows PowerShell 2.0 and later. You can either double-click LaunchUCSPS.bat or invoke StartUCSPS.ps1 from an existing PowerShell session to get started. Alternatively you can use Import-Module from an existing PowerShell session like this:
Import-Module “C:\Program Files (x86)\Cisco\UCSMPowerToolkit\CiscoUCSPS.dll”
I would suggest rather than installing to the Program Files folder (which requires administrative privileges), that Cisco generates a module manifest and install the module to the default PowerShell module directory (C:\Users\<username>\Documents\WindowsPowerShell\Modules).
When the module is imported we can use Get-Command with the –Module parameter to list all command inside the CiscoUCSPS module:
The current version of the module contains 149 cmdlets, so all commands are not shown in the above screenshot.
The first thing we need to do is connect to an instance of the UCS Manager. If using the Cisco UCS Emulator you can view the management IP address when the virtual machine has started:
We then use the Connect-UCSM cmdlet to connect to the UCS Manager:
The default credentials for the UCS Emulator is config/config.
Next we can start exploring cmdlets like Get-Blade and Get-Vlan. Note that by default the cmdlets outputs a lot of information for each object, so I`ve picked out a few properties to show using Format-Table:
Going further it`s easy to automate things like adding VLAN and assigning it to a vNIC template:
Although the PowerShell coverage isn`t 100% yet, it`s possible to administer all aspect of the UCS directly through the XML API from PowerShell using the Invoke-XmlCommand cmdlet.
Resources
A Platform Built for Server Virtualization: Cisco Unified Computing System
Cisco Unified Computing Forums
Automating Cisco UCS Management with Windows PowerShell
PowerScripting Podcast – Josh Heller from Cisco on UCS and PowerShell
Cisco UCS Manager XML API Programmer’s Guide
Cisco UCS Manager API Management Information Model





