PowerShell

Removing locally installed printers and replacing with print server

Recently ran into an environment where there was a print server installed and managing all 200 printers however some users (380 computers) still had printers installed locally and were printing directly to the printer through the IP address or host name. This can cause issues with permissions, driver updates, or logging.

Instead of manually touching each computer I created a PowerShell script to verify it was a network printer installed locally and if it existed on the print server to install it for the user, reducing phone calls to the help desk. The script also confirms they are on the corporate network to continue and run and also verifies the printer is online so that it doesn’t remove personal printers that may have been installed for home use.

 
   1: #Only run if on the corporate network to prevent removing personal printers

   2: $Continue = $false

   3:  

   4: $DNSAddresses = Get-DNSClientServerAddress | Select-Object -ExpandProperty ServerAddresses

   5:  

   6: foreach ($DNSAddresses in $DNSAddresses)

   7: {

   8:     #Check DNS server IP to ensure on corporate network

   9:     if($DNSAddresses -eq "192.168.x.x")

  10:     {

  11:         $Continue = $true

  12:         Write-Host "We are on corporate network, continuing.."

  13:         break

  14:     }

  15: }

  16:  

  17: if($Continue -eq $true)

  18: {

  19:     $LocalPrinters = Get-Printer

  20:  

  21:     foreach ($printer in $LocalPrinters)

  22:     {

  23:         if($printer.Type -eq 'Local')

  24:         {

  25:  

  26:             $Port = $printer.PortName.Split("_")

  27:        

  28:             #Checking if a live printer on corporate network

  29:             $ConnectionResults = Test-Connection $Port[0] -Count 1 -Quiet

  30:  

  31:             #Checking if printer is a network printer

  32:             if($ConnectionResults -eq $true)

  33:             {

  34:                 Write-Host "Deleting printer: " $printer.Name

  35:                 Remove-Printer -Name $printer.Name

  36:  

  37:                 #Checking if printer is on print server so we can re-add it

  38:                  $PrintServerPrinterPortName = Get-Printer -ComputerName "printserver.domain.org" -Name $Port[0]

  39:  

  40:                 Write-Host "Printers found on print server with same port name: "$PrintServerPrinterPortName.Count

  41:  

  42:                 if($PrintServerPrinterPortName.Count -gt 0)

  43:                 {

  44:                     $AddPrinter = "\\printserver.domain.org\" + $Port[0]

  45:                    Write-Host "Adding printer from print server: " + $AddPrinter

  46:                   

  47:                    Add-Printer -ConnectionName $AddPrinter

  48:                 }

  49:                 else

  50:                 {

  51:                     Write-Host "Did not find printer on print server with same port name. Checking printer name."

  52:                     $PrintServerPrinterName = Get-Printer -ComputerName "printserver.domain.org" -Name $printer.Name

  53:  

  54:                     Write-Host Write-Host "Printers found on print server with same printer name: "$PrintServerPrinterName.Count

  55:  

  56:                     if($PrintServerPrinterName.Count -gt 0)

  57:                     {

  58:                         $AddPrinter = "\\printserver.domain.org\" +$printer.Name

  59:                         Write-Host "Adding printer from print server: " + $AddPrinter

  60:                         

  61:                         Add-Printer -ConnectionName $AddPrinter

  62:                     }

  63:                     else

  64:                     {

  65:                         Write-Host "Exhausted all options and no printers found."

  66:                     }                

  67:                 }

  68:             }        

  69:         }

  70:     }

  71: }

  72:  

Removing locally installed printers and replacing with print server Read More »

Remove DNS NS Records after demoting domain controller with PowerShell

 

Get-DnsServerZone | ForEach-Object { Get-DnsServerResourceRecord -ZoneName $_.ZoneName -RRType Ns | Where-Object {$_.RecordData.NameServer -like ‘DCName.fqdn.com.‘} | Remove-DnsServerResourceRecord -ZoneName $_.ZoneName -Confirm:$false }

 

Replace the bold test with the fully qualified domain name of the name server. Don’t forget to keep the period at the end of it as well.

Remove DNS NS Records after demoting domain controller with PowerShell Read More »

SharePoint – Export All Documents on Site and Sub-Sites

 

I was eliminating a site on SharePoint that had over 50 sub-sites. I wanted an easy way to get all the documents in each site without having to manually visit each one. Here is an easy PowerShell script I came up with.

   1: #Created by Brandon Claps

   2: #9/25/14

   3: #Exports all documents under a specific site and sub-sites to a local directory

   4:  

   5: #Address of your SharePoint root site

   6: $MainSiteAddress = "https://sharepointsite.contoso.com"

   7:  

   8: #URL of what you you would like to gather. Type a single asterisk if you want everything

   9: $MatchURL = "*URLAddress*"

  10:  

  11: #Destination where you want to download the documents to

  12: $destination = "D:\Exported Documents"

  13:  

  14:  

  15: $Site = Get-SPSite $MainSiteAddress

  16: $WebCollection = $Site.AllWebs

  17:  

  18: foreach($Web in $WebCollection)

  19: {

  20:     foreach($List in $Web.Lists)

  21:     {

  22:         if($List.ParentWebUrl -like $MatchURL)

  23:         {

  24:             if($List.BaseTemplate -eq "DocumentLibrary")

  25:             {                                

  26:                 $webUrl = $MainSiteAddress + $List.ParentWebUrl

  27:                 $listUrl = $webUrl + "/" + $List.RootFolder.Url

  28:                 

  29:                 $web2 = Get-SPWeb -Identity $webUrl

  30:                 $list2 = $web2.GetList($listUrl)

  31:                 

  32:                 function ProcessFolder 

  33:                 {

  34:                     param($folderUrl)

  35:                     $folder = $web2.GetFolder($folderUrl)

  36:                     

  37:                     foreach ($file in $folder.Files) 

  38:                     {

  39:                         $destinationfolder = $destination + "/" + $List.ParentWebUrl.TrimStart("/").Replace("/","-") + "---" + $folder.Url 

  40:                         if (!(Test-Path -path $destinationfolder))

  41:                         {

  42:                             $dest = New-Item $destinationfolder -type directory 

  43:                         }

  44:                         

  45:                         $binary = $file.OpenBinary()

  46:                         $stream = New-Object System.IO.FileStream($destinationfolder + "/" + $file.Name), Create

  47:                         $writer = New-Object System.IO.BinaryWriter($stream)

  48:                         $writer.write($binary)

  49:                         $writer.Close()

  50:                     }

  51:                 }

  52:                 Write-Host "Downloading: " $listUrl 

  53:                 ProcessFolder($list2.RootFolder.Url)

  54:             

  55:                 foreach ($folder in $list2.Folders) {

  56:                     ProcessFolder($folder.Url)

  57:                 }                                

  58:             }        

  59:         }        

  60:     }

  61:  }

