How to find saved wireless passwords on your Windows

To find saved wireless password on your windows, please follow this steps:

  1. Open a cmd with admins rights and run the following command to see your wireless profiles:

    netsh wlan show profile

  2. Identify the wireless profile that you want to get the password, and run the following command:

    netsh wlan show profile “WIRELESS PROFILE NAME” key=clear


    You’ll see your Wi-Fi password in the Key Content field.

    Good luck with finding out your wireless password.

Script to set Outlook signature using AD info, Security Groups and Templates

Script to set Outlook e-mail signature using Active Directory information, Security groups and unlimited templates.

Script Localization: https://gallery.technet.microsoft.com/office/Script-to-set-Outlook-da7b56ee 

PowerShell
<#
    .SYNOPSIS
    Script to set Outlook 2010/2013/2016 e-mail signature using Active Directory information, Security groups and unlimited templates
    .DESCRIPTION
    This script will set the Outlook 2010/2013/2016 e-mail signature on the local client using Active Directory information. 
    The template is created with a Word document, where images can be inserted and AD values can be provided.

    Author: João Dias
	Company: Mutega IT AB
	Email: jd@mutega.se
	Site: www.mutega.se
    Version 1.0
	
	Script it is a mix of Jan Egil Ring and Daniel Classon Script
	https://gallery.technet.microsoft.com/office/6f7eee4b-1f42-499e-ae59-1aceb26100de
	https://gallery.technet.microsoft.com/office/Set-Outlook-20102013-8341e049

    .DISCLAIMER
    All scripts and other powershell references are offered AS IS with no warranty.
    These script and functions are tested in my environment and it is recommended that you test these scripts in a test environment before using in your production environment.
    #>


#Custom variables
$SignatureName = 'OSignature' #insert the company name (no spaces) - could be signature name if more than one sig needed
$SigSource = $env:appdata+"\MUTEGA\OutlookSignature\Templates\OSignature.docx" #Path to the *.docx file, i.e "c:\temp\template.docx"
$Source = $env:appdata+"\Mutega\OutlookSignature\IMG\"
$SignatureVersion = "1.0" #Change this if you have updated the signature. If you do not change it, the script will quit after checking for the version already on the machine
$ForceSignature = '1' #Set to 1 if you don't want the users to be able to change signature in Outlook
 
#Environment variables
$AppData=(Get-Item env:appdata).value
$SigPath = '\Microsoft\Signatures'
$LocalSignaturePath = $AppData+$SigPath
$RemoteSignaturePathFull = $SigSource

<# #Copy version file
If (-not(Test-Path -Path $LocalSignaturePath\$SignatureVersion))
{
New-Item -Path $LocalSignaturePath\$SignatureVersion -ItemType Directory
}
Elseif (Test-Path -Path $LocalSignaturePath\$SignatureVersion)
{
Write-Output "Latest signature already exists"
break
}  #>

#Check signature path (needs to be created if a signature has never been created for the profile
if (-not(Test-Path -path $LocalSignaturePath)) {
	New-Item $LocalSignaturePath -Type Directory
}

#Get Active Directory information for current user
$UserName = $env:username
$Filter = "(&(objectCategory=User)(samAccountName=$UserName))"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter = $Filter
$ADUserPath = $Searcher.FindOne()
$ADUser = $ADUserPath.GetDirectoryEntry()
$ADDisplayName = $ADUser.DisplayName
$ADEmailAddress = $ADUser.mail
$ADTitle = $ADUser.title
$ADDescription = $ADUser.description
$ADTelePhoneNumber = $ADUser.TelephoneNumber
$ADMobile = $ADUser.mobile
$ADStreetAddress = $ADUser.streetaddress
$ADwWWHomePage = $ADUser.wWWHomePage
$ADCity = $ADUser.l
<# $ADCustomAttribute1 = $ADUser.extensionAttribute1 #>
$ADModify = $ADUser.whenChanged

#Copy signature templates from source to local Signature-folder
Write-Output "Copying Signatures"
Copy-Item "$Sigsource" $LocalSignaturePath -Recurse -Force
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False
	
#Insert variables from Active Directory to rtf signature-file
$MSWord = New-Object -ComObject word.application
$fullPath = $LocalSignaturePath+'\'+$SignatureName+'.docx'
$MSWord.Documents.Open($fullPath)

