Windows Management and Scripting

A wealth of tutorials Windows Operating Systems SQL Server and Azure

Posts Tagged ‘PowerShell’

Powershell CMDLET for managing Windows Server 2012 Cluster

Posted by Alin D on January 17, 2013

If you manage Windows Failover Clusters, you may notice the Cluster.exe CLI command is missing after you install the Windows Server 2012 Failover Clustering feature. For years, systems administrators have used Cluster.exe to script the creation of clusters, move failover groups, modify resource properties and troubleshoot cluster outages. Yes, the Cluster.exe command still exists in the Remote Server Administration Tools (RSAT), but it’s not installed by default and is considered a thing of the past.

Another thing you may soon notice in Windows Server 2012 is the PowerShell and Server Manager Icons pinned to your taskbar. What you may not notice is that the default installation of the Windows Server 2012 operating system is now Server Core and contains more than 2,300 PowerShell cmdlets. Microsoft is sending a clear message that Windows servers should be managed just like any other data center server, both remotely and through the use of scripting. With Windows, that means PowerShell.

Fortunately, Windows Server Failover Clustering is no stranger to PowerShell. With Windows Server 2008 R2, 69 cluster-related PowerShell cmdlets assist with configuring clusters, groups and resources. This tip explores the new PowerShell cmdlets in Windows Server 2012 failover clusters.

With Windows Server 2012, a total of 81 failover cluster cmdlets can be used to manage components from PowerShell. New cluster cmdlets can perform cluster registry checkpoints for resources (Add-ClusterCheckpoint), monitor virtual machines for events or service failure (Add-ClusterVMMonitoredItem) and configure two new roles: Scale-Out File Servers (Add-ClusterScaleOutFileServerRole) and iSCSI Target Server (Add-ClusteriSCSITargetServerRole).
Windows PowerShell ISE

Windows PowerShell ISE

To list all the failover cluster cmdlets, use the PowerShell cmdlet “Get-command –module FailoverClusters” (Figure 1). I am using the built-in Windows PowerShell Integrated Scripting Environment (ISE) editor, which helps admins get familiar with all the failover clustering cmdlets.

In addition to the FailoverCluster cmdlets, Microsoft has several new modules of PowerShell cmdlets, including ClusterAwareUpdating with 17 new cmdlets, ClusterAware ScheduledTasks with 19 new cmdlets and iSCSITarget with 23 new cmdlets. There are many Cluster Aware Updating cmdlets, such as adding the CAU role (Add-CauClusterRole), getting an update report (Get-CauReport) or invoking a run to scan and install any new updates (Invoke-CauRun).

Cluster-Aware scheduled tasks are new to Windows Server 2012 and the Task Scheduler now integrates with failover clusters. A scheduled task can run in one of three ways:

ClusterWide on all cluster nodes
AnyNode on a random node in the cluster
ResourceSpecific on a node that owns a specific cluster resource

The new ScheduledTasks cmdlets create a cluster-aware scheduled task. In the table, you can see the cmdlets that register, get and set Clustered Scheduled task properties.
PowerShell Cmdlet     Description
Register-ClusteredScheduledTask     Creates a new clustered scheduled task
Unregister-ClusteredScheduledTask     Deletes a clustered scheduled task
Set-ClusteredScheduledTask     Updates existing cluster task
Get-ClusteredScheduleTask     Enumerates existing clustered tasks

To get an idea of how to use these PowerShell cmdlets, you first assign an action and trigger variable. The action variable specifies the program that is to be executed, such as the Windows calculator in the example below. The trigger variable sets up when the task is to be executed. The resulting cmdlets to schedule the task to run cluster-wide daily at 14:00 would look like this:

PS C:\> $action = New-ScheduledTaskAction –Execute C:\Windows\System32\Calc.exe

PS C:\> $trigger = New-ScheduledTaskTrigger -At 14:00 –Daily

PS C:\> Register-ClusteredScheduledTask -Action $action -TaskName ClusterWideCalculator -Description “Runs Calculator cluster wide” -TaskType ClusterWide -Trigger $trigger

TaskName         TaskType
——–         ——–
ClusterWideCa… ClusterWide

PS C:\>
Windows PowerShell Task Scheduler

While only PowerShell can be used to register, get/set and unregister Cluster-Aware scheduled tasks, you can use the Task Scheduler in Computer Management to view the cluster jobs (Figure 2).
iSCSI Target cmdlets
Cmdlets Failover Clusters3

