Browsed by
Category: PowerShell

Order is everything when setting up SharePoint on Azure IaaS

Order is everything when setting up SharePoint on Azure IaaS

I spent a bunch of time with my buddy Kirk Evans while at DevConnections in Las Vegas last month, some drinking and watching football, but mostly learning about running SharePoint on Azure. Azure IaaS has come a long way, but is still confusing & troublesome at times. I have written a few PowerShell tools that help me and I will share them in some future posts.

I started playing with SharePoint on Azure IaaS on my own without doing much reading. My goal in this was to see how intuitive it was to get things setup and going for the average person. Once in the console creating a VM was very quick and simple. I was up and running on a pre-built Windows Server image in no time. This was great.

Then I decided that I wanted to build a SharePoint farm. I deployed out 2 addtional VMs. I built an Active Directory and attempted to join the other 2 servers to the domain. This is where I ran into problems.

There are some building blocks that need to first be put in place before you start building servers if you want them to be able to communicate with one another.

The first is the Affinity Group (AG). An AG is required before you can create a Virtual Network. The way that Kirk explained it, the AG is a container to keep your Virtual Network in a single data center. To create an AG you will either use PowerShell or go to Settings at the bottom of the Management Portal and find Affinity Groups as the fourth of five options.

1-1-2014 10-30-49 PM

Next create the Virtual Network and assign it ot the AG.

2

After the Virtual Network is created you will be able to setup a Cloud Service. The Cloud Service is going to be the container for your VMs.

3

This process sounds uber simple, but the order of things matters here. Now you can create your VMs. Once you have your VMs and your DNS server built you can go in and specify the Domain Controller as a DNS server.

This is where you will hit a snag. In the normal course of events you would be running a domain controller on a static IP address. Unfortunately this is not something that you can do on Azure IaaS. Every time you deprovision a VM, which you have to do unless you want to get charged, your IP address reservation can get taken by another machine.

My solutions to this problem was fairly simple:

1.) Create a virtual network for each of my environments
2.) Always start the VMs in the same order so that they pick up the same IP address each time

The first part was easy, however the second part is difficult when you get beyond one or two people using the same Azure subscription. I needed an easier way to ensure that my VMs would start in a specific order. After a late night with one of my favorite single malts I came up with a fairly simple PowerShell solution.

set-AzureVMs.ps1
As a result of my conversations with Kirk, and some annoyance at the inconsistent nature of shutting down VMs using the Management Portal, I decided to look into how I could shutdown my VMs using PowerShell. There is a nice cmdlet for doing this called stop-AzureVM.

Since I want to do this for a set of VMs I needed to be able to run a for-each loop, so I wrote a start and stop function into the script.

4

I started to use a CSV or text file method for loading the VMs that I wanted to start and stop together when I realized that I didn’t want to have to maintain a series of files on every environment that I create and then distribute that to my team. Not to mention that I have multiple Azure subscriptions that I am using for clients and personal use. The management of that would get cumbersome quickly.

Then I remembered that all of the VMs that I will want to use together are going to be a part of the same Azure Cloud Service (ACS) and that each farm or group of servers that I want to use will have their own unique ACS. There is a cmdlet to get all of the ACS in an Azure Subscription called get-AzureService. I have opted to get the Service Name, Affinity Group, and status of the ACS in my script.

5

The status field is not overly useful, but if something other than “Created” is returned it is worth investigating since that is the expected value.

6

Once you have the correct ACS the script will list the VMs that exist within and ask if you want to start or stop them.

The obvious question at this point is “How does this solve the IP address problem that you set out to solve?”

The answer is that the script will always start and stop the VMs in a specific order. Starting the VMs using this script will ensure that the same IP addresses are obtained every time.

The script was originally designed to solve this problem however I have been using it to ensure that my VMs get shutdown cleanly rather than using the Management Portal which, as I mentioned earlier, is inconsiestent at best.

I hope that you find this as useful as I do. I have been using this script since I wrote it Thanksgiving weekend and I stopped tweaking about a week ago. You can find the script here: http://www.jasonhimmelstein.com/scripts/Azure/set-AzureVMs/set-AzureVMs.ps1

Enjoy!

PowerShell Script: SharePoint Farm Creation

PowerShell Script: SharePoint Farm Creation

