Coping AD member groups for Computers - Poweshell - powershell

Trying to create a script that Copies groups from 1 Computer to another. The script also has a list of Groups that won't copy over. I have been able to debug the script until line 42 with the below error message.
Here is my current script:
*If($Hostname -eq 'ISD-TS-01' -or 'ISD-TS-03' -or 'ISD-TS-04')
{
function Show-Menu
{
param (
[String]$Title = 'Copy AD Computer Groups Groups'
)
cls
Write-Host ================ $Title ================
$ComputerToCopy = Read-Host -Prompt 'Input the Computer to copy'
$Computer = $ComputerToCopy
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive Select -ExpandProperty SamAccountName
If ($members -contains $Computer) {
Write-Host "$Computer is in $group" -ForegroundColor Red
Pause
Exit
} Else {
Write-Host Starting Script -ForegroundColor Green
}
}
$NewComputer = Read-Host -Prompt 'Input the name of the new computer'
Get-ADComputer -Identity $ComputerToCopy -Properties memberof -Verbose | Select-Object -ExpandProperty memberof -Verbose |
Add-ADGroupMember -Members $NewComputer -PassThru -Verbose
$Computer = $NewComputer
$groups = 'G-SCCM-SD-EGRESS_WIN10'
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
If ($members -contains $Computer) {
#remove-adgroupmember -Identity "$Group" -Member "$NewComputer" -Confirm:$false
Write-Host "$Computer has been removed from $group" -ForegroundColor Cyan
} Else {
Write-Host "$Computer is not a member of $group" -ForegroundColor Green
}
}
Write-Host "1: Press '1' to Retry."
Write-Host "Q: Press 'Q' to quit."
}
do
{
show-menu
$input = Read-Host "Select an option"
Switch ($input)
{
'1' {
cls
'You chose option #1'
}'2'{
cls
'You chose option #2'
}'q'{
return
}
}
pause
}
until ($input -eq 'q')
}
Else {
Write-Host "Script Cannot be Run on this Host. Please use TS-01"
Read-Host
}*
Powershell Error

You have to use the SamAccountName of the station! the SamAccountName is the computer name with $ at the end
you can use this in your script to find it
Get-ADComputer -Identity $NewComputer | Select-Object -ExpandProperty SamAccountName

Related

POWERSHELL - Display Users AD Group That Starts With a Specific Character

This is my script it can display all the AD group that is assigned to a user account. I just don't know the syntax on how to do a wildcard search.
Write-Host "'Get AD Groups"
$userName = Read-Host -Prompt "Please enter the LDAP ID"
$ADUser = Get-ADUser -Filter "SamAccountName -eq '$userName'" | Select-Object SamAccountName
if($ADUser -eq $null) {
Write-Host "$userName does not exist in AD or account is inactive" -ForegroundColor Red
Continue
} else {
$sourceUser = Get-ADUser -Identity $userName -Properties MemberOf
$sourceGroups = $sourceUser.MemberOf
Foreach($group in $sourceGroups) {
$thisgroup = $group.split(",")[0].split("=")[1]
Write-Host "$thisgroup"
}
}

Powershell Catch Error: Unable to find a default server with Active Directory Web Services running

Need help to catch the error. Whenever my network connection is unstable my get-ad script will be terminated.
$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$Date = Get-Date -Format yyyy_MM_dd_THHmm
Start-Transcript -Path "$ScriptDir\Logs.log" -Append
$List = Import-Csv "$ScriptDir\Accounts.csv"
$TotalCount = $List.Length
$CurrentCount = 0
Write-Host 'Total Count: '$TotalCount
ForEach ($user in $List) {
# Retrieve UserSamAccountName and ADGroup
$Groups = $User.Group
$UserSam = $User.SamAccountName
# Retrieve SamAccountName and ADGroup
$ADUser = Get-ADUser -Filter "SamAccountName -eq '$UserSam'" | Select-Object SamAccountName
$ADGroups = Get-ADGroup -Filter * | Select-Object Name
# User does not exist in AD
if ($ADUser -eq $null) {
Write-Host "$UserSam does not exist in AD" -ForegroundColor DarkCyan
Continue
}
# User does not have a group specified in CSV file
if ($Groups -eq $null) {
Write-Host "$UserSam has no group specified in CSV file" -ForegroundColor Yellow
Continue
}
# Retrieve AD user group membership
$ExistingGroups = Get-ADPrincipalGroupMembership $UserSam | Select-Object Name
foreach ($Group in $Groups.Split(';')) {
# Group does not exist in AD
if ($ADGroups.Name -notcontains $Group) {
Write-Host "$Group group does not exist in AD" -ForegroundColor Gray
Continue
}
# User already member of group
if ($ExistingGroups.Name -eq $Group) {
Write-Host "$UserSam already exists in group $Group." -ForeGroundColor Yellow
}
else {
# User not a member of group
Write-Host "User $UserSam doesn't exists in $Group AD group" -ForegroundColor Red
}
}
$CurrentCount++
$Percentage = [math]::Round($CurrentCount/$TotalCount*100)
Write-Progress -Activity "Building report in progress" -Status "$Percentage% Complete" -PercentComplete $Percentage
}
Stop-Transcript
Write-Output 'Script complete.'
OUTPUT ERROR
Get-ADUser : Unable to find a default server with Active Directory Web Services running.
At C:\Users\JVERE05\Desktop\Powershell\Powershell\CheckIfExist\08_08.ps1:22 char:11
+ $ADUser = Get-ADUser -Filter "SamAccountName -eq '$UserSam'" | Select ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (:) [Get-ADUser], ADServerDownException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1355,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The fully qualified type name is Microsoft.ActiveDirectory.Management.ADServerDownException:
try {
Get-ADUser ... -ErrorAction Stop
}
catch [Microsoft.ActiveDirectory.Management.ADServerDownException] {
<# AD Server is down #>
}
catch {
<# Something else went wrong #>
}