Finally, failover clusters can now be configured with a highly available iSCSI Target Server. This role allows you to create and serve iSCSI LUNs in a highly available fashion to clients across your enterprise. To add this new cluster role, use the Cmdlet Install-WindowsFeature –name FS-iSCSITarget-Server (or use Server Manager) to install the iSCSI Target Server role. Then, use the new cmdlet Add-ClusteriSCSITargetServerRole to create the iSCSI Target resource and associate it with shared storage. You can then leverage the new iSCSI Target cmdlets to configure iSCSI LUNs (Figure 3).

There is no shortage of PowerShell cmdlets in Windows Server 2012 to help you manage your failover clusters. In addition to creating, configuring and troubleshooting your cluster, you can use PowerShell cmdlets to add new scale-out file server, iSCSI Target Server roles, clustered scheduled tasks and Cluster-Aware Updating.

About these ads

Posted in Windows 2012 | Tagged: , , | Leave a Comment »

How Exchange 2010 leverages Windows PowerShell Part 1

Posted by Alin D on May 30, 2011

From an Exchange perspective, Windows PowerShell provides a way to perform tasks quickly and simply in a variety of manners, from one-off interventions that process one or
more Exchange objects to complex scripts that perform tasks such as mailbox provisioning. Most administrators cut their teeth with PowerShell by using the Exchange Management
Shell (EMS) to do simple things, like using Get-Mailbox to report on a mailbox’s properties and Set-Mailbox or Set-CASMailbox to set a property, before moving on to the more
esoteric commands to manipulate connectors, control ActiveSync, update Active Directory with user safe lists, and so on. The saying is that almost anything is possible with Windows
PowerShell, and this is certainly true when you dedicate enough energy and time to mastering the language, not to mention the time necessary to scan the Internet for useful
examples of scripts that can be adapted to meet your needs.
Prior to Exchange Server 2007, business logic was scattered in components throughout the product. The management console did things—even simple things like setting a property
on a server—using different code and logic than in the setup program, and the application programming interfaces (APIs) included in the product usually provided a third way to
approach a problem. The result was a total lack of consistency, duplication of code, and a tremendous opportunity to create bugs in multiple places. In addition, there was no way for
administrators to automate common tasks to meet the needs of their organization; essentially, if an Exchange engineer didn’t code something into the product, it couldn’t be done.
Figure 3-1 illustrates the central role that Windows PowerShell now plays in the Exchange architecture and how it provides a central place to encapsulate business logic that
underpins the Exchange setup program, the Exchange Management Console (EMC), the Exchange Control Panel (ECP), and the EMS.
Exchange’s use of Windows PowerShell to implement functionality presented by the graphical user interface (GUI) of EMC and the setup program is probably the most extensive of
any Microsoft application. As explored throughout this book, the options presented by EMC to work with mailboxes, connectors, servers, and other objects invariably result in a call to
one or more PowerShell cmdlets that actually do the work. It’s also worth emphasizing that the functionality presented to administrators, specialist users (those who perform a subset
of administrative tasks such as maintaining user details), and normal users is all based on PowerShell.
The exact scope and range of the functionality presented to any individual user is determined by the permissions granted to them through role-based access control (RBAC).
RBAC is a huge shift in the way that Exchange manages and grants permissions to users that is designed to function across a range of different environments, from a single-server
organization to an organization composed of a mixture of on-premise and hosted servers. The need to accommodate such a wide range of environments is also the reason Microsoft has moved from local PowerShell (where all commands are executed on a local server) to remote PowerShell (where commands are redirected through Microsoft Internet Information
Services [IIS] for execution on a target server). We’ll get to the details of just how remote PowerShell and RBAC work together in the Exchange Server 2010 version of EMS shortly.

image

organization. The RTM release of Exchange 2010 includes 584 cmdlets that are added by EMS to join the standard set of Windows PowerShell cmdlets, including cmdlets to work with
the system registry, the file system, variables (including environmental variables), and so on. The number of cmdlets grows again to 619 in Exchange 2010 SP1. For example, the Export-
Mailbox and Import-Mailbox cmdlets that are used to export and import mailbox data from Outlook personal storage (PST) files are replaced by the New-MailboxExportRequest and New-MailboxImportRequest cmdlets and other associated cmdlets used to control the requests.

