About Me

SharePoint Architect with over 17 years of IT Experience in various roles as SharePoint Architect, Administrator, Technical Architect, IT Analyst, Application Developer, CRM Consultant, BI Developer, Microsoft Solution Architect in Client/Server, Web and Enterprise CRM Applications in E-Commerce, Financial, Healthcare, Insurance, Telecom, Outsourcing and Technology Services.
MCITP (Pro): Microsoft Certified IT Professional: SharePoint 2010 Administrator.
MCTS: Microsoft Certified Technology Specialist, SharePoint 2010 Configuration.

Sunday, October 30, 2011

Powershell Remoting IIS

Get IIS Settings$q = "Select * from IIsSetting"
$y = [WmiSearcher] $q
$y.Scope.Path = "file://server/root/microsoftiisv2"
$y.Scope.Options.Authentication = 6
# works like objWMIService.Security_.authenticationLevel = WbemAuthenticationLevelPktPrivacy
$a = $y.Get()
foreach ( $b in $a ) {
write-host $b.LogFileDirectory " + " $b.Name
}

Get Application Pools
$objWMI = [WmiSearcher] "Select * From IIsApplicationPool"
$objWMI.Scope.Path = "\\" + $strServerName + "\root\microsoftiisv2"
$objWMI.Scope.Options.Authentication = 6
$pools = $objWMI.Get()
foreach ($pool in $pools)
{
$pool.Name
}

Net User - Commands

Find Full Name of the User Account:
        NET USER vaddiv /DOMAIN | FIND /I " name "
 What permissions does a user have on this directory?      SHOWACLS /U:domain\userid
When did someone last change his password?    NET USER loginname /DOMAIN | FIND /I "Password last set"

Saturday, October 29, 2011

Run Powershell commands on remote computer.

Before you do any of this, you must run the following command in an admin PowerShell command prompt on the machine where you would like to run the remote command:


winrm quickconfig




need to open up the client connection permissions.
You may not want to open it up to anywhere though.
Something like this should also work:



C:\Windows\System32>winrm set winrm/config/client @{TrustedHosts="Server811"}

gacutil, assembly, Check dll


Assembly Location:

get-pssnapin | select assemblyName | export-csv test.csv


check the GAC using something like gacutil /l "System.Management.Automation"




Finding an assembly:

Here's a trick to find it from within PowerShell:
$ref=[psobject].assembly.location



Wednesday, October 26, 2011

PowerShell Script to query/enumerate Scheduled Jobs on a Server

PS Code to query/enumerate Scheduled Jobs on Server:

$servername = "ServerName"
$schedule = new-object -com Schedule.Service
$schedule.connect($servername)
$tasks = $schedule.getfolder("\").gettasks(0)
$tasks |select name, path, lasttaskresult, lastruntime

Tuesday, October 25, 2011

Get Application Pool Properties even Passwords using AppCmd

APPCMD list apppool "ApplicationPoolName" /text:*

If run at the path
C:\Windows\System32\inetsrv>

Will list all Pool Properties with Account/Password

Exit PowerShell Command Line Window/Session

$host.SetShouldExit(5000)

Run PowerShell Script from Task Scheduler

If you schedule the following script with appropriate changes for Log file paths, emails, mailservers, will monitor SharePoint Logging Levels and sends an email if verbose is enabled in environment.

Set your default logging levels to monitor.
RunMonitorSPDiagLogging.bat

powershell.exe -command C:\PowerShell\MonitorSPDiagLogging\MonitorSPDiagLogging.ps1

MonitorSPDiagLogging.ps1

 
Set-ExecutionPolicy RemoteSigned
Set-ExecutionPolicy Unrestricted
#
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
#
$SetTraceSeverity="Unexpected"
$SetEventSeverity="Error"
#
$blnVerbose = "False"
#
$destfile = "C:\PowerShell\MonitorSPDiagLogging\MonitorSPDiagLoggingOut.log"
#
$SPDiagLog = Get-SPLogLevel | Select Area, Name, TraceSeverity, EventSeverity
#Get-SPLogLevel | Select Area, Name, TraceSeverity, DefaultTraceSeverity, EventSeverity, DefaultEventSeverity
foreach ( $obj in $SPDiagLog )
{
#$strLine=""
#$strLine = [string]::join($obj.Name, $obj.Area)
#$strLine = [string]$obj.Name + [string]$obj.Area
#Write-Host $obj.TraceSeverity $obj.DefaultTraceSeverity
#

if(($obj.TraceSeverity -eq "Verbose") -or ($obj.EventSeverity -eq "Verbose") -or ($obj.EventSeverity -eq "Information"))
{
      if($obj.TraceSeverity -ne "VerboseEx")
      {
            #"verboseEx-False So Verbose=TRUE"
            $blnVerbose = "True"
           
      }
}

#
#$strLine5 = $strLine + $blnTrace + $blnEvent;
#$strLine5
}
#
if($blnVerbose -eq "True")
{
      "Processing email... - one of service is in stopped mode.. "
      $emailFrom = "SharePointSupport@unisys.com"
      $emailTo = "User@Domain.com,User2@Domain"
      #$emailTo = "User@Domain.com"
      $subject = "Alert: Verify Diagnostic Logging Levels:" + $env:computername

      $body = @"
      Alert: Verify Diagnostic Logging Levels in $env:computername
      -------------------------------------------------------------

      Found verbose enabled for Trace or Verbose/Information Enabled for Event Logging
      for some of objects in Diagnostic Logging.

      Set logging to default using following command.

      Use (PowerShell)
      Set-SPLogLevel -TraceSeverity Unexpected -EventSeverity Error

      Don't use (Stsadm)
      stsadm -o setlogginglevel -tracelevel Unexpected -windowslogginglevel Error)

      "@
      $smtpServer = "mailrelay.na.uis.yourcorp.com"
      $smtp = new-object Net.Mail.SmtpClient($smtpServer)
      $smtp.Send($emailFrom, $emailTo, $subject, $body)
      #$smtp.Dispose()
      $strTimestamp =  [string](Get-Date -format "yyyy-MM-dd_hh-mm-ss")
      $strTimestamp
      $strTimestamp + " : Email Processed" | Out-File "MonitorSPDiagLogging-ps1-Error.log" -append
      #$host.SetShouldExit(5000)
}

