Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Monday, March 4, 2019

Powershell: Scripting, copying one users group membership to another

At $work I've been working on a new On-Boarding script, and to make things easy part of this script prompts to enter an existing users SamAccountName to copy the memberof to the new user.

It took me an hour or more of solid Google-Fu but here's the result and it works perfectly:

Get-auser -identity $copyuser -properties memberof | select-object memberof -ExpandProperty memberof | add-adgroupmember -members $newuser

Cheers.

Wednesday, September 12, 2018

Outlook 2013/2016 Meetings in room resources replace subject with organizers name...

Ran into this today.. last time was a number of years ago so I had forgotten about it.  Anyway you create a room resource mailbox in Exchange right? I 'assign' it to a conference room so users can schedule meetings and keep some semblance of order right?
Except first user opens their personal calendar, creates a meeting object, selects your new room as the location, types a descriptive subject line and send it on.
The room accepts, and adds the meeting to it's calendar except it's deleted teh subject and replaced the text with the users name.  WTH?

While I do not understand the reasoning.. this is by default.  Logon to your Exchange server, open the Management shell and type the following:


Set-CalendarProcessing -Identity <RESOURCEMAILBOX> -DeleteSubject $False -AddOrganizerToSubject $False 



Thursday, May 25, 2017

Powershell Script: Remove Windows 10 Apps

Tired of all the bullshit apps that Microsoft bundles with Windows 10?  I know I am!

This is just a combination of the same stuff that can be found on MANY websites out there.  I just didn't want to create 15 individual .ps1's or copy/paste as many times.




Get-AppxPackage *xboxapp* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *soundrecorder* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *bingsports* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *windowsphone* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *people* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *onenote* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *bingnews* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *zunevideo* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *bingfinance* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *solitairecollection* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *windowsmaps* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *zunemusic* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *getstarted* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *skypeapp* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *officehub* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *windowscommunicationsapps* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *3dbuilder* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *feedback* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *bamboo* | Remove-AppxPackage
[void](Read-Host 'Press Enter to continue…'); Get-AppxPackage *eclipse* | Remove-AppxPackage



Feel free to pretty up the "Press Enter to continue..."

Monday, February 1, 2016

Powershell - Inactive computer accounts, 90 days

A little script I wrote a while back, it will return to the screen, all computer objects that have a LastLogonTimestamp of older than 90 days.


# Calculate the UTC time 90 days ago, in FileTime (Integer) format and convert it to a string
$LLTSlimit = (Get-Date).AddDays(-90).ToFileTimeUTC().ToString()
# Create the LDAP filter for the AD query
# Searching for enabled computer accounts which have lastLogonTimestamp older than 90 days
$LDAPFilter = "(&(objectCategory=Computer)(lastlogontimestamp<=$LLTSlimit) (!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
# Create an ADSI Searcher to query AD
$Searcher = new-object DirectoryServices.DirectorySearcher([ADSI]"")
$Searcher.filter = $LDAPFilter
# Execute the query
$Accounts = $Searcher.FindAll()
# Process the results
If ($Accounts.Count –gt 0) {
# Create an array to store all the results
$Results = @()

# Loop through each account

ForEach ($Account in $Accounts) {

# Create an object to store this account in
$Result = "" | Select-Object Name,ADSPath,lastLogonTimestamp
# Add the name to the object as a string
$Result.Name = [String]$Account.Properties.name
# Add the ADSPath to the object as a string
$Result.ADSPath = [String]$Account.Properties.adspath
# Add the lastLogonTimestamp to the object as a readable date
$Result.lastLogonTimestamp = `

[DateTime]::FromFileTime([Int64]::Parse($Account.Properties.lastlogontimestamp))

# Add this object to our array

$Results = $Results + $Result
}
}

# Output the results
$Results | Format-Table -autosize
# Extending this script to disable the discovered accounts is as easy as adding this code snippet to the end:
# Disable each account
#ForEach ($Result in $Results) {
#$ADSIAccount = [ADSI]$Result.ADSPath
#$ADSIAccount.PSBase.InvokeSet("AccountDisabled", "True")
#$ADSIAccount.SetInfo()
#}

Tuesday, January 19, 2016

Powershell - Export-CSV all users in a specified OU

Today I needed this gem and had forgotten to save it last time.. so this time it's saved AND posted.


echo off
Import-Module activedirectory

$export=read-host "Please enter the export path"
$ou=read-host "Please enter the OU in ldap format (ou=employees,ou=people,dc=domain...)"
get-aduser -filter * -searchbase "$ou" -properties Displayname, Samaccountname | export-csv "$export"


Thursday, December 10, 2015

Powershell Line Continuation

In my Powershell script that I created earlier this year to create new domain user objects while also editing several attributes I ran into an issue here yesterday where I wanted to package it up as an executable for other members of IT here. Once converted using the PS2EXE script here, it'd fail to add the streetaddress, city, zip, and scriptpath attributes only.  Very, very weird.

So in ISE the script would process 100% correctly, however in a Powershell session or after converting to an EXE it'd fail.

I posted to ExpertsExchange and only really got head scratches, and a couple comments about the organization of the script.  I had a switch array before the actual $ value, which I swapped around. I had thought initially that maybe there was a limit to the number of values you could modify either in one line or in one cmdlet but that's just crazy talk.  I tried breaking the New-ADuser part up over multiple lines but then it started missing other attribute values.

So I went looking for the correct method of busting up a long cmdlet and read about Splatting.  Splatting didn't work for me.. not sure why but most likely I got the syntax wrong.  So then I found the back tick (`) line continuation.  This method actually worked.. so to show you before I had this:

New-ADUser -path $myOU -samaccountname $name -name $displayname -DisplayName $DisplayName -Surname $Surname -givenname $givenname  -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -force) -enabled:$false -emailaddress $proxyaddress  -Description $Description -Title $jobtitle -Office $office -UserPrincipalName $proxyaddress -Department $department  -Company $company -StreetAddress $Street -city $city -state $state -PostalCode $zip -ScriptPath $scriptpath

All on one gigantic line.. Now though it's this:

New-ADUser -path $myOU -samaccountname $name -name $displayname -DisplayName $DisplayName -Surname $Surname -givenname $givenname `
 -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -force) -enabled:$false -emailaddress $proxyaddress `
 -Description $Description -Title $jobtitle -Office $office -UserPrincipalName $proxyaddress -Department $department `
 -Company $company -StreetAddress $Street -city $city -state $state -PostalCode $zip -ScriptPath $scriptpath

I know it's not MUCH different here but notice the back ticks.. those are breaking it up over 4 lines.  Makes it incredibly easier to read and now my script works again.  Now I'm not saying that breaking up this cmdlet over multiple lines actually fixed the missing variables but I'm glad I had to go through it.

Thursday, October 29, 2015

Powershell - Convert date to large integer

Found this today.. converting a date into a Large integer.. used in various positions within Active Directory.



(Get-Date "01/01'2015").ToFileTime()

And that's it.  Surprisingly easy.

Wednesday, October 28, 2015

Powershell Remote Goodies (RDP Shutdown Query)

I had cause this morning to reboot a remote server that was unresponsive to RDP sessions.  The server is running Windows 2003 (yes, yes I know.. )  So new RDP session would hang at Applying settings so I looked to POSH to take care of this.

A couple things I discovered that I'd not heard of before.. Quesry session, and MSG.

First off to see what users had sessions:
Query Session /server:"servername"

It will list all current sessions whether Active or otherwise. Very nice.

Next is MSG.

The MSG command sends a message just like the old NET SEND did.  So first thing to notify the few users who had working sessions that the server was going down.

(I didnt even need to use my admin account for this)
MSG /server:"server name" *
Enter message to send; end message by pressing CTRL-Z on a new line, then ENTER.

Easy as cake.. even my RDP session that was still Applying Settings got the notice. So next step to actively tell it to reboot.

First thing I tried was
Shutdown /r /m \\servername /force

Which didn't work because I did not have the right permissions.  Next was running POSH as my admin account, when I retried the command it wanted a reason code.

Reasons on this computer:
(E = Expected U = Unexpected P = planned, C = customer defined)
Type    Major   Minor   Title

 U      0       0       Other (Unplanned)
E       0       0       Other (Unplanned)
E P     0       0       Other (Planned)
 U      0       5       Other Failure: System Unresponsive
E       1       1       Hardware: Maintenance (Unplanned)
E P     1       1       Hardware: Maintenance (Planned)
E       1       2       Hardware: Installation (Unplanned)
E P     1       2       Hardware: Installation (Planned)
  P     2       3       Operating System: Upgrade (Planned)
E       2       4       Operating System: Reconfiguration (Unplanned)
E P     2       4       Operating System: Reconfiguration (Planned)
  P     2       16      Operating System: Service pack (Planned)
        2       17      Operating System: Hot fix (Unplanned)
  P     2       17      Operating System: Hot fix (Planned)
        2       18      Operating System: Security fix (Unplanned)
  P     2       18      Operating System: Security fix (Planned)
E       4       1       Application: Maintenance (Unplanned)
E P     4       1       Application: Maintenance (Planned)
E P     4       2       Application: Installation (Planned)
E       4       5       Application: Unresponsive
E       4       6       Application: Unstable
 U      5       15      System Failure: Stop error
E       5       19      Security issue
 U      5       19      Security issue
E P     5       19      Security issue
E       5       20      Loss of network connectivity (Unplanned)
 U      6       11      Power Failure: Cord Unplugged
 U      6       12      Power Failure: Environment
  P     7       0       Legacy API shutdown

I re-ran the command but by this time the local staff had powered it off since it was not responding to a shutdown at the console either. :(

But I did learn some new things today.

Friday, October 9, 2015

Powershell Script - Change Contractor Info

Crafted this gem today.. I need to change some AD attributes for contracted personnel, namely adding a 'c-' to the beginning of their email, UPN and SAMAccountName. Adding a '(Contractor)' to the end of the DisplayName field and changing a couple proxyaddresses.


First things, the csv used has the following columns:

name, mail, displayname, samaccountname, proxyaddress_0, proxyaddress_1, proxyaddress_2

Code:

#========================================================================
# Created with: SAPIEN Technologies, Inc., PowerShell Studio 2012 v3.1.26
# Created on:   10/9/2015 1:46 PM
# Created by:   Ben Hart
# Organization: UnifiedBrands
# Filename:     Change-ContractorInfo.ps1
#========================================================================


Import-module ActiveDirectory
Import-Csv -Path d:\Users\username\Desktop\test.csv | foreach-object {


$email = $_.mail
$Displayname = $_.displayName
$UPN = $_.mail
$sam = $_.samaccountname
$proxy0 = $_.Proxyaddress_0
$proxy1 = $_.Proxyaddress_1
$proxy2 = $_.Proxyaddress_2


set-aduser -identity $sam -emailaddress $email -UserPrincipalName $email -DisplayName $Displayname



Set-ADUser -Identity $sam -Replace @{proxyaddresses=@("SMTP:"+$email)}
Set-ADUser -Identity $sam -Add @{proxyaddresses="$proxy0"}
Set-ADUser -Identity $sam -Add @{proxyaddresses="$proxy1"}
Set-ADUser -Identity $sam -Add @{proxyaddresses="$proxy2"}
Set-ADUser -identity $sam -Replace @{targetaddress="$email"}

}

Friday, October 2, 2015

PowerShell Script - Backing up ESXi Configuration

Crafted this guy today because I've been forgetting to backup our ESXi hosts configs in quite a while.

I used a small part of the PowerCLI script to load the modules for this..



# Loads additional snapins and their init scripts
function LoadSnapins(){
   $snapinList = @( "VMware.VimAutomation.Core", "VMware.VimAutomation.Vds", "VMware.VimAutomation.License", "VMware.DeployAutomation", "VMware.ImageBuilder", "VMware.VimAutomation.Cloud")

   $loaded = Get-PSSnapin -Name $snapinList -ErrorAction SilentlyContinue | % {$_.Name}
   $registered = Get-PSSnapin -Name $snapinList -Registered -ErrorAction SilentlyContinue  | % {$_.Name}
   $notLoaded = $registered | ? {$loaded -notcontains $_}
 
   foreach ($snapin in $registered) {
      if ($loaded -notcontains $snapin) {
         Add-PSSnapin $snapin
      }
   }
}
LoadSnapins




$cred = Get-Credential
connect-viserver 1.2.3.4  -credential $cred
get-vmhost | get-vmhostfirmware -backupconfiguration -destinationpath "C:\vmware_backups"

pause


Tuesday, September 1, 2015

PowerShell Script - Generate list of domain users and their Logon Script values

Yesterday I had cause to make some logon script changes.. Now we still use Batch files but in combination with PowerShell scripts and Group Policy Objects.  However a few years ago I made some test changes and discovered that I had not pushed those out to all users. *DOH*
The push currently to get everyone on the same page is DFS.  Distributed File System for those who don't know... We're preparing to make changes to some file servers and if all users are using DFS paths it'll be very easy.
Anyway below is the script I used to generate the text file with the data.

Get-AdUser -Filter * -Properties ScriptPath | ft Name, Scriptpath > C:\PathToFile\File.txt


Which resulted in A LOT of accounts that I don;t need to sift through.. ex-consultants, service accounts and the like. So I narrowed my field of search down a bit...


Get-AdUser -Searchbase "OU=blahblah,OU=blahblah,DC=Domain,DC=com" -filter * -properties ScriptPath | sort-object ScripPath | ft Name, ScriptPath > C:\PathToFile\File.txt




There you go, enjoy.





Friday, August 7, 2015

Exchange Online and Remotely Terminated Employees

So as you know my company recently (Feb) migrated to Exchange Online and one thing we did not think to ask about during that really hurried and busy time period was how to immediately sever email communications with remote employees when they are terminated.

What I've been hearing today is that our practice of firing people without having either them come into an office or an employee (likely HR) travelling to them.  Do things like collect hardware, deal with exit interviews, company property, outstanding expense reports, etc.

We actually fire people via phone calls, and hope they want their last check bad enough to ship in all the company property AND to not do anything stupid.  Well it happened yesterday.
We apparently fired a person who 8 hours later sent out some emails under his company account.


Many folks blew a virtual gasket.. then of course flooded IT with questions: How did he do that? Why was his access not cut off?, etc, etc..

Well to answer that we have a procedure that worked perfectly pre-migration that consisted of
running a powershell script that I developed two years ago that performed the following


  1. Changed the domain user password
  2. Disabled the domain account
  3. Changed the description field to term the exact time/date of termination
  4. Hid the user from the GAL
  5. And moved the user object into a Disabled Users OU
All of that took care of the issue because once the domain account was disabled any VPN session were terminated. Disabled user account and changed password meant no OWA access either.

Now, however, once all of that is done if the user keeps outlook open their session lives on for up to 10 hours.  That's how this latest guy was able to send email.

So it turns out that we have protections in place for mobile devices, however the way our local domain info syncs to the parent company which in turn syncs to Microsoft is rather convoluted IMO.

We use PCNS to sync AD credentials.. which is good except password changes are synced in almost real time.  Account changes though can take anywhere up to 6 hours. So while we can change their password, if they keep Outlook open their current session will keep working for 10 hours or so before checking to see that the password has changed in order to prompt the user to input the new password.  Or before it determine the account is disabled which then makes Outlook cough and sputter.


So how to fix this?

I/We played with settings such as disabling MAPI, OWA, Activesync via ECP but those seem to need Outlook (or the device) to be restarted before the change takes affect.. or 10 hours passes in the case of Outlook.

What we eventually determined was that changing the MaxSendSize to 0 takes roughly 10 minutes. You could change the RecieveSize too just to be safe.

This is our fix until the company decides to either bring the term into an office or send a representative to them.

Win?







Wednesday, July 15, 2015

Search-ADAccount -lockedout.. Where have you been all my life?

So yesterday I had a supervisor call me because a few of his users could not get logged in.  I went down the usual list of accounts that I know they use and non-were locked out.  I tell him to get find out what username the problem folks are using and to let me know.  So he hangs up and while Im sitting there I decide to google it.

Search-ADAccount - locked out

Is what I found.. OMG! Where has this command been for the past few years? So easy.. So short.. So easy to remember.

Thursday, July 9, 2015

PowerShell: Export-CSV with specific user info

Today I had need to export a bunch of info about our users for some sort of internal survey sending situation.


Get-ADUser -Filter * -SearchBase "OU=Employees,DC=Domain,DC=Com" -Properties DisplayName, EmailAddress, Department, Manager | Select DisplayName, EmailAddress, Department, Manager | Export-CSV "D:\path"

Monday, June 8, 2015

Powershell - Change computer object description to username

Two years ago, with help from ExpertsExchange, I had created a VisualBasic script to collect the currently logged on users username, and set the computers description to that username in AD.

To us it's purpose was to help associate the computers to the actual user, since computers change hands, get re purposed and you don't always remember to change the description.

So here's the old script:

On Error Resume Next
strComputer = "."

Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery("Select Description FROM Win32_OperatingSystem")
For Each object In objRegistry
strDescription = object.Description 
Next 


Set objSysInfo = CreateObject("ADSystemInfo")
Set objComputer = GetObject("LDAP://" & objSysInfo.ComputerName)
objComputer.Description = strDescription
objComputer.SetInfo

And the new Powershell version:

Import-Module ActiveDirectory
$computer = $env:computername
$username = $env:USERNAME
set-adcomputer $computer -description $username


Shocking, no?  Another reason I :heart: Powershell.


UPDATE:

Well this script has failed me.  Well not the script mind you but I ran into an issue in it's utilization here that will not work.  Our images of Win7Ent do not contain the RSAT tools for obvious reasons.. but that means that my attempt to call this via a GPO logon script failed because running this script locally on a machine that does not have the module means import-module ActiveDirectory fails.

The fix for our scenario was to fall back to the visual basic script above.  It's still called from a GPO though, after giving Authenticated Users write permission to computer-Description.


Wednesday, June 3, 2015

Powershell - Script generates CSV with computer names and bitlocker recovery key and TPM-OwnerInformation

So here at work we're in the process of Bitlocking 'important' users laptops and to help keep track and poll AD I went looking for a powershell script to accomplish this.  I found a script here: https://gallery.technet.microsoft.com/ScriptCenter/4231a8a1-cc60-4e07-a098-2844353186ad/

Props to Jan Egil Ring, his relevant blog post is http://blog.powershell.no/2010/10/24/export-bitlocker-information-using-windows-powershell/ for creating the first iteration using  Quests Powershell addons back in 2010.

I don;t use the QAD tools anymore so I went to work on configuring the script to run natively.


So this script generates a CSV with all computer objects with Windows 7 or 8, pulls the msTPM-OwnerInformation and msFVE-RecoveryInformation and marks the columns for the recovery key and TPM owner as either True or False.

Anyway here's the meat:



# NAME: Get-BitlockerEnabledComputer.ps1 



# EDITTED BY: Benjamin Hart
# EMAIL: Invalid.path@gmail.com

# COMMENT: Script to retrieve BitLocker-information for all computer objects with Windows 7 or Windows Vista in the current domain. 

#          The information will be exported to a CSV-file containing the following information: 
#          -Computername 
#          -OperatingSystem 
#          -HasBitlockerRecoveryKey 
#          -HasTPM-OwnerInformation 
#           
#          Required version: Windows PowerShell 1.0 or 2.0 
#          Requried privileges: Read-permission on msFVE-RecoveryInformation objects and Read-permissions on msTPM-OwnerInformation on computer-objects (e.g. Domain Admins) 
#     
#  





import-module activedirectory 

#Custom variables
$CsvFilePath = "path_to_csv" 

set-location AD:
$bitlockerenabled = Get-ADObject -LDAPFilter '(objectclass=msFVE-recoveryInformation)' -Properties cn,distinguishedname | ForEach `
{
    ((($_ | Select -ExpandProperty DistinguishedName) -split ",?CN=")[2] -split ",")[0]
}

$computers = Get-ADComputer -filter * -Properties cn,OperatingSystem,msTPM-OwnerInformation | Where-Object {$_.operatingsystem -like "Windows 7*" -or $_.operatingsystem -like 
"Windows 8*"} | Sort-Object msTPM-OwnerInformation

#Create array to hold computer information 
$export = @() 

read-host "Created array"

foreach ($computer in $computers) 
  { 
    #Create custom object for each computer 
    $computerobj = New-Object -TypeName psobject 
    
     
    #Add name and operatingsystem to custom object 
    $computerobj | Add-Member -MemberType NoteProperty -Name DistinguishedName -Value $computer.Name 
    $computerobj | Add-Member -MemberType NoteProperty -Name OperatingSystem -Value $computer.operatingsystem 
     
    #Set HasBitlockerRecoveryKey to true or false, based on matching against the computer-collection with BitLocker recovery information 
    if ($computer.cn -match ('(' + [string]::Join(')|(', $bitlockerenabled) + ')')) { 
    $computerobj | Add-Member -MemberType NoteProperty -Name HasBitlockerRecoveryKey -Value $true 
    } 
    else 
    { 
    $computerobj | Add-Member -MemberType NoteProperty -Name HasBitlockerRecoveryKey -Value $false 
    } 
    
     
    #Set HasTPM-OwnerInformation to true or false, based on the msTPM-OwnerInformation on the computer object 
     if ($computer."msTPM-OwnerInformation") { 
    $computerobj | Add-Member -MemberType NoteProperty -Name HasTPM-OwnerInformation -Value $true 
    } 
    else 
    { 
    $computerobj | Add-Member -MemberType NoteProperty -Name HasTPM-OwnerInformation -Value $false 
    } 
   #  $computerobj | add-member -membertype noteproperty -name recoveryguid -value $object.recoveryguid
   #$computerobj | add-member -membertype noteproperty -name When-Created -value $computer.whencreated
#Add the computer object to the array with computer information 
$export += $computerobj 

  } 

#Export the array with computerinformation to the user-specified path 
$export | Export-Csv -Path $CsvFilePath -NoTypeInformation | sort hastpm-ownerinformation -descending
read-host "Exported csv"

Thursday, May 21, 2015

PowerShell - Searching AD for locked out domain accounts

So yeah.. should be a no-brainer to most however with the changed cmdlets in Powershell 4 I had to look it up.  This is one of those little things that you probably don't need very often but when you do it's a life saver.

Import-Module activedirectory
Search-ADaccount - Lockedout


That's it.  Easy right?

Wednesday, May 6, 2015

Carbon - powershell module

I got an email this morning from Powershell.com letting me know about a new and recommended module named Carbon.

I have only been playing with it for a short time but so far I'm interested.  they've added quite a few new and handy cmdlets.  And if the folks at Powershell.com recommend it it automatically has my support.

Check it out. Oh and sign up for Powershell.com's PowerTips, I've been getting them every few days for months now.  A number of them have proven very useful.

Monday, April 6, 2015

Powershell: Modifying ADGroup membership

Here's a script I made today that is destined for users who manage certain AD distribution groups for their own departments and the like.





function list_groups
    {
    Get-ADGroup -Filter "managedby -eq '$($user.DistinguishedName)'" |fl samaccountname
    }
function add_member
    {
    $newuser = read-host = "Enter username to add"
    $group = read-host = "Enter the group name you wish to modify as they are named above"
   add-adgroupmember -identity $group -members $newuser
   get-adgroupmember -identity $group |fl name
    }
function remove_member
    {
    $olduser = read-host = "Enter the username you wish to remove"
    $group1 = read-host = "Enter the group name as they are named above"
   remove-adgroupmember -identity $group1 -members $olduser -confirm:$false
   get-adgroupmember -identity $group1 |fl name
    }

$username = Read-host "Enter your username"
$user = Get-ADUser $username

[int]$xMenuChoiceA = 0
do {

Write-host "1. List groups I manage"  -fore Cyan
Write-host "2. Add members to a group" -fore Cyan
Write-host "3. Delete members from a group" -fore Cyan
Write-host "4. Quit and exit" -fore Cyan

$xMenuChoiceA = read-host "Please enter an option 1 to 4"

Switch( $xMenuChoiceA ){
  1
    {
    list_groups
    }
  2
    {
    add_member
    }
 
  3
    {
    remove_member
    }
default
    {
    write-host "Valid responses are 1,2,3,4"
    }
    }
}while  ( $xMenuChoiceA -le 3 )

Connecting to Powershell in Office 365

Here's a little script I've got for connecting to a Powershell session in MSOnline or Office365.




Import-Module MSOnline
# Imports the O365 Commandlets

$CloudCredential=Get-Credential -Credential "username"
# Saves your User name and password

$CloudSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Credential $CloudCredential -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue

Import-PSSession $CloudSession -Prefix 365
# Sets the O365 Commands to start with 365

Connect-MsolService -Credential $CloudCredential
# Connects to O365 services