SharePoint – Export All Documents on Site and Sub-Sites Read More »

Configuring alarms on all VMware alarm definitions automatically using PowerShell

 

My example contains alarm actions to send an email, but you can configure this for SNMP or any other actions. You can copy and paste this into a “.ps1” file to create a PowerShell scripts.

# This command will remove any alarms actions that are configured currently.

Get-AlarmDefinition | Get-AlarmAction | Remove-AlarmAction -confirm:$false

 

#This command will add an alarm action to send an email. It automatically adds the trigger for status "Yellow" to "Red".

Get-AlarmDefinition | New-AlarmAction -Email -To '[email protected]'

 

#This command adds and additional trigger to send an email when the the status changes from "Yellow" to "Green"

Get-AlarmDefinition | Get-AlarmAction -ActionType "SendEmail" | New-AlarmActionTrigger -StartStatus "Yellow" -EndStatus "Green"

Configuring alarms on all VMware alarm definitions automatically using PowerShell Read More »

SharePoint 2010 Alerts – Daylight Savings Time (DST)

 

Are your alerts behind or ahead by an hour? Microsoft has created a PowerShell script to automatically update your alerts for daylight savings time.

http://technet.microsoft.com/en-us/library/cc508847.aspx

You’ll want to make sure you’re running the script as a SharePoint administration from within the SharePoint Management Shell.

  1. Add the PowerShell script to the scope
    • . ./Invoke-AlertFixup.ps1 (make sure there is a period, space, period)
  2. Type Invoke-AlertFixup –site <URL> –oldurl <URL> (if using this script for DST, make sure the site URL and oldurl are the same.

SharePoint 2010 Alerts – Daylight Savings Time (DST) Read More »

SharePoint 2010: Unable to Display This Web Part. Error while executing web part: System.StackOverflowException: Operation caused a stack overflow.

 

This was caused by the XsltTransformTimeout when using an Xslt list view. This is corrected by installing the February 2012 Cumulative Update and by making the following change via PowerShell.

Check Current Setting

$farm = Get-SPFarm $farm.XsltTransformTimeOut

The default setting is 1 second. The PowerShell code below changes it to 5 seconds which should be sufficient.

Change Setting to 5 Seconds

$farm = Get-SPFarm $farm.XsltTransformTimeOut = 5 $farm.Update()

SharePoint 2010: Unable to Display This Web Part. Error while executing web part: System.StackOverflowException: Operation caused a stack overflow. Read More »

Schedule Update-SPProfilePhotoStore

 

Create a PowerShell script with the following. Make sure your MySite host location is correct.

Add-PSSnapin Microsoft.SharePoint.PowerShell Update-SPProfilePhotoStore -CreateThumbnailsForImportedPhotos 1 -MySiteHostLocation http://mysitehostlocation/MySite/

  1. Save the file as a .ps1 file on your SharePoint 2010 server – C:\Scripts\UpdateSPPhotos.ps1
  2. Create a daily scheduled task on the SharePoint 2010 server that runs at the SharePoint Farm Administrator account.
  3. Configure the action as follows
    • Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    • Arguments: -NonInteractive -NoProfile -File “C:\Scripts\UpdateSPPhotos.ps1”

 

Schedule Update-SPProfilePhotoStore Read More »

Check Windows Service Status with PowerShell

I needed a way to watch a service and if it was stopped to start it. I created this PowerShell script to check it, start it and create a log, using it in a scheduled task.

Make sure the service name is the name of the actual service and not the display name for the service.

$logFile = "C:\test.csv"

$serviceName = "ServiceName";

$serviceStatus = (get-service "$serviceName").Status;

$date = Get-Date

$dateShort = $date.ToShortDateString()

$timeShort = $date.ToShortTimeString()

$i = 1

 

if ($serviceStatus -eq "Running") 

    {

        Add-Content $logFile "$dateShort, $timeShort, $serviceName is $serviceStatus"

    }

elseif ($serviceStatus -eq "Stopped") 

    {

 

            Add-Content $logFile "$dateShort, $timeShort, $serviceName is $serviceStatus, Starting"

            Start-Service $serviceName

        $serviceStatus = (get-service "$serviceName").Status;

        Add-Content $logFile "$dateShort, $timeShort, $serviceName is $serviceStatus"

            

    }

else 

    {

            Add-Content $logFile "$dateShort, $timeShort, $serviceName is $serviceStatus, Unable to Start"

    }

Check Windows Service Status with PowerShell Read More »