By comparison, Exchange 2007 includes 394 cmdlets, 26 of which are removed in Exchange 2010 (largely because of the demise of storage groups). The 216 new cmdlets provided in
Exchange 2010 reflect the new functionality in the product, such as the introduction of the RBAC model, mailbox archives, and the Database Availability Group (DAG), along with the
expansion of existing functionality such as messaging records management.
Windows PowerShell has been at the heart of Exchange since Exchange 2007, and its use and syntax are fundamental skills for administrators to master. In fact, many of the more
hardcore Exchange administrators prefer EMS to EMC because of the additional flexibility that EMS provides. This chapter lays out the basics of Windows PowerShell and sets the
stage for the examples of Windows PowerShell found in other chapters. To begin, let’s review the biggest change that Microsoft has made to EMS in Exchange 2010: the transition
from a purely local implementation to remote PowerShell and its associated technology.

Once we understand how to connect to EMS, we’ll go on to review how to use cmdlets to get work done.

Remote PowerShell

Exchange Server 2007 was the first major Microsoft server product to embrace Windows PowerShell extensively. Windows PowerShell has a relatively short history, and its 1.0 release
exhibited some of the flaws that you’d expect. Inconsistencies in syntax are easily overcome, but the lack of remote capability was more serious because it required the installation of
Windows PowerShell and its snap-in (set of cmdlets) for Exchange on any workstation or server from which you wanted to perform management tasks. In reality, this shortcoming is often overlooked because Exchange administrators are accustomed to having to install software before they can operate. Installing software is an acceptable requirement i environments where all the servers are under your control and within your own network, but it causes problems when you want to manage servers remotely. The Microsoft introduction
of online services where companies will be able to run their Exchange environments inside large Microsoft datacenters means that remote management has taken on new importance.
Exchange 2010 includes many new features designed to ease the transition to online services, and remote PowerShell provides the fundamental building block for management.
The combination of remote PowerShell with RBAC allows administrators to manage objects residing on a server in a remote datacenter as easily as you can manage objects on a local
server.

Exchange 2010 extends the concept of remote management to support the remote execution of commands in a secure manner using HTTPS and a Kerberos-based encryption mechanism that is easily manageable through firewalls (assuming that port 80 is open). Remote PowerShell is used for all EMS sessions in Exchange 2010. Even if you are logged on to an Exchange server and want to use EMS to change a property of that server, EMS still creates a remote session to the local server to do the work. The same applies for EMC, because Exchange creates a remote session when you log on to connect to a server in the local Active Directory site to retrieve information about the organization and then display it in the console. In effect, remote PowerShell replaces local PowerShell in Exchange 2010 for all server roles except Edge servers. The sole exception is for commands used during setup, which continue to execute locally. The removal of local PowerShell and the concentration on the combination of remote PowerShell and RBAC as the basis for administrative control over Exchange components is a major change in the product. The implementation of remote PowerShell for Exchange 2010 separates business logic into code that runs on the client and code that runs on the Exchange server. It is based on common Windows components such as Windows PowerShell 2.0 and the WS Management model (WS-Man and Windows Remote Management, WinRM). The discussion at http://blogs.msdn.com/powershell/archive/2009/01/06/manage-winrm-settings-with-wsman -provider.aspx provides useful background about how Windows PowerShell remoting is built on top of WinRM. Collectively, the Windows components combine to provide an effective ability to perform Exchange management operations remotely.
The logic for replacing local PowerShell with the remote model is simple. Just like the change in Exchange 2007 to force all messages to flow through the transport system so that a single common place existed to apply features such as transport rules, remote PowerShell forces Exchange administration to flow through RBAC so that a PowerShell session will only ever include the cmdlets necessary to do the job. The logic for keeping local PowerShell on Edge servers is simple, too. These servers are isolated from the rest of the organization so they do not have access to the RBAC roles. Anyone who logs onto an Edge server as an administrator operates in a management context of just that server and has complete control over that server. However, he cannot affect any other server or object in the Exchange organization.
The need to support hosting platforms such as Microsoft Business Productivity Online Services (BPOS) was a major influence on Exchange’s move to remote PowerShell. Providing
a secure and controllable mechanism that permits administrators to execute privileged commands to control the subset of objects that they own inside an infrastructure that is
controlled and managed by someone else is always a difficult task, especially when all the data have to pass across the Internet. Exchange 2007 controls access to its management
cmdlets through access control lists (ACLs) that are linked to Active Directory accounts. If the ACLs on your account mark you as an Exchange administrator, you can use Windows
PowerShell to manage Exchange; if not, you can’t. However, in an online services environment where many different companies share the same multitenant server and storage
infrastructure, it is highly unlikely that you will share the same Active Directory. Trust relationships and directory synchronization provide answers that have been used in hosting
environments, but these solutions often require a good deal of effort to set up and maintain. Microsoft takes a new approach to the management of permissions in Exchange
2010 with the introduction of RBAC. The concept is not new and has been used in previous authentication or identity management systems on UNIX and other platforms. What’s different here is its application to provide Exchange with a method to extend RBAC so that roles apply remotely.

