Tag Archives: PowerShell

View disabled Health Check rules – PowerShell one liner

Scripting this was harder than I thought it should be, so I wanted to share this crazy long PowerShell one liner.  If anybody knows of a shorter way, please leave a comment or Tweet me.   First, we get the web applications including a special switch to get Central Admin (which is normally skipped for safety).   Then we get the site collections, but since help collection has one we need to filter those out.  Then we grab the Health Analyzer Rules Definitions list.  Finally, we can filter for disabled items and display as a table.

When working on a new farm that someone else installed.  Or heck, even one I installed but just can’t remember how.  This is a good way to confirm your assumptions about any red or yellow Health warnings you see (or don’t see because they’re suppressed)

 

(Get-SPWebApplication -IncludeCentralAdministration |? {$_.IsAdministrationWebApplication -eq $true} |
Get-SPSite |? {$_.Url -notlike '*help'}).Rootweb.Lists["Health Analyzer Rule Definitions"].Items |?
{$_["HealthRuleCheckEnabled"] -eq $false} | select Title,ID | ft -AutoSize

 

I would also recommend creating a new filtered view in the Central Admin GUI for an easy way to quickly view these going forward.  There are legitimate times when a rule should be disabled, that’s why we have the checkbox.  However, it pays to know what the current settings are and not forget those hidden items.

Once all of the health rules are the way you like, run a quick SPTimerJob refresh to see the outcomes of those rules.  Smile

 

Get-SPTimerJob |? {$_.name -like '*-health-*'} | Start-SPTimerJob

 

image

image

Say Happy Birthday with Code!

Most people just say “Happy Birthday” to each other over social networks like Facebook and Twitter with the same 14 predictable letters.   Why not say it with code?   If you’re a developer you already understand.   Smile   Before you ask … Yes, I really did write and run the QBasic 4.5 version in 16-bit mode running www.DosBox.com on Windows 7 x64.   Oh, and no it’s not my birthday.

 

With PowerShell

1..4 | % {if ($_ -ne 3) {Write-Host "Happy Birthday to You!"} else {"Happy Birthday Dear Jeff"}}

With C# Console Application

for (int i = 0; i <= 3; i++) { Console.WriteLine(((i == 2) ? "Happy Birthday dear Jeff" : "Happy Birthday to You!")); }

With JavaScript

With Command Prompt

@ECHO OFF
FOR %%A IN (1 1 2 1)
DO (
IF %%A == 1 ECHO "Happy Birthday to You!"
IF %%A == 2 ECHO "Happy Birthday dear Jeff"
) 
:EOF

With QBasic 4.5  (oh yes I did!)

CLS
FOR x = 1 TO 4
        IF x = 3 THEN
                PRINT "Happy Birthday dear Jeff!"
        ELSE
                PRINT "Happy Birthday to You!"
        END IF
NEXT x
FOR x = 37 TO 1000
        SOUND x, 1
NEXT x

 

image

image

image

image

EmptyList.ps1 – delete all SharePoint list items with PowerShell

Recently I needed to empty an InfoPath Form Library by deleting all of the items and skipping Recycle Bin.  Datasheet view is great for small lists (a few hundred rows) but it doesn’t perform as well on large lists.  Also, skipping the Recycle Bin is a unique requirement best handled with server side code.  See the below PowerShell script for how to easily “empty” any SharePoint list or library.  This works with both SharePoint 2010 and SharePoint 2007 (MOSS 2007).  NOTE – Use this script carefully, it is really good at deleting.  Smile

# SharePoint On-Premise
Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
$web = Get-SPWeb "http://sitename/"
$list = $web.Lists["Shared Documents"]
$caml=""
#optional filter
$query=new-object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.Query=$caml
$items=$list.GetItems($query)
Write-Host $items.Count
$items | % { $list.GetItemById($_.Id).Delete() }
$web.Dispose()
$site.Dispose()

# SharePoint Online (SPO)
$webUrl = "https://tenant.sharepoint.com/sites/team"
$listTitle = "Shared Documents"
Connect-PnPOnline –Url $webUrl -UseWebLogin
$l = Get-PnPList $listTitle
$items = Get-PnPListItem -List $listTitle -PageSize 500
$batch = New-PnPBatch
foreach ($item in $items) {
$item.ID
Remove-PnPListItem -List $l -Identity $item.Id -Batch $batch
}
Invoke-PnPBatch -Batch $batch

Add-SPSolution: Failed to extract the cab file in the solution (FIXED)

Today I saw this error message and was able to fix by renaming the original source files in Visual Studio 2010 to remove special characters.   After checking on Google it appears that symbols such as ~!@#$%^&* may cause issues.   Lesson learned: keep file names simple so SharePoint is happy.  Smile

Add-SPSolution: Failed to extract the cab file in the solution.

8-3-2011 8-44-21 AM

References

“Open-EC2” PowerShell cmdlet (RDP + PS)

To save time I wrote a quick PowerShell function to open RDP and a remote PowerShell console for Amazon EC2 machine instances. Example screenshots are below.    Enjoy!  Hot

 