Get EventReceivers info for a given site


UserEventReceiverInfo.ps1

param(
[String]$site = ""
)
$URL = "http://WebApp.com/Sites/" + $site + "/blog"
$URL
$web = Get-SPWeb $URL
$list = $web.Lists["Posts"]
$web.Site.Owner
$list.EnableModeration
$list.EventReceivers | fl Type,Class,SequenceNumber

Update Taxonomy Hidden List



UpdateTaxonomyHiddenList.ps1
$Assem = (
    "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" ,
    "Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
         )
           
$Source = @"

using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System;

namespace TaxonomyUpdater
{
    public static class TaxonomyHiddenList
    {
        public static void Update(string SiteUrl)
        {
            SPSite Site2Update = new SPSite(SiteUrl);
            TaxonomySession.SyncHiddenList(Site2Update);
        }
    }
}
"@
Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp

Migrate Users from Groups and/or set target group permissions.

This Powershell Script serves a special purpose.

If you have two user groups in a Site Collection and if you want to copy users from one user group to other user groups, you can use this Powershell Script.

Also, optionally you can also remove Full Control Permissions on the Target User Group and also set Contributor Permissions on the Target Group.

The code verifies if the user already exists, and attempts to copy the user only if the user does not exists.

Logs verbose to log file at path, C:\Reports
Logs copy actions on each user. Helps you to have you rollback any changes.

usage : ProcessGUIDGroups.ps1 SiteUrlsTest.csv
Input File: SiteUrlsTest.csv
URL,GroupGUID,Group
http://webapp.domain.com/sites/site1, group_source1, group_dest1
http://webapp.domain.com/sites/site2, group_source2, group_dest2


ProcessGUIDGroups.ps1

param (
    [string] $filesiteurls = ""
)
if ($filesiteurls -eq "")
{
                $filesiteurls = Read-Host "Enter filename of siteurls";
}

$blnRemoveFullControl = $true
$blnAddContribute=$true
$blnCopyUser = $true