How to flow remotely

To understand how remote PowerShell and RBAC work together, let’s examine how an administrator might create a new mailbox on a remote server. In this example, the administrator
works on a help desk and has been assigned a role that allows her to create new mailboxes and update the properties of existing mailboxes. We also assume that the user’s account is enabled to use remote PowerShell. In many cases, people in specialist roles such as help desk personnel will use the EMC or the ECP to perform tasks, but an experienced Exchange administrator might prefer to use a command-line interface because of its power and flexibility when compared to either EMC or ECP.
Next figure lays out the various components used by remote PowerShell from the local PowerShell host on a workstation or server across the network to IIS and the PowerShell
application running there. The other components are the PowerShell engine and the complete set of cmdlets available to Exchange 2010, the Exchange authorization library that
handles the interpretation of roles in terms of the cmdlets that each RBAC role can use, and the Active Directory driver used to read data from Active Directory. For the purpose of this
discussion we’ll assume that the account used has been assigned a role such as Recipient Management and is enabled for remote PowerShell. If you are unsure about the account’s
status, you can enable it to use remote PowerShell as follows:
Set-User –IdentityAccountName –RemotePowerShellEnabled $True
All PowerShell sessions flow through IIS because even a local connection goes through localhost.
All Exchange 2010 servers support IIS and the PowerShell virtual directory, or vdir, and all are members of the Exchange Trusted Subsystem security group and therefore can manipulate any object in the organization.

image

If you run EMS on a workstation or server that has the Exchange management components installed, EMS creates a remote session automatically as part of its initialization process. If
you run PowerShell on a workstation that doesn’t have the Exchange management components installed, you will have to specify the name of the server with which you want to
work. This is done with the New-PSSession cmdlet, passing the name of the server to which to connect in the form https://fqdn/PowerShell/. This cmdlet creates a secure authenticated
connection to IIS running on the target server and begins a session there by checking the role held by the account that initiates the connection.

IIS uses the RBAC mechanism to check the user’s role and associated permissions via the Exchange Authorization Library (a new component in Exchange 2010). The Exchange Authorization Library (or ADDriver) connects to Active Directory to use it as the definitive source of information about accounts and supplements these data with its knowledge
about the Exchange-specific roles that administrators have assigned to users. During a PowerShell session, ADDriver connects to a domain controller in the local site to fetch
data from Active Directory and keeps this connection throughout the session (something referred to as DC affinity). This is different from the behavior that exists in Exchange 2007
because all PowerShell sessions on a server run in the same process, so you cannot have a static setting because it might be inappropriate for some sessions. In Exchange 2007, each
PowerShell session functions in its own process and you have complete control over the Active Directory settings. Many PowerShell cmdlets support the –DomainController parameter
to allow you to connect to a specific domain controller (specifying the fully qualified domain name [FQDN]) should the need arise. Things are a little more complicated in a hosted environment where you are connected to your local network but need to work with Exchange data in a forest maintained by the hosting provider. In this instance, a directory synchronization process occurs to synchronize the basic account information from the local Active Directory forest and the data held in the Active Directory forest managed by the hosting provider.
A role group defines the set of administrative actions that a user is allowed to perform inside Exchange and can be resolved into a set of PowerShell cmdlets that the user is
allowed to use within her PowerShell session. Because our user works with mailboxes as defined by the Recipient Management role group, the set of cmdlets that she can use
includes commands with easily identified purposes such as New-Mailbox, Set-Mailbox, Get-Mailbox, and so on. Unlike the situation with Exchange 2007, where the complete set
of cmdlets is available after you load the Exchange snap-in to a PowerShell session, RBAC ensures that the user can execute only the cmdlets required to perform her role. If you
are an Exchange administrator who holds the Organization Management role, you’ll have access to almost the full set of cmdlets (to gain access to the full set, you have to grant your
account access to some minor roles). However, if your account has been assigned only the roles necessary to be able to work with recipients, you’ll see just the cmdlets covered by the
roles assigned to you.