For a long time I have been meaning to rewrite the PowerShell script that I have been using to do my SharePoint farm creation and just haven’t gotten around to completing the necessary effort to make it all that I want it to be. I have leveraged the work of others, borrowing a piece here and a snippet there but to honest I haven’t been satisfied.

What I really wanted was a script that I can use in my consulting practice as a normalized practice of how a farm should be deployed as well as a script that I could use in the highly repetitive process of doing ITPro dev work. I wanted something that was flexible enough to use for client installs, but repeatable enough that I could use it in my dozens of farm builds that I do in my spare time for troubleshooting and fun.

Here are the key points of what I did differently with this script:

  1. use temporary variables that can be accepted or overridden at the PowerShell command-line when the script is called
    SNAGHTML37d3721b
  2. validate if the pieces have been implemented correctly & gives information about what piece failed, not just throwing the ugly PowerShell errors that we are used to seeing
    SNAGHTML37d4db9e
  3. validate that you are using PowerShell running as Administrator to ensure that you won’t fail for that silly reason
    SNAGHTML37d64475
  4. pulls the system & domain variables rather than having to set those parameters manually
    SNAGHTML37d7b73f

I am happy to report that I was able to accomplish all of these things in my script and am happy to offer it up for others to use if you see fit. I highly recommend that you consider using the PowerShell profile that I laid out in my previous article “How to: Automatically log your PowerShell session everytime” so that you can, among other things, capture the output of building your farm.

There are very few people who can honestly say that they created their PowerShell scripts completely from scratch, and I am certainly not among them. Credit is due for snippets & reference to Shannon Bray, Gary LaPointe, Brian Lalancette, Todd Klindt, & I’m sure others. Special appreciation to Evan Riser for helping me QA this script. 

One last thing to note about this script… it does just what it says it does. It creates a SharePoint farm.  This is not an all inclusive build your farm & configure every setting script. If you are looking for the all inclusive, über build & configure script please go visit Brian’s codeplex project: AutoSPInstaller. There is no need for anyone to recreate the amazing work that he has done. 

The reason I create this scripts like this is that I prefer to break my scripts down into pieces and keep them highly modular. This is partly because I consult on such a wide variety of projects that it makes my life easier to be able to deploy pieces at a time using different scripts. It also could be that I am a neurotic, lunatic control freak who is a bit over obsessed with developing in PowerShell for fun.  Hopefully it’s more the first thing than the second thing… 🙂

I will continue to publish the scripts that I find useful here in the hopes that it helps someone else along the way. You can find my SharePoint Farm Creation PowerShell script here on my SkyDrive.

Updated PowerShell Profiles Creation Script

Updated PowerShell Profiles Creation Script

 

 

While enjoying Doug Hemminger’s presentation at the SharePoSH meeting tonight I realized that I hadn’t published an update to my How to: Automatically log your PowerShell session every time post, even though I had fixed some issues with the script more than 2 months ago. FYI, I still blame Todd Klindt for prompting me to write this thing in the first place by introducing me to start-transcript…

I updated the version of code in the previous post from v1.8 to v1.14 without posting about it, however the output formatting was poor.

The major changes from v1.8 to v1.15 are:

1.) Proper formatting of screen outputs
2.) Added PowerShell Active Directory modules
3.) Outputting a validated list of snap-ins & modules that are actually loaded instead of just printing on screen that the SharePoint module loaded even when it hadn’t
4.) Validation that the user is running in the context of an Administrator
5.) Removed unnecessary code & added proper commenting inline

You can find the updated code at on SkyDrive here.

How to: Create Active Directory Users using PowerShell

How to: Create Active Directory Users using PowerShell

Not unlike several posts in recent weeks, tonight’s adventures in PowerShelling started with from a conversation at SharePoint Saturday New Hampshire with the Iowan treasure Todd Klindt. The conversation was around the script that he used to create Active Directory users. I had my own bit of jumbled together code for this purpose, but his has some snazzy ifelse-ness to it and the ability to set Managers and add Pictures that made it especially appealing.

At the same time there were things in his script that I felt were a bit lacking and it lead to the whole “I can write that code in 2 hours” game not unlike a name that tune style geek-out.

Rather than reiterating all of the goodness that Todd built into his version of the script I will refer you to his post: http://www.toddklindt.com/PoshMakeUsers to read all of his fun comments.