[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint");

$strTimestamp =  [string](Get-Date -format "yyyy-MM-dd_hh-mm-ss")
$strFilePath = ("C:\Reports\")

$strFilenameErr = ($strFilePath + "Error_" + $strTimestamp + ".log")
$strFilenameRep = ($strFilePath + "Rep_" + $strTimestamp + ".log")

Write-Host -ForegroundColor green "Opening SharePoint site..."

ipcsv $filesiteurls | foreach {

     $siteUrl = $_.URL
     $groupSource = $_.GroupGUID
     $groupDest = $_.Group

                #Write-Host -ForegroundColor white $siteUrl","$groupTarget","$groupDest

                #Open Site
                #$exists = (Get-SPWeb -Identity $siteUrl | Select-Object -Property Exists -ErrorAction SilentlyContinue) -ne $null 
                $exists = (Get-SPWeb $siteUrl -ErrorAction SilentlyContinue) -ne $null 
               
                if ($exists -ne "" -and $exists -ne $null)
                {
                                $site = New-Object Microsoft.SharePoint.SPSite($siteurl)         
               
                                #Open Web
                                $web = $site.OpenWeb()
                                $groupS = $web.SiteGroups | where { $_.Name -eq $groupSource }
                                $usersS = $groupS.Users
                                $groupD = $web.SiteGroups | where { $_.Name -eq $groupDest }
                                $usersD = $groupD.Users
                                #
                                "Users-Source,Users-Dest,Group,Site" | Out-File ($strFilenameRep) -append
                                [string]($usersS.Count) +","+ [string]($usersD.Count) +","+ $groupS.Name +","+ $siteUrl | Out-File ($strFilenameRep) -append
                                "Users at Source:" + $usersS.Count + "  Users at Dest:" + $usersD.Count +","+ $groupS.Name +","+ $siteUrl | Out-File ($strFilenameRep) -append
                                #
                                Write-Host $site.url", ",$groupS.Name", "$groupD.Name
                                ###################################################
                                # Get Roles and Check if "Full Control" exists
                                ###################################################
                                $spPrincipal = [Microsoft.SharePoint.SPPrincipal]$Web.SiteGroups[$groupDest]
                                $roleAss = $Web.RoleAssignments.GetAssignmentByPrincipal($spPrincipal); 
                                $roleBindings = $roleAss.RoleDefinitionBindings;
                                ###################################################
                                $strRoles=""
                                $IsFullControlRoleExists=$false;
                                $IsContributeRoleExists=$false;
                                foreach($role in $roleBindings)
                                {
                                                if($strRoles -eq ""){
                                                                $strRoles = $role.Name
                                                }
                                                else{
                                                                $strRoles + "," + $role.Name;
                                                }
                                               
                                                if("Full Control" -eq $role.Name)
                                                {
                                                                $IsFullControlRoleExists=$true;
                                                }              
                                                if("Contribute" -eq $role.Name)
                                                {
                                                                $IsContributeRoleExists=$true;
                                                }
                                }

                                "Roles= " + $strRoles | Out-File ($strFilenameRep) -append                                                     
                                Write-Host "Roles= ",$strRoles
                                "Is FullControl Role Exists= " + $IsFullControlRoleExists | Out-File ($strFilenameRep) -append                                                          
                                Write-Host "IsFullControlRoleExists= ",$IsFullControlRoleExists
                                "Is Contribute Role Exists= " + $IsContributeRoleExists | Out-File ($strFilenameRep) -append                                                           
                                Write-Host "IsContributeRoleExists= ",$IsContributeRoleExists
                               
                                # REMOVE FULL CONTROL
                                if($blnRemoveFullControl -eq $true)
                                {
                                                #Remove FullControl
                                                if($IsFullControlRoleExists -eq $true)
                                                {                              
                                                                $spPrincipal = [Microsoft.SharePoint.SPPrincipal]$Web.SiteGroups[$groupDest]
                                                                $roleDef = $Web.RoleDefinitions["Full Control"];
                                                                $roleAss = $Web.RoleAssignments.GetAssignmentByPrincipal($spPrincipal);  
                                                                $roleAss.RoleDefinitionBindings.Remove($roleDef);  
                                                                $roleAss.Update();
                                                                #
                                                                "FullControl Removed" | Out-File ($strFilenameRep) -append                                                 
                                                                Write-Host "FullControl Removed"                 
                                                }
                                }
                                else
                                {
                                                "FullControl NOT Removed - Check blnRemoveFullControl in Code" | Out-File ($strFilenameRep) -append   
                                                Write-Host "FullControl NOT Removed"                        
                                }
                                # ADD CONTRIBUTE
                                if($blnAddContribute -eq $true)
                                {
                                                if($IsContributeRoleExists -eq $false)
                                                {
                                                                $spPrincipal = [Microsoft.SharePoint.SPPrincipal]$Web.SiteGroups[$groupDest]
                                                                $roleDef = $Web.RoleDefinitions["Contribute"];
                                                                $roleAss = $Web.RoleAssignments.GetAssignmentByPrincipal($spPrincipal);  
                                                                $roleAss.RoleDefinitionBindings.Add($roleDef);  
                                                                $roleAss.Update();             
                                                                #
                                                                "Contribute Role Added" | Out-File ($strFilenameRep) -append                                                              
                                                                Write-Host "Contribute ROLE NOT Added"                                   
                                                }
                                }
                                else
                                {
                                                "Contribute ROLE NOT Added - Check blnAddContribute in Code" | Out-File ($strFilenameRep) -append     
                                                Write-Host "Contribute ROLE NOT Removed"                              
                                }                              
                                #Write-Host "role Full Control= ", $roleexists, $roleexists
                                ###################################################
                                # ENUMERATE USERS + EXPORT + COPY USERS
                                ###################################################
                                if($blnCopyUser -eq $false)
                                {
                                                "Demo Run- Users are exported and NOT COPIED." | Out-File ($strFilenameRep) -append                                                
                                                "----------------------------------------------------------------" | Out-File ($strFilenameRep) -append
                                                Write-Host "Demo Run- Users are exported and NOT COPIED."
                                }
                                else
                                {
                                                "Users are exported and COPIED." | Out-File ($strFilenameRep) -append                                                             
                                                "----------------------------------------------------------------" | Out-File ($strFilenameRep) -append
                                                Write-Host "Users are exported and COPIED."

                                }
                                #**************************************************        
                                $strFilenameRepGrp = ($strFilePath + "RepGrp_" +$groupDest + "_" + $strTimestamp + ".log")
                                "Users-Source,Users-Dest,Group,Site" | Out-File ($strFilenameRepGrp) -append

                                foreach ($userD in $usersD)
                                {
                                                $site.url+","+$groupDest+",NON-GUID,DESTINATION,"+$userD.LoginName | Out-File ($strFilenameRepGrp) -append
                                }
                                # *************************************************
                                foreach ($userS in $usersS)
                                {
                                  #Set-SPUser -Web $Web -Identity $loginname -Group $Group
                                  #Write-Host $site.url", ",$groupS.Name", "$userS.LoginName
                                  # EXPORT #####
                                  # CHECK IF EXIT AT SOURCE
                                                if($userS.Groups[$groupDest] -eq $null)
                                                {
                                                                try{
                                                               
                                                                $selectedUser = $web.Site.RootWeb.EnsureUser($userS.LoginName);
                                                               
                                                                                if($selectedUser -eq $null)
                                                                                {
                                                                                                "Error (EnsureUser): User Not Found: " + $userS.LoginName + " - " + $siteUrl | Out-File ($strFilenameErr) -append
                                                                                                write-error $("EnsureUser : User Not Found : " + $userS.LoginName);
                                                                                }
                                                                                else
                                                                                {
                                                                                                if($blnCopyUser -eq $true)
                                                                                                {
                                                                                                                $groupD.AddUser($selectedUser);
                                                                                                                $site.url + "," + $groupDest + ",GUID,COPIED," + $userS.LoginName | Out-File ($strFilenameRepGrp) -append                                                                                                
                                                                                                }
                                                                                                else
                                                                                                {
                                                                                                                $site.url + "," + $groupDest + ",GUID,Needs-Copy," + $userS.LoginName | Out-File ($strFilenameRepGrp) -append                                                                                        
                                                                                                }
                                                                                }
                                                                }
                                                                catch{
                                                                                "Exception (AddUser) for User: " + $userS.LoginName + " - " + $siteUrl | Out-File ($strFilenameErr) -append
                                                                                "--------- (AddUser) for GUIDGroup: " + $groupSource + ", DestGroup: " + $groupDest | Out-File ($strFilenameErr) -append        
                                                                                Write-Host -ForegroundColor red "Exception (AddUser) for User: " + $userS.LoginName
                                                                                #write-error $("TRAPPED: " + $_.Exception.GetType().FullName);
                                                                    #write-error $("TRAPPED: " + $_.Exception.Message);                                                           
                                                                                continue;
                                                                }
                                                }
                                                else
                                                {
                                                                $site.url + "," + $groupDest + ",GUID,EXIST-DEST," + $userS.LoginName | Out-File ($strFilenameRepGrp) -append
                                                }              
                                  # COPY #######
                                }

                }#if ($exists -ne "")
                else
                {
                                Write-Host -ForegroundColor red "Error: Site Not Found : " $siteUrl
                                "Error: Site Not Found : " + $siteUrl | Out-File ($strFilenameErr) -append
                }

}#foreach ipcsv $filesiteurls
$web.dispose();
$site.Dispose();

Write-Host -ForegroundColor green "Done.";
Exit
Write-Host -ForegroundColor green "Done. Again";