Office 365 PowerShell Fun with Calendars

Published 9/13/2015

Prologue

Ace Fekay here again.

You might say to yourself this is some really simple stuff. Sure, it might be, for the pro. As many of you know, I’m an avid Active Directory and Exchange server engineer/architect, and an MVP in Active Directory.

Therefore with AD, Exchange, and Office 365, you will find that scripting comes into play more and more with your daily tasks.  The main reason I’m posting simple scripts is that to get the job done, I just needed an arsenal of simple quickie scripts when called upon a simple task, such as this one, dealing with mailbox permissions.

I hope this blog and my future scripts blogs, especially with Office 365, help you out.

Scope

These are a few examples of dealing with every day requests for calendar administration. Sure, you can do it from your web based, Office 365 tenant dashboard, but what fun is that?

And yes, this is simple stuff. The main reason I’m posting this, and I will be posting much more, including Office 365 scripts, is that I had to look it up. I’ve found various websites that provide how-tos, but when it comes to handling variables and piping, I’ve found there is no one place to get various examples and have found myself looking at multiple places to get this info, including my colleagues, who are extremely adept at scripting. With many place, I also see elaborate scripts that do more than what I need. They are fabulous blogs and websites, but sometimes I need the simple one-liners to perform day to day stuff.

Open PowerShell session and Login – Of course you first have to open a PowerShell session to your tenant account

Open a PowerShell window.
Run the following:
$MySession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $AceCred -Authentication Basic -AllowRedirection

This will prompt you to login using your credentials.
Then run:
import-pssession $MySession

To be able to run Start-OnlineCoexistenceSync Dirsync – on a DC

After you make any changes in your local AD, instead of waiting for the dirsync schedule to run, you can manually run a dirsync on your onprem AD to force a sync:

Command Prompt
cd “C:\Program Files\Microsoft Online Directory Sync”
Run:
.\DirSyncConfigShell.psc1

Or just run:
“C:\Program Files\Microsoft Online Directory Sync\DirSyncConfigShell.psc1”
Then run:
Start-OnlineCoexistenceSync  or invoke-dirsync

To view the dirsync log, click on the DirSync icon in task bar that opens the Synchronization Service Manager. If it’s not on the task bar, it can be found in:

“C:\Program Files\Microsoft Online Directory Sync\SYNCBUS\Synchronization Service\UIShell\miisclient.exe”

===========================================================

General Calendar Commands

To view the rights on a calendar:

get-mailboxfolderpermission MarySmith@contoso.com:\Calendar

To add rights to a calendar for a user, JohnDoe, and providing him “Editor” access rights:

Add-MailboxFolderPermission -Identity Office.Vacation.Calendar@contoso.com:\Calendar -User JohnDoe@contoso.com -AccessRights Editor

To remove JohnDoe’s rights from a calendar:

remove-mailboxfolderpermission -Identity Office.Vacation.Calendar@contoso.com:\Calendar -User JohnDoe@contoso.com

Rule to move anything with subject, “Sent by Microsoft Exchange Server 2013” to a folder called, “Rejected Calendar Notifications”

New-InboxRule “Sent by Exchange 2013” -Mailbox MarySmith@contoso.com -MyNameInToBox $true -FlaggedForAction Any -SubjectOrBodyContainsWords “Sent by Microsoft Exchange Server 2013” -MoveToFolder “Rejected Calendar Notifications” -StopProcessingRules

New-InboxRule “SendOnBehalf Sent by Exchange 2013” -Mailbox JohnDoe -MyNameInToBox $true -FlaggedForAction Any -SubjectOrBodyContainsWords “Sent by Microsoft Exchange Server 2013” -MoveToFolder “Rejected Calendar Notifications” –StopProcessingRules

Create a shared calendar in Office 365 without creating it in our Active Directory so we don’t get charged for a license.

This is an example for creating a shared calendar called “Ace’s Cancelled Meetings” with a username of AceCancelledMeetings.

1. New-Mailbox -Name “AceCancelledMeetings” -DisplayName “Ace’s Cancelled Meetings” -Share

If required:
2.  UserPrincipalName: AceCancelledMeetings@YourDomain.onmicrosoft.com