Function Open-EC2($server, $user, $pass)
{
  Write-Host "- saving RDP credential" -ForegroundColor Blue
  cmdkey /generic:TERMSRV/$server /user:$user /pass:$pass
  Write-Host "- opening RDP" -ForegroundColor Blue
  mstsc /v:$server 
  
  $secure = ConvertTo-SecureString $pass -asplaintext -force
  $cred = New-Object System.Management.Automation.PSCredential $user,$secure
  Set-Variable -Name c -Value $cred -Scope global
  Write-Host "- opening PSSession" -ForegroundColor Blue
  New-PSSession -computername $server -credential $c -Authentication Negotiate
}

 

image

image

image

AutoSPInstaller + PowerShell Remoting

Today while working on the Amazon EC2 cloud I wondered if maybe it was possible to run @brianlala’s AutoSPInstaller script entirely from a remote PowerShell session.   Why?   RDP is fading out.  PowerShell and command line automation will be required skills in the future for IT Pros to manage on a large scale.   I’d like to know how to do everything with PowerShell.   I admit RDP-ing over first is generally available and easy.   But what if you need to run 10 installs?  20?   At some point RDP stops scaling up.

New to PowerShell Remoting?  It’s just opening the console to a remote machine.  This allows you to manage it without any RDP graphical interface and also manage multiple servers at once by sending commands and receiving output in parallel.    Read Microsoft’s description and how to get started here.

So here goes nothing …

  • Launch EC2 server  (W08R2)
  • Download ISOs  (SQL08R2 + SP2010)
  • DCPROMO  (new domain)
  • Create users
  • Install SQL
  • Install SharePoint
    • Extract ISO to folder
    • Extract updates
    • Download AutoSPInstaller
    • Populate XML config

Sounds easy enough, right?  Smile    Below are the screenshots.  Leave a comment or hit me on twitter (@spjeff) with any questions.

UPDATE: I could not see console output at first.  I tried reboot and run PS1 directly instead of BAT.   That helped with visible console output.

UPDATE:  I hit a snag on WIF prerequisite failing.  Not clear why since transcript wasn’t available.

So I bailed and just installed the normal way with an interactive RDP session.  There are limitation with PowerShell remoting (i.e. transcript) that we really need here.  Also, troubleshooting is made too cumbersome.   For now the safest way is the simplest:   interactive RDP to install, then use PowerShell remoting long term for management tasks.  Hot

 

 

image

image

image

image

image

image

image

image

image

 

image

image

 

image

 

image

 

image

 

image

SharePoint 2010 Management Shell – “Run As Admin” always

Today while watching Todd Klindt’s webcast with Idera, a cool trick was shared to avoid having to always right click and run as administrator.   You simply need to right click the icon you have, click the “Advanced” button, and check the “Run as administrator” box.    This will keep the setting permanently to make it easier to use.   

Since we’ll probably be in Powershell every single day it’s a good trick to know about.  Smile

 

image

image 

image

Toggle Developer Dashboard

Here are the commands to change the global developer dashboard setting in SharePoint 2010 and 2013.

OnDemand Mode:

$sp2010 = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$sp2010.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::OnDemand;
$sp2010.RequiredPermissions = 'ManageWeb';  #EmptyMask = all users.  ManageWeb = full control or higher.
$sp2010.TraceEnabled = $true;
$sp2010.Update();

On Mode:

$sp2010 = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$sp2010.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::On;
$sp2010.RequiredPermissions = 'ManageWeb';  #EmptyMask = all users.  ManageWeb = full control or higher.
$sp2010.TraceEnabled = $true;
$sp2010.Update();

Off Mode:

$sp2010 = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$sp2010.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::Off;
$sp2010.Update();

STSADM command line:

stsadm -o setproperty -pn developer-dashboard -pv ondemand 
stsadm -o setproperty -pn developer-dashboard -pv on 
stsadm -o setproperty -pn developer-dashboard -pv off

 

image

Making a cozy PowerShell home

During the Chicago SharePoint 2010 road show (#SharePointRS) Darrin Bishop (@bishopd) showed us a cool admin trick with the below command:

Add-PPSnapin Microsoft.SharePoint.PowerShell

NAME
    Add-PSSnapin

SYNOPSIS
    Adds one or more Windows PowerShell snap-ins to the current session.

SYNTAX
    Add-PSSnapin [-Name] <string[]> [-PassThru] [<CommonParameters>]

Every product shipping with Microsoft now seem sot have it’s own start menu icon and matching PowerShell console.   I’m a simple guy and prefer fewer icons.   So I changed my default profile.ps1 file (C:Documents and Settings%username%My DocumentsWindowsPowerShellprofile.ps1) to have all of the cmdlets loaded in one place.

It was a nice time saver for me, give it a try on your machine!  Hot

 

image

PowerShell Out-Grid.ps1

NOTE – PowerShell 2.0 now includes the “Out-GridView” cmdlet which removes the need for this custom .PS1 script built for PowerShell 1.0

The current release of PowerShell V1.0 does not ship with any GUI tools.    V2.0 CTP3 comes with a scripting IDE and the Out-GridView cmdlet to help with adoption and ease of use.I personally find the Out-Grid.ps1 script very handy and copy to servers whenever I want to do heavy PowerShell work.   Check it out below.

If you see an error stating that “the execution of scripts is disabled on this system” then you’ll want to run “set-executionpolicy unrestricted”

image

image

image

Return to Top ▲Return to Top ▲