magritton
8/29/2016 - 1:00 PM

This is a collection of scripts for SharePoint 2013 Upgrade. The underscore is a correlation to the upgrade procedure.

This is a collection of scripts for SharePoint 2013 Upgrade. The underscore is a correlation to the upgrade procedure.

#this sets the farm account as a local admin on the app servers for the user profile
Invoke-Command -ComputerName SP2013App2, SP2013App1 {
	Net Localgroup administrators /add PSNS\SPFarm2013
}
#office web apps server setup
Add-WindowsFeature Web-Server,Web-Mgmt-Tools,Web-Mgmt-Console,Web-WebServer,Web-Common-Http,Web-Default-Doc,Web-Static-Content,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Security,Web-Filtering,Web-Windows-Auth,Web-App-Dev,Web-Net-Ext45,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Includes,InkandHandwritingServices,NET-Framework-Features,NET-Framework-Core,NET-HTTP-Activation,NET-Non-HTTP-Activ,NET-WCF-HTTP-Activation45

#then restart
shutdown -r -t 0
#this create the reporting service application
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#set the temp path
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}

#start transcription
Start-Transcript C:\temp\CreateReporintServices.txt

$serviceAppPoolName = "SharePointServiceAppsPool"
$reportingServiceName = "PSNS Reporting"
$reportingServiceDNName = "PSNS_Reporting_DB"
$DBServerName = "SP2013SQL\SP2013"
$reportingServiceProxyName = "PSNS Reporting Proxy"

$appPoolName = get-spserviceapplicationpool $serviceAppPoolName
New-SPRSServiceApplication –Name $reportingServiceName –ApplicationPool $appPoolName –DatabaseName $reportingServiceDNName –DatabaseServer $DBServerName
Get-SPRSServiceApplication –name $reportingServiceName | New-SPRSServiceApplicationProxy $reportingServiceProxyName
#this script add the SSRS Services to SharePoint
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#set the temp path
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}

#start transcription
Start-Transcript C:\temp\SSRSSettings.txt

Install-SPRSService
Install-SPRSServiceProxy

#run this part only on the APPs
#get-spserviceinstance -all |where {$_.TypeName -like "SQL Server Reporting*"} | Start-SPServiceInstance

Stop-Transcript
#this sets the data model for Excel services and then check that it ran successfully
Get-SPExcelServiceApplication | New-SPExcelBIServer -ServerId "SP2013App1\POWERPIVOT" -Description "PSNS POWERPIVOT instance APP 1"
Get-SPExcelServiceApplication | New-SPExcelBIServer -ServerId "SP2013App2\POWERPIVOT" -Description "PSNS POWERPIVOT instance APP 2"
iisreset -noforce
Start-Sleep -Seconds 30

$path = "C:\temp\temp.log"
$pathDir = "C:\temp"
$pathExists = Test-Path $pathDir -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item $pathDir -type directory
}

If (Test-Path $path){
	Remove-Item $path
}

Merge-SPLogFile -path $path -Area "Excel Services Application" ##-Category "Data Model"
If (Test-Path $path){
Get-Content $path
notepad $path
}
else{
    Write-Host "No Entries found!!" -BackgroundColor Green -ForegroundColor Yellow
}
#this add the access 2013 SharePoint App
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}

Start-Transcript C:\temp\AccessAppCreate.txt

$serviceAppName = "PSNS Access"
$service2010AppName = "PSNS Access 2010"
$appPoolName = "SharePointServiceAppsPool"
$sqlServerName = "SP2013SQL\SP2013ACCESS"

#get the app pool
Write-Host "Getting the app pool..." -BackgroundColor Green -ForegroundColor Yellow
$applicationPool = Get-SPServiceApplicationPool -Identity $appPoolName

#Access Services
Write-Host "Creating Access Application $serviceAppName" -BackgroundColor Green -ForegroundColor Yellow
$spAccessServices = New-SPAccessServicesApplication -Name $serviceAppName -ApplicationPool $applicationPool -Default -DatabaseServer $sqlServerName
#Access Services Proxy
Write-Host "Creating Access Application Proxy" -BackgroundColor Green -ForegroundColor Yellow
$spAccessServicesProxy = New-SPAccessServicesApplicationProxy -application $spAccessServices