Give permissions for Mary Smith (MarySmith) to access the calendar.
3.  Add-MailboxfolderPermission AceCancelledMeetings:\Calendar -user “MarySmith” -AccessRights editor  

Give permissions for John Doe (JohnDoe) to access the calendar.
4.  Add-MailboxfolderPermission AceCancelledMeetings:\Calendar -user “JohnDoe” -AccessRights editor  

Give permissions for John Smith (JohnSmith) to access the calendar:
5. Add-MailboxfolderPermission AceCancelledMeetings:\Calendar -user “JohnSmith” -AccessRights editor

Get permissions Examples for a calendar:

PS C:\Windows> (Get-MailboxFolderPermission JohnDoe:\Calendar) | select user

Output:

User
—-
Default
User One
User Two
User Three
User Four
User Five
User Six
User Seven
User Eight

To display the accessrights for a calendar:

PS C:\> (Get-MailboxFolderPermission JohnDoe:\Calendar) | select user,accessrights

User                AccessRights
—-                ————
Default                {AvailabilityOnly}
User One            {Reviewer}
User Two            {Reviewer}
User Three            {Reviewer}
User Four            {Reviewer}
User Five            {Reviewer}
User Six            {Editor}
User Seven            {Editor}
User Eight            {Editor}
User Nine            {Owner}

PS C:\> get-MailboxFolderPermission -Identity ConfRoom1:\Calendar

FolderName           User        AccessRights
———-           —-        ————
Calendar             Default        {AvailabilityOnly}
Calendar             Anonymous        {None}
Calendar             Ace Fekay        {Editor}
Calendar             User One        {PublishingEditor}
Calendar             User Two        {PublishingEditor}
Calendar             User Three        {PublishingEditor}
Calendar             User Four        {PublishingEditor}
Calendar             User Five        {Editor}

Office 365 Alias issues

If the user’s alias, such as “JohnDoe,” doesn’t work, run the following to find and use the identifier Microsoft assigned to the user:
get-mailbox JohnDoe@contoso.com
    For example, the above query returned:   
        JohnDoe_8672d315f2
    Therefore, I had to run the following command to add permissions for that user:
    Add-MailboxFolderPermission -Identity ConfRoom22:\Calendar -User “JohnDoe_8672d315f2” -AccessRights Reviewer

Command to Add permissions to one Calendar for multiple users (list of users) importing a list of users in a text file and piping the command:

Get-Content c:\Scripts\users.txt | foreach {Add-MailboxFolderPermission -Identity Classroom2:\calendar -User $_ -AccessRights Editor}

Content of “users.txt:”
UserOne@contoso.com
UserTwo@contoso.com
UserThree@contoso.com
UserFour@contoso.com
UserFive@contoso.com
UserSix@contoso.com
UserSeven@contoso.com
UserEight@contoso.com

If you need to change the permissions on the calendar for a set of user, use the same format except use the ‘set-calendar’ command:

Get-Content c:\Scripts\users.txt | foreach {Set-MailboxFolderPermission -Identity Classroom2:\calendar -User $_ -AccessRights Editor}

If you need to give a single user permissions to multiple calendars:

This is giving MikeSmith@contoso.com access to multiple calendars

Get-Content C:\Scripts\ListOfCalendars.txt | foreach {Add-MailboxFolderPermission -Identity $_ -User MikeSmith@contoso.com -AccessRights Editor}

Content of “ListOfCalendars.txt:”

HospitalFloor1West@contoso.com:\Calendar
HospitalFloor1East@contoso..com:\Calendar
HospitalFloor1South@contoso..com:\Calendar
HospitalFloor1North@contoso..com:\Calendar
HospitalFloor2West@contoso..com:\Calendar
HospitalFloor2East@contoso..com:\Calendar
HospitalFloor2South@contoso..com:\Calendar
HospitalFloor2North@contoso..com:\Calendar

To provide permissions to multiple calendars for a list of users.

There are two variables in this scenario.

First you must bring in the list of users into memory. In this case, the users are in filename, “ListOfUsers.txt.” Now run the following to bring the users

Pull the list into memory:
PS C:\> $users= get-content C:\Scripts\ListOfUsers.txt