Users are not normally aware that they are restricted in terms of available cmdlets unless they attempt to use one to which they do not have access. The point is that they shouldn’t
care that they can’t use hundreds of cmdlets, many of which do obscure things like setting properties on messaging connectors or one-off operations such as creating a new DAG.
Instead, RBAC makes sure that users can only access the cmdlets that they need to get their job done.

Posted in Exchange | Tagged: , , , , , , , , , , , , , , , , , | Leave a Comment »

PowerShell Cmdlets for SharePoint

Posted by Alin D on January 19, 2011

The set of cmdlets which come with PowerShell is restricted to generic cmdlets and those intended for managing aspects of the Windows Server OS. If you are unfamiliar with using PowerShell cmdlets please check out PowerShell Cmdlets Tutorial first.

For technologies such as SharePoint, PowerShell uses snap-ins which are .NET Framework assemblies that contain custom PowerShell cmdlets. The SharePoint 2010 snap-in for PowerShell contains over than 500 cmdlets which can be used to perform a wide variety of SharePoint admin tasks. This PowerShell SharePoint snap-in is loaded automatically when the SharePoint 2010 Management Shell is run. If you
start the standard PowerShell console, you will need to manually load the snap to access the SharePoint cmdlets. Two native PowerShell cmdlets can assist with this: the Get-PSSnapin cmdlet retrieves info about all the snap-ins registered in the system, and the Add-PSSnapin cmdlet actually loads the snap-ins into the current PowerShell session.

The below example uses the Get-PSSnapin cmdlet with the switch parameter Registered to return the name of the SharePoint 2010 snap-in:

PS > Get-PSSnapin -Registered
Name : Microsoft.SharePoint.PowerShell
PSVersion : 1.0
Description : Register all administration Cmdlets for Microsoft Share- Point Server

The below example shows how to add the snap-in using the Add-PSSnapin cmdlet:

PS > Add-PSSnapin Microsoft.SharePoint.PowerShell

Once the SharePoint snap-in has been added, you can access all the SharePoint cmdlets. The PowerShell console and the SharePoint 2010 Management Shell differ in how threads are created and subsequently used. The standard PowerShell console runs each pipeline (as demarcated by a press of the “Enter” button), function, or script on its own thread, in contrast the SharePoint 2010 Management Shell runs each line, function, or script on one single thread. When using the SharePoint object model with PowerShell, running code on numerous different threads can result in memory leaks, in contrast, commands which run on the same thread have a lower chance causing leaks. This is because several SharePoint objects are still using unmanaged code.
The threading model which is used is determined by the the ThreadOptions property value of each PowerShell runspace (every PowerShell console window is a runspace). The SharePoint 2010 Management Shell utilizes the ReuseThread option set in the SharePoint.ps1 file which is executed every time the shell is started from the SharePoint 2010 menu group. However, the standard PowerShell console, does not have this option configured by default and therefore uses UseNewThread.
It is normally considered best practice is to set the ThreadOption property to ReuseThread when working with SharePoint using the PowerShell console. The below sample shows how to set the ThreadOption property:

PS > $Host.Runspace.ThreadOptions = "ReuseThread"

To find SharePoint Cmdlets, PowerShell includes a useful cmdlet named Get-Command which returns basic info about cmdlets and other elements of PowerShell commands, such as functions, aliases, filters, scripts, and applications. All nouns of SharePoint cmdlets start with SP. Therefore you can retrieve all SharePoint cmdlets by just using Get-Command’s –Noun parameter followed with SP*:

PS > Get-Command -Noun SP*

The asterisk (*) performs a wildcard match retrieving all cmdlets, aliases, functions, etc where the noun starts with SP. You can find different types of SharePoint cmdlets by specifying for example that you want only cmdlets returned using the CommandType parameter:

PS > (Get-Command -Name *-SP* -CommandType cmdlet).Count