PowerShell script doesnt return data the first run through

I have created a PowerShell script to find the computer name from the values in the description. We put the users name in the description and computer name is an asset tag number. If you continue and put the name in a second time it works. If you look for another user you have to do it twice also.
Here is my script:
Import-Module ActiveDirectory
do {
$a = Read-Host "Enter first or last name of user"
$b = "*$a*"
# Validates if the command returns data
$searcher = $(try {
Get-ADComputer -Filter {Description -like $b} -Properties
Name,Description | Select Name,Description
} catch {
$null
})
if ($searcher -ne $null) {
Get-ADComputer -Filter {Description -like $b } -Properties Name,Description |
Select Name,Description
} else {
Write-Host Could not find: $a -ForegroundColor "yellow"
}
# If running in the console, wait for input before closing.
if ($Host.Name -eq "ConsoleHost") {
Write-Host "Press any key to continue..."
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
$again = Read-Host 'Would you like to search again? (Y/N)'
} until ($again -eq 'No' -or $again -eq 'n')
Here is a working example using your script with a few changes.
The big change that allowed it to work was piping to Out-Host from using Get-ADComputer
# installs AD module
Import-Module ActiveDirectory
Do {
$a = Read-Host "Enter first or last name of user"
$b = "*$a*"
try {
Get-ADComputer -Filter {Description -like $b} -Properties Name, Description -ErrorVariable MyError |
Select-Object Name,Description |
Out-Host
if ($MyError){
write-host Could not find: $a -foregroundcolor Yellow
}
}
catch {
write-host Could not find: $a -foregroundcolor Red
}
$again = Read-host 'Would you like to search again? (Y/N)'
}
Until (
$again -eq 'No' -or $again -eq 'n'
)

How to check if AD user has direct reports

I am trying to write a PowerShell script to check if an AD-User has direct reports (meaning, if that AD-User is a manager), with following code but no go, Any help?
Import-Module ActiveDirectory
Set-Location AD:
$SamAccountName = "Mansings"
$test = Get-Aduser -identity $SamAccountName -Properties directreports | %{$_.directreports}
Write-Host $test
if ($test -eq $null)
{
Write-Host "He is a Manager"
}
else
{
Write-Host "He is not a manager"
}
Got the working script now
Import-Module ActiveDirectory
Set-Location AD:
$SamAccountName = "Mansings"
$test = Get-Aduser -identity $SamAccountName -Properties directreports | %{$_.directreports}
Write-Host $test
if (!$test)
{
Write-Host "He is an employee"
}
else
{
Write-Host "He is a Lead"
}
it's working. Thank you.

Powershell script to list users who are not part of two groups

There are two groups in our environment 'contractors' and 'employees' , I need to write a script that lists all users who are not part of both the groups, can some one help me with it.
$n = Get-ADGroupMember "Contractor" | Sort-Object |
foreach {Get-ADUser $_.name | select name}
$group = "Employee"
foreach ($u in $n) {
$get = (Get-ADUser $u.Name -Properties * | Select-Object memberof)
if ($get.memberof -match $group) {
Write-Host $u.name " is ok. They're in both groups."
} else {
Write-Host $u.Name " is not a member" -ForegroundColor Red -BackgroundColor Yellow
}
}
$AllUsers = Get-ADUser -Filter * -Properties memberof
foreach ($User in $AllUsers) {
if (($User.memberof -match "Employee") -and ($User.memberof -match "Contractor")) {
Write-Host -ForegroundColor Green "$($User.samaccountname) in both groups"
} else {
Write-Host -ForegroundColor Red "$($User.samaccountname) not in both groups"
}
}
I corrected your script, try this:
$n = get-adgroupmember "Contractor" | sort-object |foreach {get-aduser $_.SamAccountName}
$group = "Employee"
Foreach ($u in $n){
$get = (get-aduser $u.SamAccountName -Properties * | Select-Object memberof)
if ($get.memberof -match $group) {
Write-Host "$($u.name) is ok. They're in both groups." }
Else { write-host $($u.name) " is not a member" -ForegroundColor Red -BackgroundColor Yellow
}
}