If you like, you can double check and see what’s in the file you just pulled in by simply typing in the variable name and hit enter:

PS C:\> $users
UserOne@contoso.com
UserTwo@contoso.com
UserThree@contoso.com
UserFour@contoso.com
UserFive@contoso.com
UserSix@contoso.com
UserSeven@contoso.com
UserEight@contoso.com
etc

You can also run the following format to get the same info on the file:

PS C:\> $users | get-member
UserOne@contoso.com
UserTwo@contoso.com
UserThree@contoso.com
UserFour@contoso.com
UserFive@contoso.com
UserSix@contoso.com
UserSeven@contoso.com
UserEight@contoso.com
etc
 
Then you bring the list of rooms into memory, “ListOfRooms.txt”
PS C:\> $resources = get-content c:\Scripts\ListOfRooms.txt

Then to see what’s in the file, run:
PS C:\> $resources

ConfRoom1
ConfRoom2
ConfRoom3
ConfRoom4
ConfRoom5
ConfRoom6
ConfRoom7
ConfRoom8
etc

Now let’s take a look at what the calendar processsing is for one of the rooms:
    PS C:\>  Get-CalendarProcessing ConfRoom1

Identity                                                     AutomateProcessing
——–                                                     ——————
ConfRoom1                                                    AutoUpdate

To get more information about the calendar processing data for the room:
    PS C:\> Get-CalendarProcessing ConfRoom1 | fl

RunspaceId                          : <snipped>
AutomateProcessing                  : AutoUpdate
AllowConflicts                      : False
BookingWindowInDays                 : 180
MaximumDurationInMinutes            : 1440
AllowRecurringMeetings              : True
EnforceSchedulingHorizon            : True
ScheduleOnlyDuringWorkHours         : False
ConflictPercentageAllowed           : 0
MaximumConflictInstances            : 0
ForwardRequestsToDelegates          : True
DeleteAttachments                   : True
DeleteComments                      : True
RemovePrivateProperty               : True
DeleteSubject                       : True
AddOrganizerToSubject               : True
DeleteNonCalendarItems              : True
TentativePendingApproval            : True
EnableResponseDetails               : True
OrganizerInfo                       : True
ResourceDelegates                   : {}
RequestOutOfPolicy                  : {}
AllRequestOutOfPolicy               : False
BookInPolicy                        : {}
AllBookInPolicy                     : True
RequestInPolicy                     : {}
AllRequestInPolicy                  : False
AddAdditionalResponse               : False
AdditionalResponse                  :
RemoveOldMeetingMessages            : True
AddNewRequestsTentatively           : True
ProcessExternalMeetingMessages      : False
RemoveForwardedMeetingNotifications : False
MailboxOwnerId                      : ConfRoom1
Identity                            : ConfRoom1
IsValid                             : True
ObjectState                         : Changed

And now the moment you’ve been waiting for: Run the following command to set Calenar Processing settings for multiple users for multiple calendars:

PS C:\> $resources | foreach {Set-CalendarProcessing $_ -AutomateProcessing autoaccept -bookinpolicy $users}

Another example providing Editor rights to a list of calendars

This is for the IT-Rooms where we must give a list of users “Editor” permissions to a list mailbox Calendars.

List of users are in file:    c:\Scripts\ListOfUsers.txt
List of mailbox room calendars    c:\ListOfRooms.txt

=====
1. Pull the list of users into memory first:
$users= get-content c:\Scripts\ListOfUsers.txt

Run $users to see what’s in the file to be sure:
$users
or
$users | get-member

=====
2. Pull in the rooms or calendars into memory:
$resources = get-content c:\ListOfRooms.txt

If you want, run this to see what’s in that file:
$resources
or
$resources | get-member

If you want, run this to see what calendar processing is currently set on one of the rooms:
get-CalendarProcessing ConfRoom1 | fl

=====
3. Run it:

$resources | foreach {Add-MailboxFolderPermission -Identity $_:\calendar -User $Users -AccessRights Editor}

=====
Or just create a DL, and add the list of users to the DL, then run the following:

This gives the group ConfRoomSchedulers@contoso.com “Editor” access rights on the rooms listed in the file ListOfRooms.txt:

Get-Content ListOfRooms.txt | foreach {Add-MailboxFolderPermission -Identity $_ -User ConfRoomSchedulers@contoso.com -AccessRights Editor}

ListOfRooms.txt contains:
ConfRoom1@contoso.com:\calendar
ConfRoom2@contoso.com:\calendar
ConfRoom3@contoso.com:\calendar
ConfRoom4@contoso.com:\calendar
ConfRoom5@contoso.com:\calendar

Change the “Default” user on a list of calendars (rroms) or users to “None.”

Get-Content c:\Scripts\ListOfRooms.txt | foreach {Set-MailboxFolderPermission -Identity $_:\Calendar -User Default -AccessRights None}

Removing Permissions for a folder (calendar in this example)

Remove-MailboxFolderPermission -Identity <mailbox>:\Calendar –User <Mailbox-that-will-be-removed-from-Calendar-Permissions>
remove-MailboxfolderPermission ConferenceRoom1 -user “John Doe” -AccessRights editor
remove-MailboxfolderPermission ConferenceRoom1:\Calendar -user “JohnDoe”

Then confirm with:
get-MailboxFolderPermission -Identity ConferenceRoom1:\Calendar

Create a conference room. Do not allow anyone to book the room other than the people that have access rights to the room:

Set-Calendarprocessing VeryImportantConfRoom7thFloor@contoso.com -AddAdditionalResponse $true -AdditionalResponse “<p><strong><font color=red

size=4>Scheduling request denied.</strong><font></p><p><font color=blue size=4>Reason code: You are not authorized to schedule meetings or

appointments in the Very Important Conference Room 7th Floor. If you must book an entry in the room, please submit a request to either Mary Smith,

John Doe, or Robert Redford. Thank you.</p><p>Your Company’s IT Department.</font></p>”

More to come…

Comments are welcomed.

==================================================================

Summary

I hope this helps!

Published 9/13/2015

Ace Fekay
MVP, MCT, MCSE 2012, MCITP EA & MCTS Windows 2008/R2, Exchange 2013, 2010 EA & 2007, MCSE & MCSA 2003/2000, MCSA Messaging 2003
Microsoft Certified Trainer
Microsoft MVP – Directory Services

clip_image002622[2] clip_image004622[2] clip_image006622[2] clip_image008622[2] clip_image010622[2] clip_image012622[2]

Complete List of Technical Blogs: http://www.delawarecountycomputerconsulting.com/technicalblogs.php

This posting is provided AS-IS with no warranties or guarantees and confers no rights.

Office 365 PowerShell Fun with Mailbox Permissions

Published 9/11/2015

Prologue

Ace Fekay here again.

You might say to yourself this is some really simple stuff. Sure, it might be, for the pro. As many of you know, I’m an avid Active Directory and Exchange server engineer/architect, and an MVP in Active Directory.

Therefore with AD, Exchange, and Office 365, you will find that scripting comes into play more and more with your daily tasks.  The main reason I’m posting simple scripts is that to get the job done, I just needed an arsenal of simple quickie scripts when called upon a simple task, such as this one, dealing with mailbox permissions.

I hope this blog and my future scripts blogs, especially with Office 365, help you out.

Scope

These are a few examples of dealing with every day requests for mailbox delegation and permissions administration. Sure, you can do it from your web based, Office 365 tenant dashboard, but what fun is that?

And yes, this is simple stuff. The main reason I’m posting this, and I will be posting much more, including Office 365 scripts, is that I had to look it up and there is no one place to get all of this at the simple level. All I see are elaborate scripts that do more than what I needed. Hence, my posts.

Open PowerShell session and Login – Of course you first have to open a PowerShell session to your tenant account

Open a PowerShell window.
Run the following:
$MySession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $AceCred -Authentication Basic -AllowRedirection

This will prompt you to login using your credentials.

Then run:
import-pssession $MySession

To be able to run Start-OnlineCoexistenceSync Dirsync – on a DC

After you make any changes in your local AD, instead of waiting for the dirsync schedule to run, you can manually run a dirsync on your onprem AD to force a sync:

Command Prompt
cd “C:\Program Files\Microsoft Online Directory Sync”
Run:
.\DirSyncConfigShell.psc1

Or just run:
“C:\Program Files\Microsoft Online Directory Sync\DirSyncConfigShell.psc1”
Then run:
Start-OnlineCoexistenceSync  or invoke-dirsync

To view the dirsync log, click on the DirSync icon in task bar that opens the Synchronization Service Manager. If it’s not on the task bar, it can be found in:

“C:\Program Files\Microsoft Online Directory Sync\SYNCBUS\Synchronization Service\UIShell\miisclient.exe”

===========================================================

To find who has been delegated to a mailbox

Get-Mailbox JohnDoe@contoso.com | fl displayname, GrantSendOnBehalfTo

To see the whole list of delegated users:

PS C:\Windows> Get-Mailbox JohnDoe@contosl.com | select -expandproperty GrantSendOnBehalfTo
Output:
user1
user2
user3
user4
user5
user6

Or you can run this, too:

PS C:\Windows> (Get-Mailbox JohnDoe@contoso.com|).grantsendonbehalfto
Output:
user1
user2
user3
user4
user5
user6

 

Remove Mike Smith as a delegate – example:

First find the permission:

This will give you a summary list:
get-mailboxpermission –identity Dept1-Shared-Mailbox | ft

This will give you a full list:
Get-MailboxPermission -identity Dept1-Shared-Mailbox | fl

Then remove it:

Remove-mailboxpermission -identity Dept1-Shared-Mailbox -user NAMPRD999\Mike.Smith8047888747747123 -AccessRights FullAccess -Inheritance All

Remove-mailboxpermission -identity Dept1-Shared-Mailbox -user NAMPRD999\Mike.Smith8047888747747123 -AccessRights SendAs -Inheritance All

To find who has FullAccess Permissions on a Mailbox

There are two ways the results can be displayed:

  • FT – Format Table – One big summarized list
  • FL – Format List – in sections with detail

using FT

get-mailboxpermission JohnDoe@contoso.com | ft

Output example:

Identity                   User                 AccessRights        IsInherited Deny
——–                    —-                      ————        ———– —-
JohnDoe               NT AUTHORITY\SELF    {FullAccess, Rea… False       False
JohnDoe               S-1-5-21-24478488… {FullAccess}        False       False
JohnDoe               NAMPRD05\jar02546… {FullAccess}        False       False
JohnDoe               NAMPRD05\FullAcce… {FullAccess}        False       False
JohnDoe               NAMPRD05\Administ… {FullAccess}        True        True
JohnDoe               NAMPRD05\Domain A… {FullAccess}        True        True
JohnDoe               NAMPRD05\Enterpri… {FullAccess}        True        True
JohnDoe               NAMPRD05\Organiza… {FullAccess}        True        True
JohnDoe               NT AUTHORITY\SYSTEM  {FullAccess}        True        False
JohnDoe               NT AUTHORITY\NETW… {ReadPermission}    True        False
JohnDoe               PRDMGT01\View-Onl… {ReadPermission}    True        False
JohnDoe               NAMPRD05\Administ… {FullAccess, Del… True        False
JohnDoe               NAMPRD05\Domain A… {FullAccess, Del… True        False
JohnDoe               NAMPRD05\Enterpri… {FullAccess, Del… True        False
JohnDoe               NAMPRD05\Organiza… {FullAccess, Del… True        False
JohnDoe               NAMPRD05\Public F… {ReadPermission}    True        False
JohnDoe               NAMPRD05\Exchange… {FullAccess, Rea… True        False
JohnDoe               NAMPRD05\Exchange… {FullAccess, Del… True        False
JohnDoe               NAMPRD05\Managed … {ReadPermission}    True        False

using FL

get-mailboxpermission JohnDoe@contoso.com | fl

Output Example:

RunspaceId      : aaa56ea5-574b-45dc-8489-d85a2013bc58
AccessRights    : {FullAccess, ReadPermission}
Deny            : False
InheritanceType : All
User            : NT AUTHORITY\SELF
Identity        : JohnDoe
IsInherited     : False
IsValid         : True
ObjectState     : Unchanged

RunspaceId      : aaa56ea5-574b-45dc-8489-d85a2013bc58
AccessRights    : {FullAccess}
Deny            : False
InheritanceType : All
User            : S-1-5-21-2447848828-1310731447-1641304557-6207581
Identity        : JohnDoe
IsInherited     : False
IsValid         : True
ObjectState     : Unchanged

RunspaceId      : aaa56ea5-574b-45dc-8489-d85a2013bc58
AccessRights    : {FullAccess}
Deny            : False
InheritanceType : All
User            : NAMPRD05\jar02546711232540629
Identity        : JohnDoe
IsInherited     : False
IsValid         : True
ObjectState     : Unchanged

RunspaceId      : aaa56ea5-574b-45dc-8489-d85a2013bc58
AccessRights    : {FullAccess}
Deny            : False
InheritanceType : All
User            : NAMPRD05\FullAccessAdmin
Identity        : JohnDoe
IsInherited     : False
IsValid         : True
ObjectState     : Unchanged

RunspaceId      : aaa56ea5-574b-45dc-8489-d85a2013bc58
AccessRights    : {FullAccess}
Deny            : True
InheritanceType : All
User            : NAMPRD05\Administrator
Identity        : JohnDoe
IsInherited     : True
IsValid         : True
ObjectState     : Unchanged

etc

Other tidbits:

===========================

To display FullAccess on a Mailbox

Get-MailboxPermission JohnDoe | Where { ($_.IsInherited -eq $False) -and -not ($_.User -like “NT AUTHORITY\SELF”) } | Select Identity,user,AccessRights | fl

===========================

This will display SendOnBehalf:

Get-RecipientPermission JohnDoe | Where { ($_.IsInherited -eq $False) -and -not ($_.Trustee -like “NT AUTHORITY\SELF”) } | Select Trustee,AccessControlType,AccessRights | fl

 

===========================

View SendAs:

Get-RecipientPermission JohnDoe | where {($_.Trustee -ne ‘nt authority\self’) -and ($_.Trustee -ne ‘Null sid’)} | select Identity,Trustee,AccessRights | fl

==========================

View all “Send As permissions” you’ve configured in your organization

Careful running this on a really large tenant or you will tie up the bandwidth and get throttled.

Get-RecipientPermission | where {($_.Trustee -ne ‘nt authority\self’) -and ($_.Trustee -ne ‘Null sid’)} | select Identity,Trustee,AccessRights

============================

Display a list of recipient’s that have FULL ACCESS permission on other recipient’s

Get-RecipientPermission JohnDoe | Where { ($_.IsInherited -eq $False) -and -not ($_.Trustee -like “NT AUTHORITY\SELF”) } | Select Trustee,AccessControlType,AccessRights | fl

============================

Display a list of recipient’s that have FULL ACCESS permission on other recipient’s

$a = Get-Mailbox $a |Get-MailboxPermission | Where { ($_.IsInherited -eq $False) -and -not ($_.User -like “NT AUTHORITY\SELF”) -and -not ($_.User -like ‘*Discovery Management*’) } | Select Identity, user, AccessRights | fl

=============================

Revoke “Send As” Permissions

Remove-RecipientPermission <Identity>  -AccessRights SendAs -Trustee <Identity>
Remove-RecipientPermission John   -AccessRights SendAs -Trustee Suzan

Adjustments & Improvements – To avoid the need for confirmation, we can add the option: “-Confirm:$False”
Remove-RecipientPermission John -AccessRights SendAs -Trustee Suzan -Confirm:$False

 

More to come…

 

 

Comments are welcomed.

==================================================================

Summary

I hope this helps!

Published 8/17/2015

Ace Fekay
MVP, MCT, MCSE 2012, MCITP EA & MCTS Windows 2008/R2, Exchange 2013, 2010 EA & 2007, MCSE & MCSA 2003/2000, MCSA Messaging 2003
Microsoft Certified Trainer
Microsoft MVP – Directory Services

clip_image002622 clip_image004622 clip_image006622 clip_image008622 clip_image010622 clip_image012622 clip_image014622

Complete List of Technical Blogs: http://www.delawarecountycomputerconsulting.com/technicalblogs.php

This posting is provided AS-IS with no warranties or guarantees and confers no rights.

Script to Search Netlogon logon scripts and Replace Drive Mappings

Prologue

Ace Fekay here again!

Once again, As many of you know, I’m an avid Active Directory and Exchange server engineer/architect, and an MVP in Active Directory. And why am I posting simple stuff, you ask. Well, because we need to use this stuff day to day, that’s why.

Yea, this may be simple, but you’d be surprised who may struggle with it, like I did. I had to get help from a colleague who put the bulk of this together. I first had an idea with my beginner’s mentality to do it a little differently, but when I saw what he suggested, I said, hmm, I still have lots to learn.

I hope this, and my future scripts, especially with Office 365, help you out.

Scope

After migrating shares from one server to another server using a Robocopy script (that I’ll post later), we needed to change the drive mappings in the logon scripts in the Netlogon share.

Keep in mind, we already have a robust DFS in place. The new sharename has targets to the old server. However, we needed to change any logon scripts still referencing the old server by either NetBIOS or by FQDN (OldServer.domain.com).Well, with 28,000 scripts, that’s something we’re not going to do manually.

This script replaces any mappings using the old server name, “OldServer” such as either \\olderserver\sharename or \\oldserver.contoso.com\sharename, to the new DFS name, \\contoso.com\NewShareName.

Code

This works fine. Watch the word-wrap in the blog.

# First run the robocopy script to copy all data
# Then run the netlogon report script to see how many bat files in netlogon reference OldServer
# Then run this script to replace any reference to “OldServer” to the new DFS sharename in the batch files for each share.
# By Ace Fekay and a colleague, who put together the bulk of this together.
# I added counters and report to the screen.
 
# If you need to run it as a different users, un-remark the following
# get-credential

$Path = “\\contoso.com\NETLOGON\”
$FilesAltered = 0
$FilesProcessed = 0
 
# This code snippet gets all the files in $Path that end in “.bat”.
cd $Path

Get-ChildItem -Filter “*.bat” | foreach{
$file = Get-Content $_
 
    #only modify files that contain the string “OldServer”
    if (Select-String -InputObject $file “OldServer”){
 
    $file = Get-Content $_
    $file = $file -replace “\\\\OldServer\\Users”,”\\contoso.com\\OldServer-Users”
    $file = $file -replace “\\\\OldServer.contoso.com\\users”,”\\contoso.com\OldServer-User”
    $file = $file -replace “\\\\OldServer\\Department”,”\\contoso.com\\OldServer-Department”
    $file = $file -replace “\\\\OldServer.contoso.com\\Department”,”\\contoso.com\OldServer-Departmentt”
    $file = $file -replace “\\\\OldServer\\GDrive”,”\\contoso.com\OldServer-GDrive”
    $file = $file -replace “\\\\OldServer\\FDrive”,”\\contoso.com\OldServer-FDrive”
    $file = $file -replace “\\\\OldServer\\HDrive”,”\\contoso.com\OldServer-HDrive”
    $file = $file -replace “\\\\OldServer\\Share2\$”,”\\contoso.com\OldServer-Share2$”
    
#comment out any net time statements, if they exist
    $file = $file -replace “^net time”,”REM net time”
    
#write out the changes
    Set-Content -Value $file -Path $_;
    Write-Host $_.Name
    write-host $file
    Write-Host “”
    $FilesAltered++
   }
$FilesProcessed++
}
Write-Host $FilesAltered ” altered out of a total of” $FilesProcessed “files processed.” 
 

Comments are welcomed.

==================================================================

Summary

I hope this helps!

Published 9/9/2015

Ace Fekay
MVP, MCT, MCSE 2012, MCITP EA & MCTS Windows 2008/R2, Exchange 2013, 2010 EA & 2007, MCSE & MCSA 2003/2000, MCSA Messaging 2003
Microsoft Certified Trainer
Microsoft MVP – Directory Services

clip_image002622 clip_image004622 clip_image006622 clip_image008622 clip_image010622 clip_image012622 clip_image014622

Complete List of Technical Blogs: http://www.delawarecountycomputerconsulting.com/technicalblogs.php

This posting is provided AS-IS with no warranties or guarantees and confers no rights.