Instead I will regale you with the updates that I have made:

  1. Specify an OU – I am an old school AD guy at heart and I HATE a mess Users directory where I can’t find anything. I always end up moving my SQL & SharePoint Service accounts to their own OU, as well as my dummy test accounts. This tweak to the script asks you what OU you want the accounts created in and then will create the OU if it doesn’t already exist (given you have those rights). If you hit enter it will default to attempting to place the accounts in an OU called “SharePoint Service Accounts”.
  2. Prompt for the CSV input file – I have multiple files that I use in different dev environments for different purposes: a.) SQL service accounts b.) SharePoint service accounts c.) Dummy user accounts d.) Smart user accounts e.) etc, etc, etc. The script now prompts for which CSV file you want to import the users from. Hitting enter when prompted will look for a file called Users.csv in the local running directory.

    **Updated**

  3. Change the default passwordOn Todd’s Netcast tonight he mentioned this little bit of code, however I hadn’t actually written it yet. Nothing like throwing down the gauntlet there, Mr. Klindt! In response I whipped up version 3.1 of the script which now allows you to change the default password as a variable when run. If you choose nothing it will default to the pass@word1 standard.

Here is a copy of the code:

# Script to create Active Directory accounts
# v3.1 11/26/2012
# Updated by Jason Himmelstein
# http://www.sharepointlonghorn.com
# Based upon the script by Todd Klindt
# http://www.toddklindt.com

# Add the Active Directory bits and not complain if they're already there
Import-Module ActiveDirectory -ErrorAction SilentlyContinue

$OU= Read-Host -Prompt "Enter OU name you want. Press Enter for SharePoint Service Accounts"
If ($OU -eq "") {$OU = 'SharePoint Service Accounts'}
$FQDN = (Get-ADDomain).DistinguishedName

If ([adsi]::Exists("LDAP://OU=$OU, $FQDN") -eq $True){
write-host "The OU already exist" -ForegroundColor DarkGreen -BackgroundColor Gray}
else{dsadd ou "ou=$OU,$FQDN"}

$OU_specified = "ou=$OU,$FQDN"

# specify the file location
$csvfile = 'users.csv'
$userfile = Read-Host -Prompt "
Enter the location of the CSV file containing the users you want to import. Press Enter for $csvfile"
If ($userfile -eq "") {$userfile = $csvfile}

# set default password
# change pass@word1 to whatever you want the account passwords to be
$userpassword = Read-Host -Prompt "Enter default password you wish to set for all of these accounts. Press Enter for pass@word1"
If ($userpassword -eq "") {$userpassword = 'pass@word1'}
$password = (ConvertTo-SecureString $userpassword -AsPlainText -Force)

# Get domain DNS suffix
$dnsroot = '@' + (Get-ADDomain).DistinguishedName

# Import the file with the users. You can change the filename to reflect your file
$users = Import-Csv $userfile

