Posts Tagged ‘PowerShell’

A client needed a way to remove old domain users from their SharePoint 2010 farm. There was a company merger and they did not want the old domain users showing in the sites.

Enter the root site collection and the search parameter ex: domain and done.

** you might notice a table being created… I left this in here, but its not really used. The client had some additional requirements, that I have not included in this script.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
## Reference to SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
 
##Ask for WebApp Root url to enumerate or scope scan
Write-Host "Please enter root url of WebApplication, ex: http://contoso"
$siteurl = Read-Host "Value "
Write-Host "Please enter the search parameter, ex: contoso "
$searchP = Read-Host "Value "
 
##Create Table - ScanTable
$ScanTable = New-Object system.Data.DataTable "ScanTable"
$col1 = New-Object system.Data.DataColumn ("LoginName", [string])
$col2 = New-Object system.Data.DataColumn ("URL", [string])
$ScanTable.columns.add($col1)
$ScanTable.columns.add($col2)
 
##Returning info for use in remainder of script
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($siteurl)
##Start looping through the sites collections
foreach ($site in $webapp.Sites)
{
    $spSite = new-object Microsoft.SharePoint.SPSite($site.url)
	$spWeb = $spSite.OpenWeb()
 
	##Save file path, guid, and title of each closed webpart
	foreach ($_.LoginName in $spSite.RootWeb.SiteUsers | select LoginName)
	{
	if ($_.LoginName -like "*$searchP*")
	{
	$output = $ScanTable.Rows.Add($_.LoginName, $site.url)
	$spWeb.SiteUsers.Remove($_.LoginName)
	}
	}
 
	##Clean Up
    $spSite.Dispose()
    $spWeb.Dispose()
}
 
##Write txt file
Write-Output $ScanTable | select URL | Sort-Object URL -Unique | Out-File C:users.txt -Append

By default the SharePoint Trace service runs as local system.This script will fix that. 

1. Create a SharePoint 2010 Trace Account. Ex: SPTrace

2. Edit lines 2 and 3 of the PowerShell script.

3. Run script on each server in farm. (not FAST or SQL servers) a. PS C:UsersspinstallDesktop> .TraceAccountFix.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Trace Account Details
$TraceAccount = "DomainSPTrace"
$TraceAcctPWD = "Enter The password here"
$SecTraceAcctPWD = (ConvertTo-SecureString $TraceAcctPWD -AsPlainText -force)
 
# Formatting
$TraceAccountDomain,$TraceAccountUser = $TraceAccount -Split "\"
 
# Get the tracing service.
$farm = Get-SPFarm
$tracingService = $farm.Services | where {$_.Name -eq "SPTraceV4"}
 
$Cred_TraceAcct = New-Object System.Management.Automation.PsCredential $TraceAccount,$SecTraceAcctPWD
 
## Add Managed Account for Trace Account
$ManagedAccountTrace = Get-SPManagedAccount | Where-Object {$_.UserName -eq $TraceAccount}
If ($ManagedAccountTrace -eq $NULL) 
{ 
	Write-Host -ForegroundColor White "- Registering managed account" $TraceAccount
	New-SPManagedAccount -Credential $Cred_TraceAcct | Out-Null 
}
Else {Write-Host -ForegroundColor White "- Managed account $TraceAccount already exists, continuing."}
 
 
# Get the managed account.
$managedAccount = Get-SPManagedAccount "$TraceAccount"
If ($tracingService.ProcessIdentity.ManagedAccount -notlike "*$managedAccount*"){
 
# Set the tracing service to run under the managed account.
$tracingService.ProcessIdentity.CurrentIdentityType = "SpecificUser"
$tracingService.ProcessIdentity.ManagedAccount = $managedAccount
$tracingService.ProcessIdentity.Update()
 
# This actually changes the "Run As" account of the Windows service.
$tracingService.ProcessIdentity.Deploy()
}
 
Try{
([ADSI]"WinNT://$env:COMPUTERNAME/Performance Log Users,group").Add("WinNT://$TraceAccountDomain/$TraceAccountUser")
}
catch {Write-Host -ForegroundColor White " - $TraceAccount is already an in the Performance Log Users group, continuing."}
 