Cmdlet New-SPSite New-SPSite [-Url]  [-Language ] [-
Cmdlet Remove-SPSite Remove-SPSite [-Identity]  [-Delet
Cmdlet Restore-SPSite Restore-SPSite [-Identity]  -Path
Cmdlet Set-SPSite Set-SPSite [-Identity]  [-OwnerAli

The output from the command shows the cmdlets available for working with site collections. Looking at the verbs in these cmdlets, you will notice that they are self-describing. Get is used for getting info, Set is for modifying site collections, etc. You can go even deeper and get info on a specific cmdlet using Get-Command to retrieve information on the Get-SPSite cmdlet for example:

PS > Get-Command Get-SPSite
CommandType Name Definition
----------- ---- ----------
Cmdlet Get-SPSite Get-SPSite [-Limit ] [-WebApplication

That should get you started with SharePoint Cmdlets, in future articles we will dig deeper into using PowerShell for SharePoint.

Posted in Powershell | Tagged: , , , | Leave a Comment »

Import-SPSite -Imports a Site to from a Backup File

Posted by Alin D on January 10, 2011

## =====================================================================
## Title       : Import-SPSite
## Description : Imports a Site to from a Backup File
## Date        : 24/11/2009
## Input       : Import-SPSite [[-url] <String>] [[-File] <String>] [[-Location] <String>]
## Output      :
## Usage       : Import-SPSite -url http://moss -file Backup.bak -Location C:Backup
## Notes       : Adapted From Niklas Goude Script
## Tag         : Site, Sharepoint, Powershell
## Change log  :
## =====================================================================
param (
[string]$url = “$(Read-Host ‘url [e.g. http://moss%5D&#8216;)”,
[string]$File = “$(Read-Host ‘Backup File Name [e.g. Backup.bak]‘)”,
[string]$Location = “$(Read-Host ‘Backup File Location [e.g. C:Backup]‘)”
)
function main() {
[void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
Import-SPSite -url $url -File $File -Location $Location
}
function Import-SPSite([string]$url, [string]$File, [string]$Location) {
$SPImport = New-Object Microsoft.SharePoint.Deployment.SPImport
$SPImport.Settings.SiteUrl= $url
$SPImport.Settings.BaseFilename = $File
$SPImport.Settings.FileLocation = $Location
$SPImport.Settings.IncludeSecurity = “All”
$SPImport.Run()
}
main

## =====================================================================## Title       : Import-SPSite## Description : Imports a Site to from a Backup File## Date        : 24/11/2009## Input       : Import-SPSite [[-url] <String>] [[-File] <String>] [[-Location] <String>]## Output      : ## Usage       : Import-SPSite -url http://moss -file Backup.bak -Location C:Backup## Notes       : Adapted From Niklas Goude Script## Tag         : Site, Sharepoint, Powershell## Change log  :## =====================================================================
param (
[string]$url = “$(Read-Host ‘url [e.g. http://moss%5D&#8216;)”,    [string]$File = “$(Read-Host ‘Backup File Name [e.g. Backup.bak]‘)”,   [string]$Location = “$(Read-Host ‘Backup File Location [e.g. C:Backup]‘)”)
function main() {
[void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
Import-SPSite -url $url -File $File -Location $Location}
function Import-SPSite([string]$url, [string]$File, [string]$Location) {
$SPImport = New-Object Microsoft.SharePoint.Deployment.SPImport $SPImport.Settings.SiteUrl= $url $SPImport.Settings.BaseFilename = $File $SPImport.Settings.FileLocation = $Location $SPImport.Settings.IncludeSecurity = “All” $SPImport.Run()}
main

Posted in Powershell | Tagged: , , | Leave a Comment »

Add-SPList – Creates a New Sharepoint List

Posted by Alin D on January 10, 2011

## =====================================================================
## Title       : Add-SPList
## Description : Creates a New SharePoint List
## Input       : Add-SPList [[-url] <String>] [[-List] <String>] [[-Description] <String>] [[-Type] <String>]
## Output      :
## Usage       : Add-SPList -url http://moss -List Users -Description “Company Users” -Type “Custom List”
## Notes       : Adapted From Niklas Goude Script
## Tag         : List, Sharepoint, Powershell
## Change log  :
## =====================================================================
param (
[string]$url = “$(Read-Host ‘url [e.g. http://moss%5D&#8216;)”,
[string]$List = “$(Read-Host ‘List Name [e.g. My List]‘)”,
[string]$Description = “$(Read-Host ‘List Description [e.g. My New List]‘)”,
[string]$Type = “$(Read-Host ‘Type of List [e.g. Custom List]‘)”
)
function main() {
[void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
$OpenWeb = Get-SPWeb $url
$ValidChoices = ($OpenWeb.ListTemplates | Select Name) | ForEach { $_.Name }
$OpenWeb.Dispose()
if($ValidChoices -eq $Type) {
Add-SPList -url $url -List $List -Description $Description -Type $Type
} else {
Write-Host “$Type is not a Valid type of List, Please Choose one of the Following” -ForeGroundColor Red
$ValidChoices
}
}
function Get-SPSite([string]$url) {
New-Object Microsoft.SharePoint.SPSite($url)
}
function Get-SPWeb([string]$url) {
$SPSite = Get-SPSite $url
return $SPSite.OpenWeb()
$SPSite.Dispose()
}
function Add-SPList([string]$url, [string]$List, [string]$Description, [string]$Type) {
$OpenWeb = Get-SPWeb $url
if($OpenWeb.Lists | Where { $_.Title -eq $List}) {
Write-Host “List: $($List) Already Exists.” -ForeGroundColor Red
} else {
$TemplateType = $OpenWeb.ListTemplates[$Type]
[void]$OpenWeb.Lists.Add($List, $Description, $TemplateType)
}
$OpenWeb.Dispose()
}
main

## =====================================================================## Title       : Add-SPList## Description : Creates a New SharePoint List## Input       : Add-SPList [[-url] <String>] [[-List] <String>] [[-Description] <String>] [[-Type] <String>]## Output      : ## Usage       : Add-SPList -url http://moss -List Users -Description “Company Users” -Type “Custom List”## Notes       : Adapted From Niklas Goude Script## Tag         : List, Sharepoint, Powershell## Change log  :## =====================================================================
param (
[string]$url = “$(Read-Host ‘url [e.g. http://moss%5D&#8216;)”,    [string]$List = “$(Read-Host ‘List Name [e.g. My List]‘)”,    [string]$Description = “$(Read-Host ‘List Description [e.g. My New List]‘)”,    [string]$Type = “$(Read-Host ‘Type of List [e.g. Custom List]‘)”)
function main() {
[void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
$OpenWeb = Get-SPWeb $url $ValidChoices = ($OpenWeb.ListTemplates | Select Name) | ForEach { $_.Name } $OpenWeb.Dispose()
if($ValidChoices -eq $Type) {
Add-SPList -url $url -List $List -Description $Description -Type $Type
} else { Write-Host “$Type is not a Valid type of List, Please Choose one of the Following” -ForeGroundColor Red $ValidChoices }}
function Get-SPSite([string]$url) {
New-Object Microsoft.SharePoint.SPSite($url)}
function Get-SPWeb([string]$url) {
$SPSite = Get-SPSite $url return $SPSite.OpenWeb() $SPSite.Dispose()}
function Add-SPList([string]$url, [string]$List, [string]$Description, [string]$Type) { $OpenWeb = Get-SPWeb $url
if($OpenWeb.Lists | Where { $_.Title -eq $List}) {
Write-Host “List: $($List) Already Exists.” -ForeGroundColor Red
} else {
$TemplateType = $OpenWeb.ListTemplates[$Type] [void]$OpenWeb.Lists.Add($List, $Description, $TemplateType) }
$OpenWeb.Dispose()}
main

Posted in Powershell | Tagged: , , | Leave a Comment »

Invoke Best Practices Analyzer on remote servers using PowerShell

Posted by Alin D on October 3, 2010

Best Practices Analyzer (BPA) is a management tool integrated in Windows Server 2008 R2 used to scan server roles according to Microsoft best practice guidelines.

Included in the initial release for Windows Server 2008 R2 are the following BPA models:

  • Active Directory Domain Services
  • Active Directory Certificate Services
  • Domain Name System (DNS) Server
  • Remote Desktop Services
  • Web Server (IIS)

Since then several new BPA models are released and available both as separate downloads as well as through Windows Update:

At the time of this writing, a BPA model for 12 of 17 server roles in Windows Server 2008 R2 are available.
The 5 that are not available are:

  • Active Directory Federation Services (ADFS)
  • Active Directory Lightweight Directory Services (AD LDS)
  • Fax Server
  • Print and Document Services
  • Windows Deployment Services

In Server Manager, a BPA summary are available for each installed server role that an BPA Model exists for:

image

When looking at the properties for an item in BPA you get more information as well as a link to Microsoft TechNet where more information are available for the specific subject:

image

BPA are built as a PowerShell module, meaning that a PowerShell cmdlet (Invoke-BPAModel) are run in the background when you scan a server role from Server Manager:

image

This is a great feature to examine if your server roles are configured according to Microsoft`s best practices, however, if you got many servers it will take some time to log on to each server and scan each server role. In addition you don`t get any centralized reporting this way.

Since BPA are based upon Windows PowerShell it`s possible to solve this using the BPA PowerShell module and PowerShell remoting:

image

image

I`ve created a sample script to accomplish this, named Invoke-BPAModeling, with the following functionality:

  • Invoke BPA for all available server roles on specified remote servers
  • E-mail reporting
  • File reporting to CSV and HTML

You need to customize the initial variables on the top of the script. You can enable/disable reporting using these variables, as well as specify which servers to work against, SMTP server for e-mail reporting and paths to CSV/HTML reports.
By default, only items with a severity of “Error” and “Warning” are reported. You can change this to also include “Informational” severities by configuring IncludeAllSeverities to true.
On the server running the script from, the Active Directory module for PowerShell must be installed if you want to retrieve computer names from Active Directory. In the sample,  the script are configured to retrieve all computer accounts listed with Windows Server 2008 R2 as operating system.
You might choose alternate methods, like importing the computer names from a csv-file.
.
I would recommend that you approve the new BPA models mentioned at the beginning of this blog post in WSUS prior to running the script.
The script requires that PowerShell remoting are enabled and configured on the remote servers. Also note that there is a known issue with the BPA module; When the PowerShell execution policy are set to any other than “Undefined” or “Unrestricted” , an error occurs. I`ll update this blog-post as soon as a fix are provided from Microsoft.

When the script executes, it displays the progress based upon the total number of computers running against:

image

Sample e-mail report containing both CSV and HTML reports as attachment:

image

Sample HTML-report:

image

Sample CSV-report converted to an Excel spreadsheet:

image

Feel free to customize the script for your needs, as well as suggest improvements.

Resources

Best Practices Analyzer on Microsoft TechNet

Posted in Windows 2008 | Tagged: , , , , , , , , , , , , , , , | Leave a Comment »

Windows 7 – PowerShell 2.0

Posted by Alin D on June 22, 2010

Explore how Windows PowerShell 2.0 can help increase the productivity of IT professionals by providing a powerful, complete scripting language to automate repetitive tasks and conduct remote troubleshooting. It delivers a growing set of cmdlets that can be used to manage Windowsbased PCs and servers, and it can be easily extended.

Posted in Windows 7 | Tagged: , | Leave a Comment »

HOW-TO: Powershell Set-Variable Command

Posted by Alin D on June 20, 2010

How to use the PowerShell set-variable command within the PowerWF studio environment. PowerWF Studio is a suite of tools leveraging PowerShell and Windows Workflow for automation and administration of physical and virtual environments. Leveraging VMware’s PowerCLI, VIX API plus several other PowerWF activities packs, PowerWF Studio for VMware offers levels of automation typically only seen in enterprise class solutions. The product supports management of VMware Server, Workstation, Player, and Virtual Infrastructure (both ESX and vCenter).

Posted in Windows 7 | Tagged: , , , | Leave a Comment »

Embedded PowerShell

Posted by Alin D on June 20, 2010

Download / Read More here: blog.powerwf.com In this screencast Ben shows off the new embedded PowerShell window in PowerWF Studio. Ben opens a ps1 then inserts that script as a workflow. Ben uses the PowerShell as a shell then selects a command line by swiping it then inserts that as a workflow and plays it. The embedded PowerShell pane is available in build 0.9.3572.16911 and later if PowerShell 2.0 is installed on the machine where PowerWF Studio is running. PowerWF Studio is a suite of tools leveraging PowerShell and Windows Workflow for automation and administration of physical and virtual environments. Leveraging VMware’s PowerCLI, VIX API plus several other PowerWF activities packs, PowerWF Studio for VMware offers levels of automation typically only seen in enterprise class solutions. The product supports management of VMware Server, Workstation, Player, and Virtual Infrastructure (both ESX and vCenter).

Posted in Windows 7 | Tagged: , | Leave a Comment »

Using Windows 7 PowerShell Scripting Environment

Posted by Alin D on June 11, 2010

Using Windows 7 PowerShell Scripting Environment

Posted in Windows 7 | Tagged: , , , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 446 other followers

%d bloggers like this: