Convert User Mailbox to Shared Mailbox

In a Co-operate environment when users leave and you wanted to store the mailbox as a shared mailbox for reference or maybe for security and compliance reasons this script below will come handy to you in such scenarios.

Script could help you on major projects like cleaning up the exchange environment or getting into a structure.

# Import CSV File
   $MailboxTypeList = IMPORT-CSV "mailbox details .csv"

Foreach ($RecipientType in $MailboxTypeList)
{
      $UserOrShared = $RecipientType.RecipientType
      $EmailAddress = $RecipientType.WindowsEmailAddress
      $Display = $RecipientType.DisplayName


      Write-Host "RecipientType: "$UserOrShared
      Write-Host "Email Address: "$EmailAddress


   If ($UserOrShared -eq "User")
   {
      Write-Host "Changing Mailbox: "$Display
      #$Members = Set-Mailbox -Identity $EmailAddress -Type Shared
    }
}

The details that should be in the CSV file are below.

Identity, Alias, DisplayName, RecipientType, UserPrincipalName, WindowsEmailAddress

Swap users from one AD group to another

AD group swaps are very common in large organization.

Below script will achieve it.

$useringroup = Get-ADGroupMember -Identity "Group name" | select name
foreach($uig in $useringroup){

    Remove-ADGroupMember -Identity "group name that users need to be removed" -Members $uig -Confirm:$false
    $uig.name + " - is removed from Group Name!!"

    Add-ADGroupMember -Identity "Group that user need to be added" -Members $uig -Confirm:$false
    $uig.name + " - is added to group name!!" 
    
}

Nested Group Checker

This was very interest concept that i worked on for a project. Nested group checker basically will identify the AD groups that have nested groups and will standard groups.

Hope the below script helps.

$MilanCTXGroups = Get-ADGroup -Filter {samaccountname -like "group name"} -Properties samaccountname | select name

$nestedGroups = @()
$notnestedGroups = @()

foreach($group in $MilanCTXGroups){
$check   = Get-ADGroupMember -Identity $group.name | select name,objectclass
   foreach($line in $check){
        if($line.objectclass.Contains("group")){
            $nestedGroups += $group.name + " is nested into : " + $line.name
    }
           
   } 
   $notnestedGroups += "Not nested : " + $group.name
}

$nestedGroups 

Generate Random Passwords

The below was something that was created out of boredom to be honest.. Hope the script help for any purpose you see fit.

Function New-RandomPassword {
Param([int]$len=9 #how long a password do you want?
     )

[string]$s="12-34_5Abc:DeF;ghI<Jkl>MP=qrStUvwxYz67@#89$%0~!^no&"


$a=$s.toCharArray()
$x=""
for ($i=1;$i -le ($len*2);$i++) {
 $rand=$a[(Get-Random -min 0 -max $a.length)]
 if ($x -notmatch $rand) {
    $x+=$rand
  }
 }

$x.Substring(3,$len)
}

Remove AD group from Leaver

Leavers! The most ignored process by Support staff the script below will do the following:
Remove AD groups if the user. One of the reason this script helped me when users are added to an AD group which allocates Office 365 License. When the user leaves the organization if the ad group that allocates the license is not removed the license is wasted

Budget plays key role in IT – As we don’t get it much 😛

$users = (Get-ADUser -Filter * -SearchBase "OU Name which the leavers are moved" -Properties *)

$ctime = Get-Date

foreach ($user in $users){

    $daycount = $ctime.Date - $user.modifyTimeStamp.Date
    $Fday = $daycount |select days
        if(($Fday.Days) -gt 7){

               "==================" >> "Output report location.txt"
               $user.Name >> "Output report location.txt"
               $groupname = Get-ADPrincipalGroupMembership $user.SamAccountName | select Name
               Write-Host >> "Output report location.txt"
               $groupname >> "Output report location.txt"
               "==================">> "Output report location.txt"
               Write-Host >> "Output report location.txt"
                Remove-ADGroupMember -Identity $groupname -Members $user.SamAccountName
             
        }else{

           $user.SamAccountName + " : Modified time stamp date is less than 7 days." >> "Output report location.txt" 

        }

       
}    

List All the Subnets in AD Sites and Service

Listing the all the sub-nets could come very handy when it comes to firewall rules. I was recently involved in the a project that requires lots of firewall rules needs to be created for business requirement and getting the sub-nets were a challenge until i made the below script.

$siteDescription=@{}
$siteSubnets=@{}
$subnetDescription=@{}

$sitesDN="LDAP://CN=Sites," + $([adsi] "LDAP://RootDSE").Get("ConfigurationNamingContext")
$subnetsDN="LDAP://CN=Subnets,CN=Sites," + $([adsi] "LDAP://RootDSE").Get("ConfigurationNamingContext")


foreach ($site in $([adsi] $sitesDN).psbase.children){
 if($site.objectClass -eq "site"){
  $siteName=([string]$site.cn).toUpper()
  $siteDescription[$siteName]=$site.description[0]
  $siteSubnets[$siteName]=@()
 }
}


foreach ($subnet in $([adsi] $subnetsDN).psbase.children){
 $subnetDescription[[string]$subnet.cn]=$subnet.description[0]
 $site=[adsi] "LDAP://$($subnet.siteObject)"
 if($site.cn -ne $null){
  $siteName=([string]$site.cn).toUpper()
  $siteSubnets[$siteName] += $subnet.cn
 }else{
  $siteDescription["Orphaned"]="Subnets not associated with any site"
  if($siteSubnets["Orphaned"] -eq $null){ $siteSubnets["Orphaned"] = @() }
  $siteSubnets["Orphaned"] += $subnet.cn
 }
}


foreach ($siteName in $siteDescription.keys | sort){
 "$siteName  $($siteDescription[$siteName])"
 foreach ($subnet in $siteSubnets[$siteName]){
  "`t$subnet $($subnetDescription[$subnet])"
 }
}

Update SQL table via Powershell

IF you have not read the Connecting to SQL blog. I would recommand to read it first before start this.

Updating SQL tables using Powershell was quite fun doesn’t have to log into a SQL management server or any application its just you and Powershell like happy couple 😛

the below script will allow you to update a SQL table.

function Start-SQLUpdate
{
	[CmdletBinding()]
	param
	(
		[string]$Server,
		[string]$Database,
		[string]$SQLQuery,
		[string]$ConnectionCredentials
	)
	$Datatable = New-Object System.Data.DataTable
	$Connection = New-Object System.Data.SQLClient.SQLConnection
	$Connection.ConnectionString = "server='$Server';database='$Database';$ConnectionCredentials"
	
	$Connection.Open()
	$Command = New-Object System.Data.SQLClient.SQLCommand
	$Command.Connection = $Connection
	$Command.CommandText = $SQLQuery
	$UpdatedRecordCount = $Command.ExecuteNonQuery()
	#return $UpdatedRecordCount
}

Connect to a SQL Database via Powershell

Th real work starts when you decided to work with Data from a different source mostly with SQL DBs

I was recently involved in to the subject matter for a project, figured out that everyday is a school day that i learned about how much stuff Powershell can do when it comes in contact with a DB source like SQL. Less talk and let me present you the script to connect to the DB

Few things to notice before running the script. You should have below details ready to make a proper connection.

Server name = SQL server name.
Database = Database name that you are going to connect.
SQl Query = SQL query that you wanna test against the DB
Userid = Username with appropriate access to the DB
Password = Password for the above username.

function Start-SQLQuery
{
	[CmdletBinding()]
	param
	(
		[string]$Server,
		[string]$Database,
		[string]$SQLQuery
	)
	$Datatable = New-Object System.Data.DataTable
	$Connection = New-Object System.Data.SQLClient.SQLConnection
	$Connection.ConnectionString = "server='$Server';database='$Database';User Id=username;Password=Password;"
	
	$Connection.Open()
	$Command = New-Object System.Data.SQLClient.SQLCommand
	$Command.Connection = $Connection
	$Command.CommandText = $SQLQuery
	$Reader = $Command.ExecuteReader()
	$Datatable.Load($Reader)
	$Connection.Close()
	return $Datatable
}

Send Email via Powershell

Sending email is a pretty mundane task when you are a system admin. Create script that will send the mail without you opening the outlook is pretty cool and you would never be late to send that one report.

below script will allow you to send a mail via powershell.

$TodaysDate = (Get-Date -Format "yyyyMMddHHmmss")
$fileName = "attachments"
New-Item "c:\temp\$fileName" -ItemType file
$file = "c:\temp\$fileName"
$att = new-object Net.Mail.Attachment($file)
$msg = new-object Net.Mail.MailMessage
$msg.From = 'sender's email address'
$msg.To.Add('username@domain.com')
$msg.Subject = "Report"
$msg.Body = "body of the email."
$msg.Attachments.Add($att)
$smtpServer = "smtp serverl"


$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($msg)

Pretty cool isn’t it? i have been using this script for pretty much all of my automated reports to send out to management.

I do also have an Mail engine which basically shoots out email in designated time to specific people with distinct reports, which can be uploaded based on the request.

Display Message box in powershell

On my last blog i mentioned about the Menu and now its time for a message box..

Tell me who wouldn’t love to see a message box when you do something successfully, give you a proof of completion also a satisfaction in a success scenario or opens you eye when you face an error.. Anything in a message box users now a days pay more attention.

below script will show you how to create a Message box GUI in powershell.

Function Show-Msgbox {
  Param([string]$message=$(Throw "You must specify a message"),
      [string]$button="okonly",
      [string]$icon="information",
      [string]$title="Message Box"
     )

  [reflection.assembly]::loadwithpartialname("microsoft.visualbasic") | Out-Null

  [microsoft.visualbasic.interaction]::Msgbox($message,"$button,$icon",$title) 

 }

$rc=Show-Msgbox -message "Do you know what you're doing?" `
-icon "exclamation" -button "YesNoCancel" -title "Hey $env:username!!"

Switch ($rc) {
 "Yes" {"Yes."}
 "No" {"No."}
 "cancel" {"Cancel"}
}