Write-Host "All Done"

If you ever have a need to monitor a website for uptime, one approach is to buy an application that can monitor websites. Ex http://www.ipsentry.com/ or http://www.eventsentry.com/ (relatively cheap software that I have used in the past). The other option is to use PowerShell. This script is meant to be run on a monitoring server. Once its running it will check all the URLs you set in the configuration section of the PowerShell script. If an error in encountered it will send an email. The PowerShell has comments in all the areas you would want to change. The base script comes from http://blogs.technet.com/b/otto/archive/2007/08/23/quick-and-dirty-web-site-monitoring-with-powershell.aspx , I made a few changes…  Added the forever loop, force sending emails, added the ability to send credentials, set interval, added additional comments. Thanks and let me know if you have any questions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
function siteupdown{
## Display Help
if (($Args[0] -eq "-?") -or ($Args[0] -eq "-help")) {
   ""
   "Usage: SysinternalsSiteTest.ps1 -alert
<address> -log"
   "       -alert
<address>      Send e-mail alerts"
   "       -log                  Log results"
   ""
   "Example: SysinternalsSiteTest.ps1 -alert somebody@nospam.com -log"
   ""
   exit
}
 
## Create the variables
$global:GArgs = $Args
 
$urlsToTest = @{}
$urlsToTest["SP2010"] = "http://sp2010/Pages/default.aspx"
## Add more URLs for monidoting **Note URL cannot be rediriecting urls.
#$urlsToTest["TechNet Redirect"] = "http://www.microsoft.com/sysinternals"
#$urlsToTest["Sysinternals Home"] = "http://www.microsoft.com/technet/sysinternals/default.mspx"
#$urlsToTest["Sysinternals Forum"] = "http://forum.sysinternals.com"
#$urlsToTest["Sysinternals Blog"] = "http://blogs.technet.com/sysinternals"
#$urlsToTest["Sysinternals Downloads"] = "http://download.sysinternals.com/Files/NtfsInfo.zip"
 
$successCriteria = @{}
$successCriteria["SP2010"] = "*press releases*"
## Add more success criteria here.
#$successCriteria["TechNet Redirect"] = "*Mark Russinovich*"
#$successCriteria["Sysinternals Home"] = "*Mark Russinovich*"
#$successCriteria["Sysinternals Forum"] = "*Sysinternals Utilities*"
#$successCriteria["Sysinternals Blog"] = "*Sysinternals Site Discussion*"
#$successCriteria["Sysinternals Downloads"] = "*ntfsinfo.exe*"
 
## Set Username Password and domain here
$Username = 'be'
$Password = 'password!!!1'
$Domain = 'gen'
 
## sets up the call
$webClient = new-object System.Net.WebClient
$webClient.credentials = New-Object System.Net.NetworkCredential($Username, $Password, $Domain)
 
foreach ($key in $urlsToTest.Keys) {
   $alert = $false
   $output = ""
 
   $startTime = get-date
   $output = $webClient.DownloadString($urlsToTest[$key])
   $endTime = get-date
 
   if ($output -like $successCriteria[$key]) {
      $key + "`t`tSuccess`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds"
 
      if ($GArgs -eq "-log") {
         $key + "`t`tSuccess`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> WebSiteTest.log
      }
   } else {
      $key + "`t`tFail`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds"
	  $alert = $true
      if ($GArgs -eq "-log") {
         $key + "`t`tFail`t`t" + $startTime.DateTime + "`t`t" + ($endTime - $startTime).TotalSeconds + " seconds" >> WebSiteTest.log
		 $alert = $true
      }
 
      if ($alert -eq $true) {
         Write-Host "Sending Email"
		 ## Set email settings Below. $emailFrom, $EmailTo, $smtpServer
		 $emailFrom = "email@nospam.com"
         $emailTo = "email@nospam.com"
         $subject = "URL Test Failure - " + $startTime
         $body = "URL Test Failure: " + $key + " (" + $urlsToTest[$key] + ") at " + $startTime
         $smtpServer = "smtp.nospam.com"
         $smtp = new-object Net.Mail.SmtpClient($smtpServer)
         $smtp.Send($emailFrom,$emailTo,$subject,$body)
      }
   }
}
}
## Makes the script run forever.
$i=1
for ($i -le 5; $i++)
{
## Change the number, to change check site interval. 1 = 1 seconds, 30 = 30 seconds, etc..
sleep 30;
siteupdown}
</address></address>
This PowerShell Script will flush the cache for all web applications.
1
2
3
4
5
6
7
8
9
10
11
12
13
Write-Host -ForegroundColor White " - Enabling SP PowerShell cmdlets..."
If ((Get-PsSnapin |?{$_.Name -eq "Microsoft.SharePoint.PowerShell"})-eq $null)
{
$PSSnapin = Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
}
$webAppall = Get-SPWebApplication
foreach ($_.URL in $webAppall) {
$webApp = Get-SPWebApplication $_.URL
[Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($webApp)
Write-Host "Flushed the BLOB cache for:" $webApp
}
Write-Host -ForegroundColor White " - Enabling SP PowerShell cmdlets..."If ((Get-PsSnapin |?{$_.Name -eq "Microsoft.SharePoint.PowerShell"})-eq $null){   $PSSnapin = Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null}
$webAppall = Get-SPWebApplicationforeach ($_.URL in $webAppall) {$webApp = Get-SPWebApplication $_.URL[Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($webApp)Write-Host "Flushed the BLOB cache for:" $webApp}

If you are trying to run this command in powershell : New-SPConfigurationDatabase  

You might encounter an error similar to the below… If you’re like me, you install all the necessary software for your farm first, then run the products and technology wizard / configure the farm. If you use the GUI, I have never encountered errors, however via PowerShell i did receive the errors below. As soon as i uninstalled the “Office Web Apps” the error went away. Thanks! Let me know if you have any questions. 

New-SPConfigurationDatabase : The pipeline has been stopped. 

At C:Usersadministrator.GENDesktopAutoSPInstallerSP2010AutoSPInstallerAutoSPInstaller.ps1:576 char:31 

+             New-SPConfigurationDatabase <<<<  –DatabaseName “$ConfigDB” –DatabaseServer “$DBServer” –AdministrationContentDatabaseName “$CentralAdminContentDB” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm 

    + CategoryInfo          : InvalidData: (Microsoft.Share…urationDatabase:SPCmdletNewSPConfigurationDatabase) [New-SPConfigurationDatabase], PipelineStoppedException 

    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSPConfigurationDatabase 

Microsoft.SharePoint.SPException: This SharePoint farm currently has pending upgrades.  The cmdlet New-SPConfigurationDatabase cannot be executed until the upgrade is completed. 

   at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord) 

This SharePoint farm currently has pending upgrades.  The cmdlet New-SPConfigurationDatabase cannot be executed until the upgrade is completed. 

At C:Usersadministrator.GENDesktopAutoSPInstallerSP2010AutoSPInstallerAutoSPInstaller.ps1:576 char:31 

+                                             New-SPConfigurationDatabase <<<<  –DatabaseName “$ConfigDB” –DatabaseServer “$DBServer” –AdministrationContentDatabaseName “$CentralAdminContentDB” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm 

    + CategoryInfo          : InvalidOperation: (:) [New-SPConfigurationDatabase], SPException 

    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSPConfigurationDatabase 

Thank sean.

1
2
$notespw = Read-Host "Enter the password for the Notes ID file" -AsSecureString
$notespw | ConvertFrom-SecureString | Set-Content $pwfile -force

To retrieve the password and create the PSCredential object:

1
2
$notespw = get-content $pwfile | ConvertTo-SecureString
$notesid = new-object -typename system.management.automation.pscredential -argumentlist "-default-",$notespw

Example of use:

1
Get-DominoMailbox mary@contoso.com -SourceCredential $notesid

This is an example of a very simple multi thread script. All it does is output 2 user names per function.
But you can only imagine the power.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#Create a function, or in this example create/split up a large job into multiple functions.
 
#Step 1 : Create threading.ps1
#Step 2 : Create function and add it to threading.ps1
 
#(Sample Function)
 
function one{
	$users1 = "CORP1Bollasr1", "CORP2aardeje1"
		foreach ($u in $users1){
			Write-Output "$u"
		}
}
one | out-File C:lnloneresults.txt
 
 
#Step 3 : Wrap the function inside a function with (Write-Output ' ')  around each line. 
#(Sample Wrapped Function)
 
function createone{
Write-Output 'function one{'
Write-Output '	$users1 = "CORP1Bollasr1", "CORP2aardeje1"'
Write-Output '		foreach ($u in $users1){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'one | out-File C:lnloneresults.txt'
}
 
 
#Now I will show an example of 5 threads. This file is called threading.ps1
 
##Create Multi Thread Script
function createone{
Write-Output 'function one{'
Write-Output '	$users1 = "CORP1Bollasr1", "CORP2aardeje1"'
Write-Output '		foreach ($u in $users1){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'one | out-File C:lnloneresults.txt'
}
 
 
function createtwo{
Write-Output 'function two{'
Write-Output '	$users2 = "CORP1dudlesu1", "CORP2duerrma1"'
Write-Output '		foreach ($u in $users2){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'two | out-File C:lnltworesults.txt'
}
 
 
function createthree{
Write-Output 'function three{'
Write-Output '	$users3 = "CORP1khattpa2", "CORP1khattsa1"'
Write-Output '		foreach ($u in $users3){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'three | out-File C:lnlthreeresults.txt'
}
 
 
function createfour{
Write-Output 'function four{'
Write-Output '	$users4 = "CORP1pellath1", "CORP2pellian5"'
Write-Output '		foreach ($u in $users4){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'four | out-File C:lnlfourresults.txt'
}
 
 
function createfive{
Write-Output 'function five{'
Write-Output '	$users5 = "CORP1trancu1", "CORP2tranth8"'
Write-Output '		foreach ($u in $users5){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'five | out-File C:lnlfiveresults.txt'
}
 
 
#Step 4 : Create .ps1 scripts out of the functions.
#Take note that .... alows for a releative path.
 
createone | out-File ....Threadone.ps1
createtwo | out-File ....Threadtwo.ps1
createthree | out-File ....Threadthree.ps1
createfour | out-File ....Threadfour.ps1
createfive | out-File ....Threadfive.ps1
 
 
#Step 5 : Launch threading script.
 
start-job -filepath ....Threadone.ps1
start-job -filepath ....Threadtwo.ps1
start-job -filepath ....Threadthree.ps1
start-job -filepath ....Threadfour.ps1
start-job -filepath ....Threadfive.ps1
 
#Step 6 : Check Status of Jobs
#The Wait-Job cmdlet waits for Windows PowerShell background jobs to complete before it displays the command prompt.
 
get-job | wait-job
 
#Step 7 : Stop any Job that may be hung.
#The Stop-Job cmdlet stops Windows PowerShell background jobs that are in progress.
 
get-job | stop-job
 
#full Script called threading.ps1
##Create Multi Thread Script
 
function createone{
Write-Output 'function one{'
Write-Output '	$users1 = "CORP1Bollasr1", "CORP2aardeje1"'
Write-Output '		foreach ($u in $users1){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'one | out-File C:lnloneresults.txt'
}
 
 
function createtwo{
Write-Output 'function two{'
Write-Output '	$users2 = "CORP1dudlesu1", "CORP2duerrma1"'
Write-Output '		foreach ($u in $users2){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'two | out-File C:lnltworesults.txt'
}
 
 
function createthree{
Write-Output 'function three{'
Write-Output '	$users3 = "CORP1khattpa2", "CORP1khattsa1"'
Write-Output '		foreach ($u in $users3){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'three | out-File C:lnlthreeresults.txt'
}
 
 
function createfour{
Write-Output 'function four{'
Write-Output '	$users4 = "CORP1pellath1", "CORP2pellian5"'
Write-Output '		foreach ($u in $users4){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'four | out-File C:lnlfourresults.txt'
}
 
 
function createfive{
Write-Output 'function five{'
Write-Output '	$users5 = "CORP1trancu1", "CORP2tranth8"'
Write-Output '		foreach ($u in $users5){'
Write-Output '			Write-Output "$u"'
Write-Output '		}'
Write-Output '}'
Write-Output 'five | out-File C:lnlfiveresults.txt'
}
 
createone | out-File ....Threadone.ps1
createtwo | out-File ....Threadtwo.ps1
createthree | out-File ....Threadthree.ps1
createfour | out-File ....Threadfour.ps1
createfive | out-File ....Threadfive.ps1
 
start-job -filepath ....Threadone.ps1
start-job -filepath ....Threadtwo.ps1
start-job -filepath ....Threadthree.ps1
start-job -filepath ....Threadfour.ps1
start-job -filepath ....Threadfive.ps1
 
get-job | wait-job
 
get-job | stop-job

Posted by IsaacBlum at 21 January 2010

Category: Business, For The Greater Good, Free Help, MOSS 2007, PowerShell, SharePoint

Tags: , , , , , ,

The below links were used to create this script. Thanks

http://blogs.msdn.com/powershell/archive/2009/01/10/capture-console-screen.aspx

http://www.sharepointdevwiki.com/display/public/Updating+User+Profiles+in+SharePoint+SSP+using+PowerShell

http://blogs.flexnetconsult.co.uk/colinbyrne/PermaLink,guid,a332015d-c5dc-4433-a0f3-247fd37b0b04.aspx

Download the file here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
[void][reflection.assembly]::Loadwithpartialname("Microsoft.SharePoint") | out-null
[void][reflection.assembly]::Loadwithpartialname("Microsoft.Office.Server.Search") | out-null
[void][reflection.assembly]::Loadwithpartialname("Microsoft.Office.Server") | out-null
 
#################################################################################################################
# Get-ConsoleAsText.ps1
# Thanks to http://blogs.msdn.com/powershell/archive/2009/01/10/capture-console-screen.aspx for Get-ConsoleAsText.ps1
# The script captures console screen buffer up to the current cursor position and returns it in plain text format.
#
# Returns: ASCII-encoded string.
#
# Example:
#
# $textFileName = "$env:tempConsoleBuffer.txt"
# .Get-ConsoleAsText | out-file $textFileName -encoding ascii
# $null = [System.Diagnostics.Process]::Start("$textFileName")
#################################################################################################################
function Get-ConsoleAsText{
# Check the host name and exit if the host is not the Windows PowerShell console host.
if ($host.Name -ne 'ConsoleHost')
{
  write-host -ForegroundColor Red "This script runs only in the console host. You cannot run this script in $($host.Name)."
  exit -1
}
 
# Initialize string builder.
$textBuilder = new-object system.text.stringbuilder
 
# Grab the console screen buffer contents using the Host console API.
$bufferWidth = $host.ui.rawui.BufferSize.Width
$bufferHeight = $host.ui.rawui.CursorPosition.Y
$rec = new-object System.Management.Automation.Host.Rectangle 0,0,($bufferWidth - 1),$bufferHeight
$buffer = $host.ui.rawui.GetBufferContents($rec)
 
# Iterate through the lines in the console buffer.
for($i = 0; $i -lt $bufferHeight; $i++)
{
  for($j = 0; $j -lt $bufferWidth; $j++)
  {
    $cell = $buffer[$i,$j]
    $null = $textBuilder.Append($cell.Character)
  }
  $null = $textBuilder.Append("`r`n")
}
return $textBuilder.ToString()
}
 
################################################################
 
# Pause Script
function Pause ($Message="Script Complete. Press any key to continue...")
{
Write-Host -NoNewLine $Message
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host ""
}
 
################################################################
 
function Get-UserProfileConfigManager([string]$siteUrl)
{
# Need to get a PortalContext object
# as we do not have a HttpContext we need to source one the hard way
$site=new-object Microsoft.SharePoint.SPSite($siteUrl)
$servercontext=[Microsoft.Office.Server.ServerContext]::GetContext($site)
$site.Dispose() # clean up
 
################################################################
 
# Return the UserProfileConfigManager
new-object Microsoft.Office.Server.UserProfiles.UserProfileConfigmanager($servercontext)
}
function Get-SPProfileManager([string]$siteUrl)
{
# Need to get a PortalContext object
# as we do not have a HttpContext we need to source one the hard way
$site=new-object Microsoft.SharePoint.SPSite($siteUrl)
$servercontext=[Microsoft.Office.Server.ServerContext]::GetContext($site)
$site.Dispose() # clean up
 
################################################################
 
# Return the UserProfileManager
new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($servercontext)
}
function Get-SPUserProfile([string]$siteUrl, [string] $u)
{
$upm= Get-SPProfileManager([string]$siteUrl)
if ($upm.UserExists($u) -eq $false)
{
    $upm.CreateUserProfile($u)
 
$upm.GetUserProfile($u)
}
 
################################################################
 
# Create function
function Update-UserProfileProperty()
{
	PARAM
	(
		[string] $siteUrl = $( throw "You must provide a Site Collection Url e.g. 'http://moss/'"),
		[string] $userName = $( throw "You must provide a User Name e.g. 'DOMAINUSERNAME'"),
		[string] $propName = $( throw "You must provide a User Profile Property Name e.g. 'WorkPhone'"),
		[string] $propValue = $( throw "You must provide a User Profile Property Value e.g. '0400 767 022'")
	)
	END
	{
		if ($propValue -eq "NULL" -or $propValue -eq "" -or $propValue -eq "None")
		{
			Write-Host "Property '$propName' is not set ('$propValue')"
		}
		else
		{
			$cm = get-userprofileconfigmanager $siteUrl
			$spm = Get-SPProfileManager $siteUrl
			if ($spm.UserExists($userName))
			{
				$userProfile = $spm.GetUserProfile($userName);
				$tempProp = $spm.Properties.GetPropertyByName($propName);
				if ($tempProp -eq $null)
				{
					throw "User Profile Property '$propName' does not exist!";
				}
				else
				{
					$userProfile[$propName].Value = $propValue;
					$userProfile.Commit();
				}
				write-host -foregroundcolor green "'$propName' User Profile Property updated to '$propValue' for '$userName'"
				Write-Output "'$propName' User Profile Property updated to '$propValue' for '$userName'"
			}
			else
			{
				Write-Host -ForegroundColor red  "User '$userName' does not exist in User Profiles!"
				Write-output "User '$userName' does not exist in User Profiles!";
			}
		}
	}
}
 
################################################################
 
function MySiteProUpdate{
$username = "IBAdmin", "IBGuest", "IBPowerShell"
 
# Set MySite URL
$siteUrl = "http://mysites:3000"
 
# Notifies
Write-Host "Working... Please Wait"
Write-Output " "
 
foreach($u in $username){
# Executes command for all users in this script
Write-Output "Executing this command :  Update-UserProfileProperty $siteUrl $u ActiveEmployee true"
Update-UserProfileProperty $siteUrl "$u" "ActiveEmployee" "true"
}
# Dump Console
$textFileName = "C:IBLogsConsoleDump.txt"
Get-ConsoleAsText | out-file $textFileName -encoding ascii
#$null = [System.Diagnostics.Process]::Start("$textFileName")
pause
}
################################################################
 
MySiteProUpdate | out-File C:IBLogsProgress.txt

Posted by IsaacBlum at 31 December 2009

Category: Business, For The Greater Good, Free Help, PowerShell

Tags: ,

Add the below code to any PowerShell script to call a pause.

This code is made possible by http://blogs.msdn.com/powershell/archive/2007/02/25/pause.aspx

1
2
3
4
5
6
function Pause ($Message="Press any key to continue...")
{
Write-Host -NoNewLine $Message
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host ""
}

While trying to create this script I came across a ton of help, Thanks online community’s!!

Download file here

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
 
# Execute a SQL File Begin
function Execute-SqlFile($file, [string]$Server, [string]$dbName, [hashtable]$variables, [switch]$WindowsAuthentication=$true, [string]$Username, [string]$Password) {
$batch = (join-Path (cat env:TEMP) "exec_sql.bat")
write-Host Connecting to $Server</code>
 
$output = (join-Path $env:TEMP "output_sql.txt")
if (test-Path $batch) {
Remove-Item $batch -force
}
$data = ""
if (test-Path $batch) { Remove-Item $batch }
$data += "sqlcmd -S $Server"
 
if ($WindowsAuthentication) {
$data += ' -E'
} else {
$data += " -U $Username -P $Password"
}
if ($dbname) {
$data += " -d $dbName"
}
 
if ($variables -and $variables.Count -gt 0) {
$data += ' -v '
$isFirst = $true
foreach($key in $variables.keys) {
 
if (! $isFirst) { $data += ' ' } else { $isFirst=$false }
 
$val = $variables[$key]
$data += "$key="
$data += "`"$val`""
 
}
}
$data += " -i `"$file`""
 
$data += " -o `"$output`""
 
$data | Add-Content $batch -force
 
cmd /c (Resolve-Path $batch)
 
gc $output
 
}
 
 
# Allows for a Pause Begin
function Pause ($Message="Press any key to continue...")
{
Write-Host -NoNewLine $Message
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host ""
}
 
 
# Sets Variables By Asking The Users a Question Begin
$Yourfirstname = Read-Host "What is Your First Name? 5 characters Max "
$yourrandomnumber = Read-Host "Random Number? Two Digits Max"
 
 
# Hard Coded Variables Begin
$aspen = "aspen-"
$dash = "-"
$computer = "."
 
 
# Rename Computer EX: aspen-john-1  Begin
$computerobject = (gwmi -Class Win32_ComputerSystem -Namespace "rootcimv2" -ComputerName $computer)
$computerobject.rename("$aspen$Yourfirstname$dash$yourrandomnumber")
 
 
# Get the Conputers Name Begin
$comp = get-wmiobject Win32_ComputerSystem
 
 
# Joings Computer to the Doamin Begin
# ("%DomainName%","%Username'sPassword%","%DomainNameUsername%",$null,3)
$comp.JoinDomainOrWorkGroup("%%%%%","%%%%%","%%%%",$null,3)
 
 
# Calls another PowerShell Script To Set Permission Begin
# ./SetFolderPermission.ps1 -Access %Username% -Permission %PermisionLevel%
./SetFolderPermission.ps1 -Access %DomainName%%Username% -Permission FullControl
 
 
# Hard Coded Variables Begin
$domain = "%DomainName%"
$strComputer = gc env:computername
 
 
# Sets Variables By Asking The Users a Question Begin
$username = Read-Host "What is Your Aspenware domain username without the %DomainName%"
 
 
# Adds User to Aministrators Group Begin
$computer = [ADSI]("WinNT://" + $strComputer + ",computer")
$computer.name
$Group = $computer.psbase.children.find("administrators")
$Group.name
$Group.Add("WinNT://" + $domain + "/" + $username)
 
 
# Adds User to IIS_WPG Group Begin
$domain = "%DomainName%"
$strComputer = gc env:computername
$username = "svcnj"
$computer = [ADSI]("WinNT://" + $strComputer + ",computer")
$computer.name
$Group = $computer.psbase.children.find("IIS_WPG")
$Group.name
$Group.Add("WinNT://" + $domain + "/" + $username)
 
 
# Executes a SQL Script to add User Account to the SQL Server with SYSAdmin  Begin
Execute-Sqlfile "C:Documents and SettingsAdministratorsvcnjsql.sql" $computer.name
 
 
# Pause Then Reboots the Server Begin
pause
$reboot = (gwmi -Class Win32_OperatingSystem)
$reboot.psbase.scope.options.enableprivileges = $true
$reboot.reboot()
  • Archives

  • Tags

  • Subscribe
  • Pages

  • More

  • Disclaimer…

    This is my personal weblog. The opinions expressed herein are my own and are not representative of any 3rd party influence. The owner of this blog reserves the right to edit or delete any comments submitted to this blog without notice if they are deemed to be spam, offensive or otherwise inappropriate. The owner of this blog makes no representations as to the accuracy or completeness of any information on this site or found by following any link on this site. The owner will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information.


    Lastly, I do my best to document my sources if the article is not of my own creation. If I have missed or forgotten to source your work. I would love feedback via the comments section. Thank you.

DreamHost promos
SiteLock