#Access services 2010
Write-Host "Creating Access 2010 Application $service2010AppName" -BackgroundColor Green -ForegroundColor Yellow
$access2010App = New-SPAccessServiceApplication -Name $service2010AppName -ApplicationPool $applicationPool -Default
#this script add the support for apps
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#set the temp path
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}

#start transcription
Start-Transcript C:\temp\SPAppSettings.txt

$appPoolName = "SharePointServiceAppsPool"
$settingsServiceAppName = "PSNS App Settings"
$settingsServiceDBName = "PSNS_App_Settings"
$AppServiceAppName = "PSNS App Management"
$AppServiceDBName = "PSNS_App_Management"
$appDomainName = "PSNSAPPS.com"
$appName = "app"
$dbServerName = "SP2013SQL\SP2013"
$dbName = "PSNS_Secure_Store"
$secureStoreName = "PSNS Secure Store"
$secureStoreProxyName = "PSNS Secure Store Proxy"

#Subscription Settings service application

##$account = Get-SPManagedAccount "SPPool2013"
Write-Host "Get the application pool $appPoolName" -BackgroundColor Green -ForegroundColor Yellow
$applicationPool = Get-SPServiceApplicationPool -Identity $appPoolName

Write-Host "Creating the subscription service application $settingsServiceAppName" -BackgroundColor Green -ForegroundColor Yellow
$appSubscriptionSvc = New-SPSubscriptionSettingsServiceApplication -ApplicationPool $applicationPool -Name $settingsServiceAppName -DatabaseName $settingsServiceDBName
$proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy -ServiceApplication $appSubscriptionSvc

#App Management service application & proxy
Write-Host "Creating the APP Management service application $AppServiceAppName" -BackgroundColor Green -ForegroundColor Yellow
$appManagementServicApp = New-SPAppManagementServiceApplication -ApplicationPool $applicationPool -Name $AppServiceAppName -DatabaseName $AppServiceDBName
$proxyAppSvc = New-SPAppManagementServiceApplicationProxy -ServiceApplication $appManagementServicApp

Write-Host "Setting the APP domain $appDomainName" -BackgroundColor Green -ForegroundColor Yellow
Set-SPAppDomain $appDomainName
Set-SPAppSiteSubscriptionName -Name $appName -Confirm:$false

#create the secure store service application
Write-Host "Creating secure store application..." -BackgroundColor Green -ForegroundColor Yellow
$secureStoreApp = New-SPSecureStoreServiceApplication -ApplicationPool $applicationPool -AuditingEnabled:$false -DatabaseServer $dbServerName -DatabaseName $dbName -Name $secureStoreName
New-SPSecureStoreServiceApplicationProxy -Name $secureStoreProxyName -ServiceApplication $secureStoreApp


Stop-Transcript
#This checks for the workflow service
Invoke-Command -ComputerName SP2013App2, SP2013App1 {
$service = Get-Service -Name "Workflow Manager Backend"
$service}

#This starts the browser and navigates to the XML
start http://sp2013app1:12291/
start http://sp2013app2:12291/
$sync_db = "PSNS_Profile_Service_Sync"
$ups_service_app_name = "PSNS User Profile"

net stop sptimerv4

$syncdb=Get-SPDatabase | where {$_.Name -eq $sync_db}
$syncdb.Unprovision()
$syncdb.Status='Offline'

$ups = Get-SPServiceApplication  | where {$_.Displayname -eq $ups_service_app_name }
$ups.ResetSynchronizationMachine()
$ups.ResetSynchronizationDatabase()

$syncdb.Provision()

net start sptimerv4
$servers = "SP2013APP1","SP2013APP2"

foreach($server in $servers)
{
	Write-Host "Starting the User Profile Synchronization Service on server $server" -BackgroundColor Blue -ForegroundColor Yellow
	Get-SPServiceInstance -Server $server | where-object {$_.TypeName -eq "User Profile Synchronization Service"} | Start-SPServiceInstance
}
#This adds the user profile service
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#set the temp path
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}

#start transcription
Start-Transcript C:\temp\StartExcelServices.txt

$serviceAppPoolName = "SharePointServiceAppsPool"
$profileServiceAppName = "PSNS User Profile"
$profileServiceAppProxyName = "PSNS User Profile Proxy"
$profileServiceDBName = "PSNS_Profile_Service"
$profileSyncDBName = "PSNS_User_Profile_Service_Sync"
$socialDBName = "PSNS_User_Profile_Service_Social"
$servers = "SP2013APP1","SP2013APP2"

$serviceAppPool = Get-SPServiceApplicationPool $serviceAppPoolName
Write-Host "Creating the User Profile Service $profileServiceAppName" -BackgroundColor Green -ForegroundColor Yellow
$userProfileApp = New-SPProfileServiceApplication -Name $profileServiceAppName -ApplicationPool $serviceAppPool -ProfileDBName $profileServiceDBName -ProfileSyncDBName $profileSyncDBName -SocialDBName $socialDBName
Write-Host "Creating the User Profile Service Proxy $profileServiceAppProxyName" -BackgroundColor Green -ForegroundColor Yellow
New-SPProfileServiceApplicationProxy -Name $profileServiceAppProxyName -ServiceApplication $userProfileApp –DefaultProxyGroup

<#
foreach($server in $servers)
{
	Write-Host "Starting the User Profile Synchronization Service on server $server" -BackgroundColor Blue -ForegroundColor Yellow
	Get-SPServiceInstance -Server $server | where-object {$_.TypeName -eq "User Profile Synchronization Service"} | Start-SPServiceInstance -whatif
}
#>
Write-Host "Done" -BackgroundColor Cyan -ForegroundColor Black
Stop-Transcript
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}
Start-Transcript C:\temp\UpgradeSPSite.txt

$wa = Get-SPWebApplication $webApp.URL
$allSites = $wa | Get-SPSite -Limit all

foreach ($spsite in $allSites) {
    Write-Host "Upgrading sit: $spsite" -BackgroundColor Green -ForegroundColor Yellow
    Upgrade-SPSite $spsite -VersionUpgrade
}

Stop-Transcript
notepad C:\temp\UpgradeSPSite.txt

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}
Start-Transcript C:\temp\TestSPSite.txt

$wa = Get-SPWebApplication $webApp.URL
$allSites = $wa | Get-SPSite -Limit all

foreach ($spsite in $allSites) {
    Test-SPSite -Identity $spsite | Out-File C:\temp\testResults.txt -Append
}



Stop-Transcript
#this mounts the content databases to the main web application
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#set the temp path
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}

#start transcription
Start-Transcript C:\temp\MountContentDB.txt

$contantDatabases = "WSS_Content_2010","WSS_Content_C0_2010","WSS_Content_C1_2010","WSS_Content_C2_2010","WSS_Content_C3_2010","WSS_Content_C4_2010"
$dbServerName = "SP2013SQL\SP2013"
$webAppUrl = "http://sp2010"

foreach($contentDatabase in $contantDatabases)
{
	write-host "Mounting: $contentDatabase" -BackgroundColor Green -ForegroundColor Yellow
	Mount-SPContentDatabase -Name $contentDatabase -DatabaseServer $dbServerName -WebApplication $webAppUrl
}
Write-Host "Done" -BackgroundColor Cyan -ForegroundColor Yellow
Stop-Transcript
#this created the sharepoint web application for upgrading
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#set the temp path
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}

#start transcription
Start-Transcript C:\temp\CreateWebApp.txt

$webAppName = "SP2013"
$applicationPoolName = "SP2013Pool" #a new webb app poll will be created
$managedAccountName = "PSNS\SPPool2013"
$webbAppUrl = "http://sp2010"
$port = 80
$databaseName = "WSS_Content_SP2013"
$databaseServer = "SP2013SQL\SP2013"
##$hostHeader = "homeportnw.psns.navy.mil"

Write-Host "Creating web app: $webAppName" -BackgroundColor Green -ForegroundColor Yellow
#create the web application in classic authentication mode
New-SPWebApplication -Name $webAppName -ApplicationPool $applicationPoolName -ApplicationPoolAccount (Get-SPManagedAccount $managedAccountName) -AuthenticationMethod NTLM -url $webbAppUrl -Port $port -DatabaseName $databaseName -DatabaseServer $$databaseServer #-SecureSocketsLayer -HostHeader $hostHeader
Write-Host "Done" -BackgroundColor Cyan -ForegroundColor Yellow

Stop-Transcript
#this starts the Excel services on the app servers, and creates the Excel, State, Visio, PerformancePoint service applications 
Clear-Host
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#set the temp path
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}

#start transcription
Start-Transcript C:\temp\StartExcelServices.txt

#set variables
$services = "Excel Calculation Services"
$serviceAppPoolName = "SharePointServiceAppsPool"
$excelServiceName = "PSNS Excel"
$stateServiceName = "PSNS State Service"
$stateServiceDBName = "StateServiceDatabase"
$stateServiceProxyName = "PSNS State Proxy"
$visioServiceName = "PSNS Visio"
$visioServiceProxyName = "PSNS Visio Proxy"
$PerformancePointSAName = "PSNS PerformancePoint"
$performancePointProxyName = "PSNS PerformancePoint Proxy"

#app pool variables in case the app pool is not there
$appPoolName = "SharePointServiceAppsPool"
$appPoolAccountName = "PSNS\SPPool2013"
$appPoolAccountPassword = "Casino12%%"

#set the servers
$servers = "SP2013APP1","SP2013APP2"

#start Excel Services on APPs
write-host "Starting Excel Services service instance."
foreach($server in $servers)
{
    Write-Host "Setting Excel Services on: $server" -BackgroundColor Green -ForegroundColor Yellow
    Get-SPServiceInstance -Server $server | where {$_.TypeName -eq $services} | Start-SPServiceInstance

}

if(($myAppPool = Get-SPServiceApplicationPool $serviceAppPoolName -ErrorAction SilentlyContinue))
{
    $serviceAppPool = Get-SPServiceApplicationPool $serviceAppPoolName
}
else
{
    Write-Host "Creating the application pool: $serviceAppPoolName" -ForegroundColor White -BackgroundColor DarkMagenta
    $password = ConvertTo-SecureString $appPoolAccountPassword -AsPlainText -Force
    $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $appPoolAccountName, $password
    $Account = New-SPManagedAccount -Credential $cred

    New-SPServiceApplicationPool -Name $serviceAppPoolName -Account $Account
    $serviceAppPool = Get-SPServiceApplicationPool -Identity $serviceAppPoolName
}

$serviceExcelApp = New-SPExcelServiceApplication –ApplicationPool $serviceAppPool -Name $excelServiceName -Default
<#
Write-Host "Setting State Service Application" -BackgroundColor Green -ForegroundColor Yellow
$stateServiceApp = New-SPStateServiceApplication -Name $stateServiceName
New-SPStateServiceDatabase -Name $stateServiceDBName -ServiceApplication $stateServiceApp 
New-SPStateServiceApplicationProxy -Name $stateServiceProxyName -ServiceApplication $stateServiceApp –DefaultProxyGroup
#>

Write-Host "Setting Visio Service Application" -BackgroundColor Green -ForegroundColor Yellow
$visio = New-SPVisioServiceApplication -Name $visioServiceName -ApplicationPool $serviceAppPool
$visioProxy = New-SPVisioServiceApplicationProxy -Name $visioServiceProxyName -ServiceApplication $visio.Name

Write-Host "Setting Performance Point Service Application" -BackgroundColor Green -ForegroundColor Yellow
$performancePointSA = Get-SPPerformancePointServiceApplication -Identity $PerformancePointSAName
if($performancePointSA -eq $null)
{
    Write-Host "No Service Application found, creating $PerformancePointSAName now" -BackgroundColor Green -ForegroundColor Yellow
    $serviceAppPool = Get-SPServiceApplicationPool $serviceAppPoolName
    $performancePointApp = New-SPPerformancePointServiceApplication -Name $PerformancePointSAName -ApplicationPool $serviceAppPool
    New-SPPerformancePointServiceApplicationProxy -Name $performancePointProxyName -ServiceApplication $performancePointApp –Default
    Write-Host "Completed creating the PerformancePoint Service Application" -BackgroundColor Green -ForegroundColor Yellow
}

Write-Host "Done" -BackgroundColor Cyan -ForegroundColor Yellow
Stop-Transcript
#this upgrades a sharepoint server
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}
Start-Transcript C:\temp\UpgradeStatus.txt
PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures
Stop-Transcript
#this checks to see if any upgrades of the SP Server are needed
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}
Start-Transcript C:\temp\CheckUpgradeStatus.txt
stsadm.exe -o localupgradestatus | Out-File c:\temp\upgradestatus.txt
notepad c:\temp\upgradestatus.txt
Stop-Transcript
--This restores the tables to read-write
DECLARE @name VARCHAR(255) -- database name   

DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0 

BEGIN
	exec('ALTER DATABASE [' + @name + '] SET READ_WRITE')
	FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor   
DEALLOCATE db_cursor
#this script sets all of the databases to read only and then backs them up to the selected path
DECLARE @name VARCHAR(255) -- database name  
DECLARE @path VARCHAR(256) -- path for backup files  
DECLARE @fileName VARCHAR(256) -- filename for backup 
-- specify database backup directory
SET @path = 'I:\SQLBackup\'  

DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0 

BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	--select @name
	exec('ALTER DATABASE [' + @name + '] SET READ_ONLY')
    SET @fileName = @Path + @name + '.BAK'  
       BACKUP DATABASE @name TO DISK = @fileName  
 
       FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor   
DEALLOCATE db_cursor
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Name of the DBs you would like to upgrade
$SecureStoreDBName = "Secure_Store_Service_DB_8304477f381b48b78cb6446763cf862d_2010"
$BusinessDataConnectivityDBName = "Bdc_Service_DB_6358c473529d48338f0dc0b9720d347e_2010"
$ManagedMetadataDBName = "Managed Metadata Service_fbf0620f7648466a9c194b8640794f34_2010"
$SearchServiceDBName = "Search_Service_Application_DB_991ae0779fb84c00aeb3622b14ddbeb8_2010"

#Name of the Service Applications
$SecureStoreName = "PSNS Secure Store"
$BusinessDataConnectivityName = "PSNS Business Data Connectivity"
$ManagedMetadataName = "PSNS Managed Metadata"
$SearchServiceName = "PSNS Search"

#Name of the Service Applications Proxys
$SecureStoreProxyName = "PSNS Secure Store Proxy"
$BusinessDataConnectivityProxyName = "PSNS Business Data Connectivity Proxy"
$ManagedMetadataProxyName = "PSNS Managed Metadata Proxy"
$SearchServiceProxyName = "PSNS Search Proxy"

#name to the Services App Pool
$appPoolName = "SharePointServiceAppsPool"
$appPoolAccountName = "PSNS\DevAppPool"
$appPoolAccountPassword = "Pa`$`$w0rd"

#misc
$PassPhrase = "Pa`$`$w0rd"
$databaseServerName = "SP2013\SP2013"

try
{
#create the application pool
Write-Host "Creating the application pool: $appPoolName" -ForegroundColor White -BackgroundColor DarkMagenta
$password = ConvertTo-SecureString $appPoolAccountPassword -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist $appPoolAccountName, $password
$Account = New-SPManagedAccount -Credential $cred
New-SPServiceApplicationPool -Name $appPoolName -Account $Account
$applicationPool = Get-SPServiceApplicationPool -Identity $appPoolName

#secure store
Write-Host "Creating Secure Store" -ForegroundColor White -BackgroundColor DarkMagenta
$sss = New-SPSecureStoreServiceApplication -Name $SecureStoreName -ApplicationPool $applicationPool -DatabaseName $SecureStoreDBName -AuditingEnabled
$sssp = New-SPSecureStoreServiceApplicationProxy -Name $SecureStoreProxyName -ServiceApplication $sss -DefaultProxyGroup
Update-SPSecureStoreApplicationServerKey -Passphrase $PassPhrase -ServiceApplicationProxy $sssp

#BDC
Write-Host "Creating Business Data Connectivity" -ForegroundColor White -BackgroundColor DarkMagenta
New-SPBusinessDataCatalogServiceApplication -Name $BusinessDataConnectivityName -ApplicationPool $applicationPool -DatabaseName $BusinessDataConnectivityDBName

#Managed Metadata 
Write-Host "Creating Managed Metadata " -ForegroundColor White -BackgroundColor DarkMagenta
$mms = New-SPMetadataServiceApplication -Name $ManagedMetadataName -ApplicationPool $applicationPool -DatabaseName $ManagedMetadataDBName
New-SPMetadataServiceApplicationProxy -Name $ManagedMetadataProxyName -ServiceApplication $mms -DefaultProxyGroup

#Search Service
Write-Host "Creating SearchService " -ForegroundColor White -BackgroundColor DarkMagenta
$searchInst = Get-SPEnterpriseSearchServiceInstance -local
# Gets the Search service instance and sets a variable to use in the next command

Restore-SPEnterpriseSearchServiceApplication -Name $SearchServiceProxyName -applicationpool $applicationPool -databasename $SearchServiceDBName -databaseserver $databaseServerName -AdminSearchServiceInstance $searchInst 
$ssa = Get-SPEnterpriseSearchServiceApplication
New-SPEnterpriseSearchServiceApplicationProxy -Name $SearchProxyname -SearchApplication $ssa 
$ssap = Get-SPEnterpriseSearchServiceApplicationProxy 
Add-SPServiceApplicationProxyGroupMember -member $ssap -Identity $SearchProxyname

Write-Host "Checking Service Applications" -ForegroundColor White -BackgroundColor DarkMagenta
#check the service applications
Get-SPServiceApplication
}
Catch
{
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName
    Write-Host "An Error Occured: $ErrorMessage - $FailedItem" -ForegroundColor Red -BackgroundColor Yellow
}
#this starts the SP service on the specified servers
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#set the temp path
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}
#start transcription
Start-Transcript C:\temp\StartServices.txt
#setvariables
$services = "PowerPoint Conversion Service","Search Query and Site Settings Service","Word Automation Services","Work Management Service","Request Management", "Business Data Connectivity Service","Managed Metadata Web Service","PerformancePoint Service","Secure Store Service","User Profile Service", "Visio Graphics Service","Access Database Service 2010","Access Services"
$status = "Disabled" #"Online"
$servers = "SP2013APP1","SP2013APP2"

$check = Read-Host "Do you want to start the services?(y/n)"
if($check -eq 'y')
{
    foreach($server in $servers)
    {
        Write-Host "Setting server: $server" -BackgroundColor Green -ForegroundColor Yellow
        foreach($service in $services)
        {
            Write-Host "Setting service: $service" -BackgroundColor Cyan -ForegroundColor White
            $spservice = Get-SPServiceInstance -Server $server | ?{$_.TypeName -eq $service}
            if($spservice.Status -eq $status)
            {
                Write-Host "Starting service: $service" -ForegroundColor Black -BackgroundColor DarkYellow
                Start-SPServiceInstance $spservice
            }
        }
    }

    Write-Host "Working on Search Server" -BackgroundColor Green -ForegroundColor Yellow
    $SearchInsts = Get-SPEnterpriseSearchServiceInstance
    foreach($SearchInst in $SearchInsts)
    {
        $serverName = $SearchInst.Server.Address
        if($SearchInst.Status -eq $status -and $servers.Contains($serverName)){
            Write-Host "Starting search on Server: $serverName" -ForegroundColor Black -BackgroundColor DarkYellow
            $SearchSearvice = Start-SPServiceInstance $SearchInst
        }
    }

    foreach($server in $servers)
    {
        $server
        foreach($service in $services)
        {
            Get-SPServiceInstance | ?{$_.Server.Address -eq $server -and $_.TypeName -eq $service} #| ft TypeName, Status
        }
    }
}
Stop-Transcript
$pathExists = Test-Path c:\temp -pathType container
if($pathExists -eq $false){
    Write-Host "Creating temp directory" -BackgroundColor Magenta -ForegroundColor Yellow
    $dir = New-Item c:\temp -type directory
}
Start-Transcript C:\temp\CreateSQLRestore.txt
$dataPath = "C:\Program Files\Microsoft SQL Server\MSSQL11.SP2013\MSSQL\DATA\"
$dataFilesPath = "C:\DBBackup"
$line = "USE [master]`r`n"

Write-Host "Creating SQL File" -BackgroundColor Yellow -ForegroundColor Black
Get-ChildItem $dataFilesPath -Filter *.BAK | 
Foreach-Object {
    Write-Host "Writting $_.FullName" -BackgroundColor Green -ForegroundColor Black
    $name = $_.Name.Replace(".BAK","")

    $line += "RESTORE DATABASE [" + $name + "_2010] FROM  DISK = N'" + $_.FullName
    $line += "' WITH  FILE = 1,  MOVE N'" + $name + "'"
    $line += " TO N'$dataPath"
    $line += $name + "_2010.mdf',  MOVE N'" + $name
    $line += "_log' TO N'$dataPath"
    $line += $name + "_2010_log.LDF',  NOUNLOAD,  STATS = 5`r`n"
    $line | out-file c:\temp\temp.txt
}
Write-Host "Done" -BackgroundColor Yellow -ForegroundColor Black
Stop-Transcript
Function Get-MSHotfix
{
    $outputs = Invoke-Expression "wmic qfe list"
    $outputs = $outputs[1..($outputs.length)]
    
    
    foreach ($output in $Outputs) {
        if ($output) {
            $output = $output -replace 'y U','y-U'
            $output = $output -replace 'NT A','NT-A'
            $output = $output -replace '\s+',' '
            $parts = $output -split ' '
            if ($parts[5] -like "*/*/*") {
                $Dateis = [datetime]::ParseExact($parts[5], '%M/%d/yyyy',[Globalization.cultureinfo]::GetCultureInfo("en-US").DateTimeFormat)
            } elseif (($parts[5] -eq $null) -or ($parts[5] -eq ''))
            {
                $Dateis = [datetime]1700
            }
            
            else {
                $Dateis = get-date([DateTime][Convert]::ToInt64("$parts[5]", 16))-Format '%M/%d/yyyy'
            }
            New-Object -Type PSObject -Property @{
                KBArticle = [string]$parts[0]
                Computername = [string]$parts[1]
                Description = [string]$parts[2]
                FixComments = [string]$parts[6]
                HotFixID = [string]$parts[3]
                InstalledOn = Get-Date($Dateis)-format "dddd d MMMM yyyy"
                InstalledBy = [string]$parts[4]
                InstallDate = [string]$parts[7]
                Name = [string]$parts[8]
                ServicePackInEffect = [string]$parts[9]
                Status = [string]$parts[10]
            }
        }
    }
}
$KBs = "KB3045563","KB3045562","KB3102439","KB3102467","KB3151804","KB3151864"
$rebootFlag = $false
foreach($kb in $KBs)
{
  $test = Get-MSHotfix | ?{$_.HotFixID -eq $kb}
  if($test){
    Write-Host "$kb found!!" -BackgroundColor Green -ForegroundColor Yellow
     $test
     $HotFixNum= $test.HotFixID.Replace("KB","")
     Cmd /c wusa.exe /uninstall /KB:$HotFixNum /quiet /norestart
     Write-Host "$kb uninstalled!!" -BackgroundColor Blue -ForegroundColor White
     $rebootFlag = $true
   }
   else{
    Write-Host "$kb Not Found" -BackgroundColor DarkRed -ForegroundColor White
  }
  if($rebootFlag -eq $true){
    Write-Host "You need to reboot your computer" -BackgroundColor Yellow -ForegroundColor Black
  }
}
$SharePoint2013Path = "E:"
$PrereqPath = "C:\Prereqs"
  
Start-Process "$SharePoint2013Path\PrerequisiteInstaller.exe" –ArgumentList "/SQLNCli:$PrereqPath\sqlncli.msi /IDFX:$PrereqPath\Windows6.1-KB974405-x64.msu /IDFX11:$PrereqPath\MicrosoftIdentityExtensions-64.msi /Sync:$PrereqPath\Synchronization.msi /AppFabric:$PrereqPath\WindowsServerAppFabricSetup_x64.exe /KB2671763:$PrereqPath\AppFabric1.1-RTM-KB2671763-x64-ENU.exe /MSIPCClient:$PrereqPath\setup_msipc_x64.msi /WCFDataServices:$PrereqPath\WcfDataServices.exe /WCFDataServices56:$PrereqPath\WcfDataServices56.exe"
Net Localgroup administrators /add PSNS\SPSetup2013
USE [master]
GO
CREATE LOGIN [PSNS\SPSetup2013] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
GO
ALTER SERVER ROLE [dbcreator] ADD MEMBER [PSNS\SPSetup2013]
GO
ALTER SERVER ROLE [securityadmin] ADD MEMBER [PSNS\SPSetup2013]
GO
#this sets the UAC to off
New-ItemProperty -Path HKLM:Software\Microsoft\Windows\CurrentVersion\policies\system -Name EnableLUA -PropertyType DWord -Value 0 -Force
shutdown -r -t 0
Install-WindowsFeature Net-Framework-Core -source D:\sources\sxs
Install-WindowsFeature AS-NET-Framework -source D:\sources\sxs
Set-NetFirewallProfile -Profile Domain -Enabled false
$farm = Get-SPFarm
$solutions = $farm.Solutions
foreach ($solution in $solutions) {
   $solution.SolutionFile.SaveAs("f:\temp\" + $solution.Name);
}