<# 	
#User Name $ Designation 
$FindText = "DisplayName"
$Designation = $ADCustomAttribute1.ToString()

#Designations in Exchange custom attribute 1
If ($Designation -ne '') { 
	$Name = $ADDisplayName.ToString()
	$ReplaceText = $Name+', '+$Designation
}
Else {
	$ReplaceText = $ADDisplayName.ToString() 
}
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,	$MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,	$Format, $ReplaceText, $ReplaceAll	) 
#>

#DisplayName		
$FindText = "DisplayName"
$ReplaceText = $ADDisplayName.ToString() 
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,	$MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,	$Format, $ReplaceText, $ReplaceAll	)
	
#Title		
$FindText = "Title"
$ReplaceText = $ADTitle.ToString()
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,	$MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,	$Format, $ReplaceText, $ReplaceAll	)
	
#Description
   If ($ADDescription -ne '') { 
   	$FindText = "Description"
   	$ReplaceText = $ADDescription.ToString()
}
Else {
	$FindText = " | Description "
   	$ReplaceText = "".ToString()
}
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,	$MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,	$Format, $ReplaceText, $ReplaceAll	)
#$LogInfo += $NL+'Description: '+$ReplaceText
   	
#Street Address
If ($ADStreetAddress -ne '') { 
       $FindText = "StreetAddress"
    $ReplaceText = $ADStreetAddress.ToString()
   }
   Else {
    $FindText = "StreetAddress"
    $ReplaceText = $DefaultAddress
    }
	$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,	$MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,	$Format, $ReplaceText, $ReplaceAll	)

#City
If ($ADCity -ne '') { 
    $FindText = "City"
       $ReplaceText = $ADCity.ToString()
   }
   Else {
    $FindText = "City"
    $ReplaceText = $DefaultCity 
   }
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,	$MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,	$Format, $ReplaceText, $ReplaceAll	)
	
#Telephone
If ($ADTelephoneNumber -ne "") { 
	$FindText = "TelephoneNumber"
	$ReplaceText = $ADTelephoneNumber.ToString()
   }
Else {
	$FindText = "TelephoneNumber"
    $ReplaceText = $DefaultTelephone
	}
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,	$MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,	$Format, $ReplaceText, $ReplaceAll	)
	
#Mobile
If ($ADMobile -ne "") { 
	$FindText = "MobileNumber"
	$ReplaceText = $ADMobile.ToString()
   }
Else {
	$FindText = "| Mob MobileNumber "
    $ReplaceText = "".ToString()
	}
$MSWord.Selection.Find.Execute($FindText, $MatchCase, $MatchWholeWord,	$MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap,	$Format, $ReplaceText, $ReplaceAll	)

#Email
$MSWord.Selection.Find.Execute(“EmailAddress”) 
$MSWord.ActiveDocument.Hyperlinks.Add($MSWord.Selection.Range, “mailto:”+$ADEmailAddress.ToString(), $missing, $missing, $ADEmailAddress.ToString()) 

#Linkedin
$selection = $MSword.selection
$selection.TypeParagraph()
$selection.TypeParagraph()
$selectimage = $selection.InlineShapes.AddPicture($Source+"\linkedinbutton.jpg")
$msword.ActiveDocument.Hyperlinks.Add($selectimage.Range,$ADwWWHomePage.ToString())
$selection.TypeParagraph()

#Save new message signature 
Write-Output "Saving signatures"

#Fixes Enumeration Problems
$wdTypes = Add-Type -AssemblyName 'Microsoft.Office.Interop.Word' -Passthru
$wdSaveFormat = $wdTypes | Where {$_.Name -eq "wdSaveFormat"}

#Save HTML
$path = $LocalSignaturePath+'\'+$SignatureName+".htm"
$MSWord.ActiveDocument.saveas([ref]$path, [ref]$wdSaveFormat::wdFormatHTML);
$MSWord.ActiveDocument.saveas($path, $wdSaveFormat::wdFormatHTML);
    
#Save RTF 
$path = $LocalSignaturePath+'\'+$SignatureName+".rtf"
$MSWord.ActiveDocument.SaveAs([ref]$path, [ref]$wdSaveFormat::wdFormatRTF);
$MSWord.ActiveDocument.SaveAs($path, $wdSaveFormat::wdFormatRTF);
	
#Save TXT    
$path = $LocalSignaturePath+'\'+$SignatureName+".txt"
$MSWord.ActiveDocument.SaveAs([ref]$path, [ref]$wdSaveFormat::wdFormatUnicodeText);
$MSWord.ActiveDocument.SaveAs($path, $wdSaveFormat::wdFormatUnicodeText);
	
$MSWord.ActiveDocument.Close();
$MSWord.Quit();

#Remove old regedit keys
If (Test-Path HKCU:'\Software\Microsoft\Office\14.0')
{
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\14.0\Common\MailSettings' -Name 'ReplySignature'
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\14.0\Common\MailSettings' -Name 'NewSignature'
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\14.0\Outlook\Setup' -Name 'First-Run'
}
If (Test-Path HKCU:'\Software\Microsoft\Office\15.0')
{
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'ReplySignature'
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'NewSignature'
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Outlook\Setup' -Name 'First-Run'
}
If (Test-Path HKCU:'\Software\Microsoft\Office\16.0')
{
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'ReplySignature'
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'NewSignature'
Remove-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Outlook\Setup' -Name 'First-Run'
}

#Office 2010
If (Test-Path HKCU:'\Software\Microsoft\Office\14.0')
{
If ($ForceSignature -eq '1')
    {
    Write-Output "Setting signature for Office 2010 as forced"
    New-ItemProperty HKCU:'\Software\Microsoft\Office\14.0\Common\MailSettings' -Name 'ReplySignature' -Value $SignatureName -PropertyType 'String' -Force
    New-ItemProperty HKCU:'\Software\Microsoft\Office\14.0\Common\MailSettings' -Name 'NewSignature' -Value $SignatureName -PropertyType 'String' -Force
    }
else
{
Write-Output "Setting Office 2010 signature as available"

$MSWord = New-Object -comobject word.application
$EmailOptions = $MSWord.EmailOptions
$EmailSignature = $EmailOptions.EmailSignature
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries

}
}

#Office 2013
If (Test-Path HKCU:'\Software\Microsoft\Office\15.0')
{
If ($ForceSignature -eq '1')
    {
    Write-Output "Setting signature for Office 2013 as forced"
    New-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'ReplySignature' -Value $SignatureName -PropertyType 'String' -Force
    New-ItemProperty HKCU:'\Software\Microsoft\Office\15.0\Common\MailSettings' -Name 'NewSignature' -Value $SignatureName -PropertyType 'String' -Force
    }
else
{
Write-Output "Setting Office 2013 signature as available"

$MSWord = New-Object -comobject word.application
$EmailOptions = $MSWord.EmailOptions
$EmailSignature = $EmailOptions.EmailSignature
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries

}
}


#Office 2016 signature

If (Test-Path HKCU:'Software\Microsoft\Office\16.0')

{
Write-Output "Setting signature for Office 2016"

If ($ForceSignature -eq '1')

{
Write-Output "Setting Office 2016 as available"

$MSWord = New-Object -ComObject word.application
$EmailOptions = $MSWord.EmailOptions
$EmailSignature = $EmailOptions.EmailSignature
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries

}

If ($ForceSignature -eq '1')
{
Write-Output "Setting signature for Office 2016 as forced"
    If (Get-ItemProperty -Name 'NewSignature' -Path HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings') { } 
    Else { 
    New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'NewSignature' -Value $SignatureName -PropertyType 'String' -Force 
    } 
    If (Get-ItemProperty -Name 'ReplySignature' -Path HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings') { } 
    Else { 
    New-ItemProperty HKCU:'\Software\Microsoft\Office\16.0\Common\MailSettings' -Name 'ReplySignature' -Value $SignatureName -PropertyType 'String' -Force
    } 
}

}
taskkill /F /IM winword.exe

Prerequisites

User Groups

Name Description Type
OSIGADMIN Outlook Signature Admin Group Security Group – Global
MTSE001 User Outlook Signature Template in Swedish without Mobile Number Security Group – Global
MTSE002 User Outlook Signature Template in Swedish with the Mobile Number Security Group – Global

Nomeclature for Creation of User Groups

Example:

MTSE001

MT = MUTEGA IT 

SE = Swedish

001 = Template number 001

The security group and the template .docx must have the same name, as I should describe further on.

Active Directory Fields

The Outlook Signature gets the information from the Active Directory, so we need to fill up the following fields.

AD Fields

DisplayName

Title

telephoneNumber

mobileNumber

EmailAddress

wWWHomePage

Outlook Signature localization (Example)

Location of the script files: \\mutega.local\SysVol\mutega.local\scripts\OutlookSignature

Location of the logon file: \\mutega.local\SysVol\mutega.local\Policies\{xxxxx-xxxx-xxxxx-xxxxx}\User\Scripts\Logon

Location of the Outlook Signature of the Clients: %appdata%\mutega\Outlooksignature

Final location of the Outlook Signature on the Clients: %appdata%\Microsoft\Signatures

Outlook e-mail Signature GPO

This GPO is the one responsible to run Outlook Signature script at the Log On.

Name of the GPO: OutlookSignature

Fuction: Running the file Run_LO.cmd for the users that below to the Outlook Signature Security Group.

Outlook Signature Execution

The Outlook signature runs allow on the Logon, but the execution only occurs in the following conditions:

  1. The version of the Signature is not the same;
  2. The user is added to an Outlook Signature security group;
  3. The user is changed to a new Outlook Signature security group to another one;
  4. The Signature file under %appdata%\Microsoft\Signatures is deleted manually.

Outlook Signature Desktop Icon

Now the user has the possibility to recreate the Outlook Signature.

  1. The shortcut is called ReCreate Outlook Signature, and if the end-user double clicks it, will recreate the Outlook Signature

 

Script – Migration of mailboxes from Exchange On-premise to Exchange Online

If you want to perform a bulk migration of mailboxes from Exchange On-premise to Exchange Online, this PowerShell script will help you.

You just need to create a txt file with the alias mailboxes that you want to migrate. The script will migrate all the alias mailboxes on the txt to Office 365 (Exchange Online).

This is tested on an Exchange 2010 Hybrid environment but should work also on the new Exchange version.

Script localization: https://gallery.technet.microsoft.com/office/Script-Migration-of-0f2aa80d 

 

PowerShell
#********************************************************************************************* 
 
# Migration of mailboxes from Exchange On-premise to Exchange Online 
# 
# Written by João Dias  
# Date 28/03/2017 
# 
# Version: 1.0 
# 
#********************************************************************************************* 
 
#Set Powershell Execution Policy to Unrestricted 
Set-ExecutionPolicy Unrestricted -Force 
 
#Get credentials 
$O365CREDS = Get-Credential 
$ONPREMCREDS = Get-Credential 
 
#Configuring Session 
$SESSION = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365CREDS -Authentication Basic -AllowRedirection 
 
#Import Exchange Online Session 
Import-PSSession $SESSION 
 
#Connect to Exchange Online 
Connect-MsolService -Credential $O365CREDS 
 
#Reading the user list that will be migrated to O365 
$MAILBOXLIST = Get-Content "C:\temp\Userlist.txt" 
 
#Migration of mailboxes to O365 
foreach ($line in $MAILBOXLIST) {New-MoveRequest -Identity $line.alias -Remote -RemoteHostName niras.dk -TargetDeliveryDomain niras.mail.onmicrosoft.com -RemoteCredential $ONPREMCREDS -BadItemLimit 1000}

Troubleshoot Outlook performance issues – Exchange/Office 365

It is not the first, and it will not be the last client that ask me what to do to fix Outlook performance issues.

Dennis from blogoffice365.com has written an article that mirrors what I usually recommend to my customers.

Here it is Dennis fantastic post. To see the original post click here.

(more…)

Windows 2016 or Windows 10 fail to perform an in-place upgrade

When performing a Windows Server 2012 in-place upgrade to Windows Server 2016, and you get an error pops up saying just that the upgrade has failed, the first thing to do is look at the logs.

Location of the Windows Server 2016 in-place upgrade: C:\$Windows.~BT\Sources\panther\setupact.log

More info regarding log files that are created when you upgrade to a new version of Windows: https://support.microsoft.com/en-us/help/928901/log-files-that-are-created-when-you-upgrade-to-a-new-version-of-window

If you got these two errors below, we have the solution for you.

Error    MOUPG CDlpActionProductKeyValidate::ReportDownlevelInstallChannel(2896): Result = 0x80070490[gle=0x00000002]

Error    MOUPG ProductKey: Failed to report Host OS channel to telemetry.[gle=0x00000002]

The system was not able to mount the WIM file, so what can be preventing this to happen?

A filter driver could be causing this error. To find the filter driver, run this:

fltmc filters


CBFLTFS4 is a CallBackFilter develped by Eldos.


According to Eldos:
Callback File System (CBFS) lets you create virtual file systems and disks that expose and manage remote data as if these data were files on the local disk.

Callback File System is an SDK (software development kit, a component for use in software development) for Windows® platform.

We have it in our remote application host server because we have installed Liquidware Labs’ ProfileUnity.

SOLUTION
We need to temporarily disable this filter driver.

  1. In order to do that we need to change the registry key:

    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\cbfltfs4
    Value: Start
    Type: REG_DWORD
    To: 4

  2. Restart the machine

You can also run this command line:

Disable
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\cbfltfs4 /v Start /t REG_DWORD /d 4 /f

Enable Startup automatically (To run after the machine is upgraded)

reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\cbfltfs4 /v Start /t REG_DWORD /d 0 /f

Reference: Charlie Chang Blog

Modifying Lync Server 2013 or Skype for Business 2015 Monitoring Reports URLs on the Control Panel

After moving the Skype for Business Monitoring Reports to a new SQL Server Reporting Services (SSRS) instance on another server, everything was working, but I was still seeing the old server and the new links to the Reporting Service on the Control Panel under “View Monitoring reports”.

So I add to remove the old Monitoring report server and edit the new one with the correct link page.

To do that I add made the following step:

  1. To check the configuration:

    Get-CsReportingConfiguration

    (For Lync Server 2010 “Get-CsService -MonitoringServer | Select-Object Identity”)

  2. Identify the old monitoring server and run:

    Remove-CsReportingConfiguration –identify “Service:….”

  3. Check that the old server is now removed:

    Get-CsReportingConfiguration

  4. Edit the new server with the desired configurations:

    Set-CsMonitoringServer -Identity ” Service:….”” -ReportingUrl “https://server.[domain]/ReportServer/Pages/ReportViewer.aspx?/LyncServerReports/Reports%20Home%20Page

Now you can see that I only have one link under the “View Monitoring reports” and it works with the correct link.

skype for business server 2015 control panel

Hope this helps you, and if you need some help, just contact us.

Windows 10 Stuck on Welcome Screen

If your computer was working perfectly until the last week, and now you get stuck on the welcome screen, whenever you reboot the computer, or the computer goes into sleep mode!?  This means that you have installed some nasty quality windows updates that are making your computer stop responding.

Are you getting crazy with this bug!? I was!!!

Search message tracking logs

Message tracking records the message activity as mail flows through the transport pipeline on Mailbox servers and Edge Transport servers. You can use the Get-MessageTrackingLog cmdlet in the Exchange Management Shell to search for entries in the message tracking log by using specific search criteria. For example:

  • Find out what happened to a message that was sent by a user to a specific recipient.
  • Find out if a transport rule acted on a message.
  • Find out if a message sent from an Internet sender made it into your Exchange organization.
  • Find all messages sent by a specified user during a specified time period.

This example searches the message tracking logs on the local server for all entries from 2/20/2018 8:00 AM to 2/20/2015 5:00 PM for all FAIL events where the message sender was sender@mutega.se

Get-MessageTrackingLog -ResultSize Unlimited -Start “2/20/2018 8:00AM” -End “2/20/2018 5:00PM” -EventId “Fail” -Sender “sender@mutega.se”

This example searches the message tracking logs on the local server for all entries from 2/20/2018 8:00 AM to 2/20/2015 5:00 PM for all emails sent to to@mutega.com where the message sender was sender@mutega.se

Get-MessageTrackingLog -ResultSize Unlimited -Start “2/20/2018 8:00AM” -End “2/20/2018 5:00PM” -EventId “Fail” -Sender “sender@mutega.se” -Recipients “to@mutega.com”

More info (Source article): https://technet.microsoft.com/en-us/library/bb124926%28v=exchg.160%29.aspx?f=255&MSPPError=-2147217396

Copy AD OU Structure To Another AD Location

This was made by MALEK Ahmed and change by João Dias, in order to copy a AD structure to a new AD location. Just copy and paste on the notepad and save it as .ps1

 

#START

#*********************************************************************************************
#
# Copy AD OU Structure To Another Location
#
# Written by João Dias
# Date 10/04/2017
#
# Version: 1.0
#
#*********************************************************************************************

#Configuration of the Source and the Destination
$sourceOU = “OU=mutegaold,DC=domain,DC=local”
$destinationOU = “OU=muteganew,DC=newdomain,DC=local”

#AD Path
$adPath= “LDAP://” + $destinationOU

#Importing AD module
import-module activedirectory
#Copying the OU’s to the destination
$objDomain=New-Object System.DirectoryServices.DirectoryEntry($adPath)
$ObjSearch=New-Object System.DirectoryServices.DirectorySearcher($ObjDomain)
[array] $OUs = @()
$OUs = dsquery * $sourceOU -Filter “(objectCategory=organizationalUnit)” -limit 0
$OUsorted = $OUs | sort-object { $_.Length}
for ($k=0; $k -le $OUsorted.Count -1; $k++)
{
$OUtoCreate = ($OUsorted[$k] -replace $sourceOU,$destinationOU).ToString()
$OUSearch = ($OUtoCreate -replace ‘”‘,””).ToString()
$ObjSearch.Filter = “(&(objectCategory=organizationalUnit)(distinguishedName=”+ $OUSearch + “))”
$allSearchResult = $ObjSearch.FindAll()
if ($allSearchResult.Count -eq 1)
{
“No changes were done on = ” + $OUtoCreate
}
else
{
dsadd ou $OUtoCreate
“OU Creation = ” + $OUtoCreate
}
}

#END

The script is provided “AS IS” without warranty of any kind. We disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Mutega IT, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Mutega IT has been advised of the possibility of such damages.

Export Active Directory Users data to a CSV file

Here is a old script that I write down during a AD migration, to export users data from Active Directory. Just copy and paste on the notepad and save it as .ps1

#START

#*********************************************************************************************
#
# Export AD users data
#
# Written by João Dias
# Date 10/04/2017
#
# Version: 1.0
#
#*********************************************************************************************

#Define location
$path = Split-Path -parent “c:\temp\*.*”

#Define OU location
$ou = ‘OU=users,DC=domain,DC=local’

#Create a variable for the date stamp in the log file
$LogDate = get-date -f yyyyMMddhhmm

#Define CSV and log file location variables
$csvfile = $path + “\Users_$logDate.csv”

#import the ActiveDirectory Module
Import-Module ActiveDirectory

$AllADUsers = Get-ADUser -Filter * -SearchBase $ou

$AllADUsers |
Select-Object @{Label = “First Name”;Expression = {$_.GivenName}},
@{Label = “Last Name”;Expression = {$_.Surname}},
@{Label = “Display Name”;Expression = {$_.DisplayName}},
@{Label = “Logon Name”;Expression = {$_.sAMAccountName}},
@{Label = “Full address”;Expression = {$_.StreetAddress}},
@{Label = “City”;Expression = {$_.City}},
@{Label = “State”;Expression = {$_.st}},
@{Label = “Post Code”;Expression = {$_.PostalCode}},
@{Label = “Country/Region”;Expression = {if (($_.Country -eq ‘GB’) ) {‘United Kingdom’} Else {”}}},
@{Label = “Job Title”;Expression = {$_.Title}},
@{Label = “Company”;Expression = {$_.Company}},
@{Label = “Directorate”;Expression = {$_.Description}},
@{Label = “Department”;Expression = {$_.Department}},
@{Label = “Office”;Expression = {$_.OfficeName}},
@{Label = “Phone”;Expression = {$_.telephoneNumber}},
@{Label = “Email”;Expression = {$_.Mail}},
@{Label = “Manager”;Expression = {%{(Get-AdUser $_.Manager -server $ADServer -Properties DisplayName).DisplayName}}},
@{Label = “Account Status”;Expression = {if (($_.Enabled -eq ‘TRUE’) ) {‘Enabled’} Else {‘Disabled’}}}, # the ‘if statement# replaces $_.Enabled
@{Label = “Last LogOn Date”;Expression = {$_.lastlogondate}} |

#Export CSV report

Export-Csv -Path $csvfile -NoTypeInformation

#END

The script is provided “AS IS” without warranty of any kind. We disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Mutega IT, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Mutega IT has been advised of the possibility of such damages.