foreach ($user in $users) {
if ($user.manager -eq "") # In case it's a service account or a boss
 {
try {
New-ADUser -SamAccountName $user.SamAccountName -path $OU_specified -Name ($user.FirstName + " " + $user.LastName) `
-DisplayName ($user.FirstName + " " + $user.LastName) -GivenName $user.FirstName -Surname $user.LastName `
-EmailAddress ($user.SamAccountName + $dnsroot) -UserPrincipalName ($user.SamAccountName + $dnsroot) `
-Title $user.title -Enabled $true -ChangePasswordAtLogon $false -PasswordNeverExpires  $true `
-AccountPassword $password -PassThru `
                    }
catch [System.Object]
 {
Write-Output "Could not create user $($user.SamAccountName), $_"
 }
            }
 else
 {
try {
New-ADUser -SamAccountName $user.SamAccountName -path $OU_specified -Name ($user.FirstName + " " + $user.LastName) `
-DisplayName ($user.FirstName + " " + $user.LastName) -GivenName $user.FirstName -Surname $user.LastName `
-EmailAddress ($user.SamAccountName + $dnsroot) -UserPrincipalName ($user.SamAccountName + $dnsroot) `
-Title $user.title -manager $user.manager `
-Enabled $true -ChangePasswordAtLogon $false -PasswordNeverExpires  $true `
-AccountPassword $password -PassThru `
                    }
catch [System.Object]
 {
Write-Output "Could not create user $($user.SamAccountName), $_"
 }
             }
 # Put picture part here.
 $filename = "$($user.SamAccountName).jpg"
 Write-Output $filename

 if (test-path -path $filename)
            {
Write-Output "Found picture for $($user.SamAccountName)"

 $photo = [byte[]](Get-Content $filename -Encoding byte)
Set-ADUser $($user.SamAccountName) -Replace @{thumbnailPhoto=$photo} 
            }
   }

If you are looking for the downloadable PowerShell or text file version, please find them linked below. Happy PowerShelling!

powershell notepad

How to: Automatically log your PowerShell session every time

How to: Automatically log your PowerShell session every time

Preface

At SharePoint Saturday New Hampshire I sat in a packed room and listened as Todd Klindt showed everyone how to install SharePoint 2013 without screwing it up (too badly). The big take away for me was this command that I had not heard about before called start-transcript. The power of start-transcript is that it is able to write everything that you do in a PowerShell session to a log file that you can review later. Todd demo’ed how he throws this every time he opens PowerShell and has found it to be invaluable.

The main reason that I had not heard of start-transcipt before is that I live in PowerShell ISE and rarely (if ever) go into plain ol’ PowerShell, and sadly start-transcript is not supported in PowerShell ISE. DAMN YOU POWERSHELL GODS FOR TEASING ME SO!!!!

The Use Case

The problem that this solves in my view is:

  1. I spend a ton of time tweaking away at some code on a SharePoint server, get it right and then inadvertently close the PowerShell window. It’s just GONE.
  2. Opening and closing PowerShell windows and trying to remember what I manually typed 2 hours ago to fix a problem that got reintroduced after redeploying code.
  3. Needing a way to review who made changes to the serverenvironment and see what they actually did.

The more I thought about it the more the more I liked the ability to log everything that is done in PowerShell on a server, but the issue that I had was that it was something that the person opening PowerShell had to remember to do every time they opened a window.

I started thinking about using PowerShell profiles to implement this for every user. In my experience I have seen profiles used infrequently, but in a couple of the scenarios they have been deployed via AD Group Policy. However if you are working in an environment that you don’t have access to create GPOs or you are working in a development environment and developing GPOs just isn’t your thing what do you do?

The Problem

The task at hand was two-fold:

  1. Auto deploy a PowerShell Profile for SharePoint Admins that would be lightweight, contain the start-transcript function to start automatically, assist in auditing, and be Server Administrator deployable
  2. Figure out if start-transcript like functionality was available for the native PowerShell ISE

The Solution

The solution that I came up with was to leverage the All Users Startup option in Windows to launch a script that would check to see if the folder that holds the PowerShell profile scripts exists. If it exists, the script terminates and all is well. This happens on every interactive login, but takes only a second. If the folder does not exist, the will kick off a creation of the scripts based upon a preset profile definition that includes the targeting & naming of the logs, starting the transcript, and loading the SharePoint module. The profile definition can be completely customized making this a viable approach for admins of other technologies, not just SharePoint.

For PowerShell this is great because it works out perfectly as built. PowerShell ISE on the other hand is still a thorn in our sides. The Scripting Guys, aka Ed Wilson and Craig Liebendorfer, wrote a terrific function that allows you to log the output pane in PowerShell ISE v1 & 2. Sadly this is not working in PowerShell v3 since there is no output pane. Leveraging that we can get part of the functionality in ISE that we get in the command-line version.

Behind the code

The solution that I came up with is in the form of a single PowerShell script that builds the following:

  • 2 folders (at the Root of C:)
    • c:PowerShellLogs will house all of the transcripts
    • c:PowerShellScripts will be the home for the scripts used to build the profiles and will be the default starting location when PowerShell opens. This way you can put all of the scripts you want to call in one place for all users and they can launch them easily.
  • check-profiles.lnk (in the All Users Start Menu Startup folder)
    • This shortcut points to a batch file in the C:PowerShellScripts folder called check-profiles.bat
  • check-profiles.bat (in c:PowerShellScripts)
    • This batch file launches the check-profiles.ps1
  • check-profiles.ps1 (in c:PowerShellScripts)
    • This PowerShell script checks to see if the user has a WindowsPowerShell folder in their My Documents folder. If it finds the folder, the script terminates. If it doesn’t find the folder it launches the create-profiles.ps1 script
  • create-profiles.ps1 (in c:PowerShellScripts)
    • This PowerShell Script creates the profiles for both PowerShell & PowerShell ISE.

Here is what I put in the PowerShell profile:

  • Set the location for PowerShell to start in to C:PowerShellScripts
  • Display a message about needing to Run as Administrator to effect changes
  • Set the path for logging the session to C:PowerShellLogs
  • Set the log name using the user context and date time stamp
  • Start the transcript
  • Display a message about waiting for the SharePoint snap-ins to load
  • Load the SharePoint snap-ins
  • Display a message that loading the SharePoint snap-in is complete and lets you know who you are running PowerShell as

Here is what I put in the PowerShell ISE profile:

  • Set the location for PowerShell to start in to C:PowerShellScripts
  • Display a message about needing to Run as Administrator to effect changes
  • Set the path for logging the session to C:PowerShellLogs
  • Load a function to set the log name using the user context and date time stamp
  • Load the function for Output-ISETranscript (the Scripting Guys code)
  • Display a message about waiting for the SharePoint snap-ins to load
  • Load the SharePoint snap-ins
  • Display a message that loading the SharePoint snap-in is complete and lets you know who you are running PowerShell as

Conclusion

While its may not be the perfect solution for PowerShell ISE that I was looking for when I set out, at the end of the day with this code I now have the ability to automatically log everything done in command line PowerShell.

Thanks to Todd Klindt, Evan Riser, Mark Rackley, and Dan Holme for talking through these use cases, reviewing some of the code, and taking differing view points on this to validate that it is a reasonable approach or not. I love being a part of a community where bouncing ideas and solutions off of peers is so easy and open.

You can find the code here:

powershell notepad

Hopefully this code will be useful to you in your day to day world.

250 USB drives to load? WHERE IS MY POWERSHELL CAPE???

250 USB drives to load? WHERE IS MY POWERSHELL CAPE???

In preparation for SharePoint Saturday New Hampshire I had to load 250 USB drives with sponsor’s digital collateral. The fun last evening was getting all of the little buggers out of their individual boxes and sealed plastic wrappers in order to make loading them a bit faster.

Today I ran out to Best Buy and purchased a pair of Belkin 7-Port USB 2.0 Powered Hubs and then sat down to “borrow” some PowerShell commands from someone on the interwebs. Sadly, I did not find a quick pre-canned script that would let me loop through my USB sticks and load them with the data. Here is what I needed my script to do:

1.) Change the name of the USB Drive to “SPSNH 2012”
2.) Copy the files and folders from the location on my hard drive to the USB Drives
3.) With a single trigger, perform the above functions on all drives inserted in the machine

In order to accomplish this I created a drivelist.txt file. Very simple text file with the list of drive letters that I were assigned to the drives when inserted. One key tip here is to make sure that there are no extraneous carriage returns after the final drive letter (this will cause an error later). The contents of the text file look like this:

1

Next I created a PowerShell script that utilized the WmiObject, WmiInstance & Item command-lets and threw in a foreach loop. The script looked like this:

2

Using this script, 2 computers & the 2 Belkin hubs I was able to load all almost 100meg on to 250 drives in just under 2 hours with distractions. Not too shabby.

I also created a second script for USB drives that are larger than 4GB that will reformat them as NTFS (or whatever format you choose) so that you can load larger files onto them, then rename the drive & copy the files in. Here is what that script looks like:

3

Hopefully this will be useful for others in the future. I would not want to be loading these things up without some form of script to assist. Below you can find a plain text version of each of these scripts that you can download and use yourself.

notepad USB Drive rename & copy script (FAT32)

notepad USB Drive format, rename & copy script (NTFS)

When in doubt, check ALL the permissions…

When in doubt, check ALL the permissions…

Having just completed my last speaking engagement of 2012 it was time to get back into the swing of things and start playing with troubleshooting a bit. 

The dilemma

In a continuing effort to evolve my PowerShell build script for SharePoint I spent a few hours with my team playing with different settings.  One of my team members was driving to get better hands on experience with using PowerShell to configure SharePoint.

We started with the very standard PSConfig script that I have used hundreds of times in the past:
(I left out the variables to save some space)

1

The following error popped its ugly head up in PowerShell’s angriest color when attempting to run this initial farm configuration:

New-SPConfigurationDatabase : Requested registry access is not allowed.

The troubleshooting

Check permissions

Hackles went up immediately when the error was read out loud.  Prior to running the script we had just walked through several Security Best Practice checks, following Microsoft’s guidance in TechNet, partly to see if anything had changed recently (it hadn’t) and partly as a good refresher:

Account permissions and security settings (SharePoint Server 2010)

Plan administrative tasks in a least-privilege environment (SharePoint Foundation 2010)

Plan for administrative and service accounts (SharePoint Foundation 2010)

We went back and doubled checked all of our settings and found that things were configured as prescribed.  The SharePoint install account had local administrator permissions on the SharePoint server and SecurityAdmin and DBCreator rights on the SQL server.

Examine the logs

We visited our Server Event Log and 14 Hive Logs folder but found no evidence that anything was in error.  In fact, no logs entries were created at all…

Check the firewall rules

We validated that for this configuration, in a sandbox without external connections to the world, that the Windows Firewalls were turned off.

Check the connection between servers

Using the trusty Data Sources (ODBC) validation method we were able to make connection from the SharePoint server to the SQL server, and browse the available databases.

Get thyself to Google!

Completely perplexed at this point by an error that doesn’t make any sense due to the fact that the SharePoint install account was a local admin we went to our good friend Google and found, well to be honest a bunch of crap that didn’t help us in any way.  Lots of stuff for people who have lost access to Central Admin due to GPO changes, or had a driver go corrupt, or are trying to write to the registry using C# in ASP.net, & even a forum about people having problem registering their car in Nebraska.

Review of Local Security Policies

One last ditch effort to check the local security policy to see if a new GPO pushed down changes to turned out fruitless, however one of the AD admins mentioned they had seen an issue similar to this once before they changed the User Account Control Settings (UAC). 

The Root Cause

Not even thinking about it my response to the UAC question was “There is no need to do that, you just right-click and launch as Administrator or use my PowerShell script to run as a different user

Upon examination of my team member’s screen it was revealed that: 2

PowerShell ISE have in fact been opened without being run as Administrator.  A costly lesson from a time perspective, but a good learning experience for a newbie at PowerShell for SharePoint.

The most troubling of all however was upon reexamination of the PowerShell error message we needed to only go 2 lines above the big red error message that we were troubleshooting on, to the plain black texted TRUE error: (highlighted here in yellow)

3

Unassuming and unnoticed as we troubleshot the obvious error, the line was thrown by the PSConfig.exe and not a bad PowerShell parameter which explains why PowerShell did not recognize it as an error.

The moral of the story…

Even after following every documented Best Practice out there, we still were able to find a way to cause an error.  While the UI was bad for the error that would have been useful to us, it was at least thrown in our faces.

The easy answer is to always make sure that you open PowerShell or PowerShell ISE as Administrator.  My personal preference is always going to be login in to servers using a non-SharePoint privileged account and then elevate permissions to run in the context of a SharePoint Farm admin or service account as demonstrated in my previous post which sets the run as Administrator for you.

Be sure when you are ready to do any SharePoint Admin work that you see the “Administrator:” in front of your PowerShell ISE path, like this:

4

At the end of a fun troubleshooting session we walked away with a new notch in our troubleshooter tool belt, a fun article to write, and team member who will never forget to fire the RunAs flag ever again.

How to: Run PowerShell ISE as Administrator under alternate credentials

How to: Run PowerShell ISE as Administrator under alternate credentials

Coming from a security focused AD background I prefer to have the Managed Service Accounts OU locked down with a GPO restricting interactive logon to a server. This helps avoid service accounts becoming compromised and being taken advantage of in attacks.

Having an ISE is especially helpful when you are doing SharePoint work on the farm and while I am a big fan of PowerShell, running straight at the command line is often a pain. Rather than installing one of the terrific third party solutions out there for an Integrated Shell Environment I try to only install the PowerShell ISE.

As we know, there are something that you cannot do unless you are running in the context of the Farm Administrator account. There is code out there that will let you elevate your PowerShell script and run in the context of a different user, but I really wanted to be able to open PowerShell ISE as the farm account so that I can run parts of a script at a time, or rerun specific lines.

Here is the code that I compiled that allows me to launch PowerShell ISE as the Farm Admin account:

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0

# Farm account name
$farmAccountname =
“domainservice_account”

# Load the Farm Account Creds
$cred = Get-Credential
$farmAccountname

# Create a new process with UAC elevation S
tart-Process
$PsHomepowershell.exe -Credential $cred -ArgumentList “-Command Start-Process $PSHOMEpowershell_ise.exe -Verb Runas -Wait

Once your PowerShell ISE window is launched you can run the following code to validate that you are running as the user that you are expecting:

[Security.Principal.WindowsIdentity]::GetCurrent().Name

Great you learned some more neato PowerShell, but why do I need to use a PowerShell command for this?

You may be asking why wouldn’t I just do a simple “SHIFT+Right Click” and “Run as different user” rather than resorting to a PowerShell solution. The answer is that doing that does not give you the runAs Administrator privileges that we need to do so many of SharePoint’s PowerShell Functions.

Smarty Pants.

powershell PowerShell launch code

notepad Text launch code

powershell User Context validation code

PowerShell Account Creation Script

PowerShell Account Creation Script

When building repeatable SharePoint farms I need to quickly create new service accounts. Since there is no need for a SharePoint Farm to be built using a Domain Admin account, there is really no need for a SharePoint Consultant to ask for or be granted Domain Admin rights.

I spent a good portion of my career prior to SharePoint as a Domain Admin/AD Architect, and a good portion of that role is knowing that most people who ask for Domain Admin rights don’t actually need them.

If you want to start off on the right foot with the AD team in any company, tell them you do not want or need Domain Admin rights. Immediately you have more credibility with them than most other people.

As a result of this, I have put together an account creation script that I use and turn that over to the Domain Admins so that they can handle the creation for me. I simply list out the accounts that I want and then populate them into the following PowerShell:

$domainName = $env:USERDOMAIN
$LDAP
= “LDAP://CN=Managed Service Accounts,DC=$domainName, DC=%local%
$objCN = [ADSI]$LDAP
$objUser
= $objCN.Create(“user”,“CN=%Friendly Name%)
$objUser.Put(“sAMAccountName”,“%SAMAccountName%)
$objUser.Setinfo()
$objUser.psbase.invokeset(“AccountDisabled”, “False”)
$objUser.SetPassword(“pass@word1”)
$objUser.setinfo()

Using the $env:USERDOMAIN I am able to grab the current logged in domain context rather than having to specify it. Make sure that you change the last DC to the correct domain suffix (.com, .net, .org, etc). You will need to specify the %Friendly Name% & %SAMAccountName% that you are trying to create.

The code above will allow you to create accounts that are active immediately without additional intervention.

There are additional steps that need to be taken to grant rights for the User Profile Sync account and local Administrator rights that need to be granted to the Farm Admin account, but those will get covered in later posts.

Sample scripts: powershell notepad

What is MaximumFileSize limit set to on all of my Web Apps? Now that I know, how do I change it?

What is MaximumFileSize limit set to on all of my Web Apps? Now that I know, how do I change it?

I ran into an issue today where I needed to quickly pull the MaximumFileSize setting for every web application across my farms.  I found lots of blogs that told me how to change the setting, but none that told me how to pull the information from the farm before I change it.

The UI method for this is simple, but cumbersome if you have multiple web apps and multiple farms.  Simply go to Central Administration|Application Management|Manage Web Application and select the Web Application you want to look at.  In the ribbon the General Settings button will light up and when you click on it you will get the menu that includes:

a

That great for single scenarios.  I wanted a PowerShell option that would loop through every one of my web applications and give me a list that I can store, and also will give me a quick way to audit if someone has made an unauthorized change.  Here is what I came up with:

b

The output looks like:

c

In a DevQA want all of my sites to have the same file upload size limit, so I can use the following script to set them all the same:

d

In a Production environment I want to have different upload size limits based upon what the function of the Web App is, so I will use a script that allows me to change the limit on each specific web app:

e

Why all the “add-pssnapin microsoft.sharepoint.powershell –ea 0”?

Easy answer to this is that I am generally the numbskull who forgets to pop open the correct PowerShell console (SharePoint 2010 Management Shell) on a server that I don’t usually log into, or I am using PowerShell ISE and haven’t configured a profile.  The –EA 0 flag allows me to throw the command to load the snap-ins without errors showing up if they are already loaded.  Makes for a cleaner overall experience.