Tag Archives | PowerShell

PowerShell wrapper function to display a dialog box

I wanted a function that I could pass some text, and it would put that text in a dialog box for the user to click okay. Simple, but I will reuse it I am sure.

 

Function JBMURPHY-DisplayWindowsForm(){
Param([parameter(Mandatory = $true)]$TextToDisplay,
$Title="DefaultTitle")
		[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
		[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
		$objForm = New-Object System.Windows.Forms.Form 
		$objForm.Text = $Title
		$objForm.Size = New-Object System.Drawing.Size(600,500) 
		$objForm.StartPosition = "CenterScreen"
		$OKButton = New-Object System.Windows.Forms.Button
		$OKButton.Location = New-Object System.Drawing.Size(250,400)
		$OKButton.Size = New-Object System.Drawing.Size(75,23)
		$OKButton.Text = "OK"
		$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
		$objForm.Controls.Add($OKButton)
		$objLabel = New-Object System.Windows.Forms.Label
		$objLabel.Location = New-Object System.Drawing.Size(10,20) 
		$objLabel.Size = New-Object System.Drawing.Size(500,400) 
		$objLabel.Text = $TextToDisplay
		$objForm.Controls.Add($objLabel) 
		$objForm.Topmost = $True
		$objForm.Add_Shown({$objForm.Activate()})
		[void] $objForm.ShowDialog()
}

PowerShell script to change default prf imported when Outlook starts up for the first time

In this previous post, I talk about how we use Office Customization Tool (OCT) and “.prf” files to deploy Office 2010. Continuing with the idea that  I want to know if a person is visiting from another office, I want to be able to switch from our default of “cached mode” to “online mode” for that visitor. I wrote this script with the logic of: IF {visiting from other office}, THEN {JBMURPHY-Install-ChangeDefaultOutlookPRF -CachedMode $false}.

This script would change where the ImportPRF registry entry points (in this example to a “.prf” file with cached mode disabled)

function JBMURPHY-Install-ChangeDefaultOutlookPRF {
 PARAM($CachedMode=$TRUE)
foreach ($PATH in (gci "HKLM:\SOFTWARE\Microsoft\Office\14.0\User Settings\*{*")){
 $ImportPRFRegPATH=$PATH.Name.Replace("HKEY_LOCAL_MACHINE","HKLM:")+"\Create\Software\Microsoft\Office\14.0\Outlook\Setup"
 If (Test-Path $ImportPRFRegPATH){
  $ImportPRFPath=$(get-itemproperty($ImportPRFRegPATH)).ImportPRF
  write-host -NoNewline "`nIportPRF=$ImportPRFPath - "
  if ($CachedMode) {
	if ($ImportPRFPath -eq "C:\PROGRA~1\MICROS~1\WITHCA~1.PRF") { write-host "Already in CachedMode"}
	else {write-host "Enabling CachedMode"
	Set-ItemProperty $ImportPRFRegPATH -Name ImportPRF -Value "C:\PROGRA~1\MICROS~1\WITHCA~1.PRF"
	write-host "Now IportPRF=$($(get-itemproperty($ImportPRFRegPATH)).ImportPRF)"
	}
  }
  else {
	if ($ImportPRFPath -eq "C:\PROGRA~1\MICROS~1\WITHOU~1.PRF") { write-host "CachedMode already turned off"}
	else {write-host "Turning Off CachedMode"
	Set-ItemProperty $ImportPRFRegPATH -Name ImportPRF -Value "C:\PROGRA~1\MICROS~1\WITHOU~1.PRF"
	write-host "Now IportPRF=$($(get-itemproperty($ImportPRFRegPATH)).ImportPRF)"
	}
  }
 }
}

PowerShell: Two functions to determine if a user is visiting the office

If you have users in distribution groups associated with each site in your organization, it should be easy to tell if a user is visiting from another office (more on why I want to do this later). First function returns the current site that the user is logging into:

Function JBMURPHY-AD-GetCurrentSite {
return [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().name
}

The second function loops through all “office groups” and if a user is in that office, it returns the group name


Function JBMURPHY-AD-GetHomeSite {
Param($username=$(cat env:username))
foreach ($group in "OfficeGroup1","OfficeGroup2","OfficeGroup3") {
	foreach ($user in $(Get-ADGroupMember $group)){
	if ($user.SamAccountName -eq $username) {return $group}
	}
}
}

Simple I know, but I want to put these together to do some custom startup activity (maybe via “Active Startup”)

PowerShell to verify ACLs (permissions) on a folder

In my previous post, I showed how to create a new ACL and apply it to a folder. Why apply it to the folder if the folder is already set correctly? I wrote the following function to compare the ACLs of a folder to a desired set of ACLs (either created by hand (lines 3-12) or copied from an existing folder (lines 12-15).

function JBMURPHY-PERMS-ArePermsCorrect {
        Param([parameter(Mandatory = $true)]$Path,
              [parameter(Mandatory = $true)]$CorrectACL,
              [switch]$ShowCorrect)

    $folderACLs=get-acl(get-item $Path)
    if ((compare-object $($folderACLs.access) $($CorrectACL.access) -property FileSystemRights,IdentityReference,InheritanceFlags,PropagationFlags).count -gt 0) {
    Write-host "$PATH is INCORRECT"
    return $false
    }
    else {
    if ($ShowCorrect.IsPresent){write-host "$PATH is correct"}
    return $true
    }
}

If the compare-object command returns nothing, then they are the same, if they are not the same then the items returned will be greater than 0, and the first part of the conditional will be used.

PowerShell to assign permission to a folder (not copy inherited permissions)

In my previous post, I used PowerShell to change the permissions of a top level folder. In that script, I took the folder in question and copied the inherited permissions to it, and then I tinkered it to be what I wanted. I wanted to do something similar, but I wanted a set of permission that differed from the parent. Basically I wanted the folder to have unique permissions. Below is the function to do that:

function JBMURPHY-PERMS-ClientsFolderReBase {
    Param([parameter(Mandatory = $true)]$Path)
    $correctACLs = New-Object System.Security.AccessControl.DirectorySecurity
    $correctACLs.SetAccessRuleProtection($true,$true)
    $Rule_Admin = New-Object Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators",@("FullControl"),"ContainerInherit, ObjectInherit","None","Allow")
    $Rule_System = New-Object Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\SYSTEM",@("FullControl"),"ContainerInherit, ObjectInherit","None","Allow")
    $Rule_Users1 = New-Object Security.AccessControl.FileSystemAccessRule("BUILTIN\Users",@("ReadAndExecute", "Synchronize"),"None","None","Allow")
    $Rule_Users2 = New-Object Security.AccessControl.FileSystemAccessRule("BUILTIN\Users",@("Modify, Synchronize"),"ContainerInherit, ObjectInherit","InheritOnly","Allow")
    $correctACLs.AddAccessRule($Rule_Admin)
    $correctACLs.AddAccessRule($Rule_System)
    $correctACLs.AddAccessRule($Rule_Users1)
    $correctACLs.AddAccessRule($Rule_Users2)
    write-host "Changing $Path"
    set-acl $path $correctACLs
}

In line 3 I create a new ACl, and in line 4, I set the cal to not inherit parent permissions.

Lines 4-8 are the specific permissions I want to apply (they are addressing the same issue I described here)

Lines 9-12 add the new perms to the new ACL, and line 14 set the ACL of the folder to the new ACL.

A little different want o go about this, as I created an ACL from the start.

PowerShell: Return, ForEach,ForEach-Object and a pipe

I just figured this out late last night. I was pulling my hair out. If you look at the following PowerShell code

($MyArray=1,2,3,4,5) | foreach-object {
write-host $_
if ($_ -eq 3 ){return}
}

You get a result of:
1
2
3
4
5

Next, if you look at this code (the only real difference being the lack of a pipe.)

foreach ($item in ($MyArray=1,2,3,4,5)) {
write-host $item
if ($item -eq 3 ){return}
}

You get:
1
2
3

That stumped me. Why would they not produce the same thing? Then I ran across this thread. The replier said

I think because ForEach-Object processes each item in the pipeline, but the foreach statement processes the collection as a whole.

This led me to this page, and specifically this quote clears it up for me (kinda):

 . . . [the object] it is sent into the pipeline and execution continues in the next section of the pipeline.  . . . the foreach alias gets executed and the object is run through the process script block of ForEach-Object.  Once the process script block completes, the object is discarded and the next object is [sent] . . .

In summary, last night I learned that when using a pipeline, the first item is passed to the script block, the script block is run, and then the next item is passed to the script block, and so on.

That sound correct? Can you come up with a better description?

PowerShell code to split a space delimited string – with double spaces

I am working on a PowerShell wrapper script to run multiple commands on multiple machines. The first thing I wanted to do was to chop up a space or comma delimited argument. (If you make an argument mandatory, and the user does not provide it, PowerShell will prompt you for it – and when prompted you can use space delimited values).

I was going to use the split() function, but I did not know how to handle “multiple spaces”. For example:

("123  4 5678").Split() = 
123
 
 
4

5678"

I would end up with “empty” array members. I found this post, and they guy used “| where-object {$_ -ne ”“}” to filter out the empty values. But then I stumbled upon a better way to do it, using the built in “StringSplitOptions” of  RemoveEmptyEntries.

("123  4 5678").split(" ",[StringSplitOptions]'RemoveEmptyEntries')

would result in:

123
4
5678

If you don’t know if you are going to have space or comma delimited then I used:

$Argument.split(" ",[StringSplitOptions]'RemoveEmptyEntries') | foreach {
$_.split(",",[StringSplitOptions]'RemoveEmptyEntries')}

Start Visual Studio form PowerShell

I am moving on to a new project – our migration from SharePoint 2007 to 2010. First thing I wanted to do was to upgrade my Solutions/Features from 2007 to 2010. I installed Visual Studio and started looking at how to recreate my Delegate JQuery Control (more on that later). The first thing I found annoying was that every time I added an “Empty SharePoint Project”, I received a warning “This task requires the application to have elevated permissions”. That is annoying. Since I usually leave a PowerShell prompt running as administrator (It has a red background to distinguish it), I wanted to quickly open VisualStudio from that PowerShell prompt. Here is my wrapper script to open VisualStudio 2010 from PowerShell:

function JBMURPHY-Start-VisualStudio {
Start-Process "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" -workingdirectory "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\"
}

PowerShell wrapper script to send email

I wanted a standard function that I can call from other scripts to send email. I needed multiple recipients, and default sender and smtp arguments. Here is the script that I came up with.

function JBMURPHY-Send-Email {
Param(	[parameter(Mandatory = $true)]$ToAddress,
	[parameter(Mandatory = $true)]$Subject,
	[parameter(Mandatory = $true)]$Body,
	[parameter(Mandatory = $false)]$FromAddress="[email protected]",
	[parameter(Mandatory = $false)]$SMTPAddress="192.168.1.1")
$msg = New-Object Net.Mail.MailMessage
$msg.From = $FromAddress
$msg.Body = $Body
$msg.Subject = $Subject
if($ToAddress -isnot [Object[]]) {$ToAddresses = ([string]$ToAddress).Split(";")}
foreach($Address in $ToAddresses) { $msg.To.Add($Address)}
$smtp = new-object Net.Mail.SmtpClient($SMTPAddress)
$smtp.Send($msg)
}

PowerShell script to add users to a group

In this previous post : PowerShell wrapper for creating a new distribution group, I created a script for creating a new distribution group. I wanted to take that a step further and prompt the SysAdmin to add users. I created a new recursive function called AddToDistributionGroup. In this code, I prompt for a group name, and a user to add. The SysAdmin types in the first few parts of the name (I could have used samaccountname) and then I then loop through ADusers with that name asking the SysAdmin if that is the user they want to add.

function JBMURPHY-EXCHANGE-AddToDistributionGroup {
Param(	[parameter(Mandatory = $true)]$GroupName,
	[parameter(Mandatory = $true)]$UserToAdd)
JBM-EXCHANGE-StartPSSESSION
if (!($GroupName)) {write-host "you need to specify a group name"
break}
if (($UserToAdd)) {
 $UserToAdd=$UserToAdd+"*"
 Get-aduser -filter {(name -like $UserToAdd) -and (Enabled -eq $true)} | foreach-object {
  $UserName=$_.Name
  $message = "Add $UserName to the group: $GroupName"
  $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Yes add $UserName to the group $GroupName"
  $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No","No, don't add $UserName to the group $GroupName?"
  $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
  $result = $host.ui.PromptForChoice($title, $message, $options, 0) 
  if ($result -eq 0){
   write-host "Adding $UserName"
   Add-DistributionGroupMember -Identity $GroupName -Member $UserName
  }
 }
JBM-EXCHANGE-AddToDistributionGroup $GroupName
}
}

* Note, there is not any error checking to see if the group exists. I am mainly using this code to be called from a NewDistributionGroup script, where I know the name of the group. I may add a lookup to see if the group exists at some point.

** Now that I think about it, this is for any type group, not just distribution groups.