Remove-ADComputer : Access is denied powershell - powershell

Long time lurker but I finally found a problem that I could not find an answer for so I decided it was time to join. Im trying to collect a list of computers in AD that are older than X days ($DelCompDays). Then based off of the DistinguishedName field delete that computer using the Identity flag. Problem is even with domain admin creds I am getting: Remove-ADComputer : Access is denied
Even if I run Remove-ADComputer -Identity "Full CN or Short name" I get an access denied. Anyone have any ideas? Thank you in advance!
#Get AD computers older than $DelCompDays
$results = Search-ADAccount -ComputersOnly -AccountInactive -TimeSpan "$DelCompDays.00:00:00"
#Loop and try to delete
foreach ($result in $results){
if ($result -ne $NULL){
try {
Remove-ADComputer -Identity $result.DistinguishedName -confirm:$false
$Success = "Deleted: $result.DistinguishedName"
WriteCustomOutput -message "$Success" -foregroundcolor green -backgroundcolor DarkMagenta
}
catch {
$Error = "Failed to delete: $result.DistinguishedName"
WriteCustomOutput -message "$Error" -foregroundcolor Red -backgroundcolor Black
}
}
else{
$Warning = "No computers older than $ArcDays days to delete"
WriteCustomOutput -message "$Warning" -foregroundcolor yellow -backgroundcolor DarkMagenta
}
}

Figured it out. When running non-interactive you need to specify the creds in the command call.
$secpasswd = ConvertTo-SecureString "ClearTextPass" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("Username", $secpasswd)
Remove-ADComputer -Identity $result.DistinguishedName -Recursive -confirm:$false -credential $creds

Related

Powershell Delete Computer Object

Can some one help me on the next code im trying to run..
it seem's to be ok for me but does not delete the Object when i execute-it
Import-Module ActiveDirectory
Clear-Host
$Computer = Read-Host "Type in the Host to Delete"
$rute = Get-ADComputer -Identity:"CN=$Computadora,OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com" -Server:"DCKABI02.kabi.ads.fresenius.com"
if($rute.Contains($Computer)){
Clear-Host
Remove-ADComputer -Identity=$Computadora,OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com" -Server:"DCKABI02.kabi.ads.fresenius.com" -Confirm:$false
#Clear-Host
Write-Host "The Computer Exist and it has been deleted" -ForegroundColor Green
Start-Sleep -Seconds 5
} else{
Clear-Host
Write-Host "The Host does not exist on AD" -ForegroundColor Red
Start-Sleep -Seconds 3
}
try to delete a Active directory object.. expected to work
Your code is not very clear and seems overengineered, $rute.Contains($Computer) will never ever be $true, you probably meant $rute.DistinguishedName.Contains($Computer) which could be $true but .Contains is case-sensitive so it could also be $false.
Your Read-Host statement is assigned to $Computer but then you're using $Computadora. Also, it's unclear why you are hardcoding OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com, I would assume you want to use this OU as your -SearchBase.
Here is how you can approach and will most likely work:
$param = #{
SearchBase = "OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com"
LDAPFilter = "(name={0})" -f (Read-Host "Type in the Host to Delete")
Server = "DCKABI02.kabi.ads.fresenius.com"
}
$computer = Get-ADComputer #param
if($computer) {
Clear-Host
$computer | Remove-ADComputer -Server "DCKABI02.kabi.ads.fresenius.com" -Confirm:$false
Write-Host "The Computer Exist and it has been deleted" -ForegroundColor Green
Start-Sleep -Seconds 5
}
else {
Clear-Host
Write-Host "The Host does not exist on AD" -ForegroundColor Red
Start-Sleep -Seconds 3
}

Get-SPOSite find existing sites

This is the code that will check if any of the sites listed already exists.
$sites = get-content -Path C:\code\CheckSPSites.txt
foreach($site in $sites){
$url = (Get-SPOSite -Filter{url -like $site} -ErrorAction SilentlyContinue) -ne $null
if ($url -eq $true){
Write-Host "$site already created" -BackgroundColor Red
}else{
Write-Host "$site not created" -BackgroundColor Green
}
}
It doesn't find the sites when I use the variable $site to filter the search.
I've tried putting the variable in quotes (Get-SPOSite -Filter{url -like "$site") and it doesn't work either.
Any help would be appreciated.
Many thanks
Thank you Theo and UBK. Posting your suggestion as an answer to help other community members.
You can use -Identity parameter along with the site collection URL to find out the existence.
For example: Get-SPOSite -Identity https://contoso.sharepoint.com
# Verify if site of same name already exists in SharePoint Online
$siteAlreadyExists = Get-SPOSite -Identity $url
# If it does, stop the script
if ($null -ne $siteAlreadyExists) {
Write-Host "Site already exists" -ForegroundColor Red
...
}
If your code fails when site is not present, then you can try following try-catch block:
try {
$siteAlreadyExists = Get-SPOSite -Identity $url
if ($null -ne $siteAlreadyExists) {
Write-Host "Site already exists" -ForegroundColor Red
}
}
catch {
Write-Host "Site already exists" -ForegroundColor Red
}
You can refer to Number of SPO sites causing issue with Get-SPOSite

Remove Disabled users in a CVS file from all Office 365 Groups that appear on the admin portal

I am Trying to Remove all users who are in a csv file from all the groups they are showing up under in the Office 365 admin portal, The code bellow doesn't seem to delete all the groups and still has some left under their name. Is there something I am missing?
Write-Host "Fetching the CSV..."
$file = "X:\1Onboarding.TerminationCSV\DisabledUsers.csv"
Write-Host "Importing from $file..."
$csv = Import-Csv $file
if ($csv -eq $null)
{ Write-Host "No CSV file found. exiting script in 3 seconds"
#Start-Sleep -Seconds 3
Exit }
#Credentials
$password = ConvertTo-SecureString “*Hidden*” -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential (“*hidden*”, $password)
#Connect to AzureAD
Connect-AzureAD -Credential $Cred
#Get all Azure AD Unified Groups
$AADGroups = Get-AzureADMSGroup -All:$true
foreach ($member in $csv) #loop through csv for users--------------------
{
$username= $member.username
Write-Output "username is $username"
#Get the Azure AD User
$AADUser = Get-ADUser -filter {sAMAccountName -eq $username}
$groupCount = 0
ForEach ($Group in $AADGroups)
{
$GroupMembers = (Get-AzureADGroupMember -ObjectId $Group.id).UserPrincipalName
If ($GroupMembers -contains $UserUPN)
{
Write-Output "$username is in $($Group.DisplayName)"
#Remove user from Group
try { Remove-AzureADGroupMember -ObjectId $Group.Id -MemberId $AADUser.ObjectId }
catch { "$($Group.DisplayName) is not an azure group" }
try {Remove-DistributionGroupMember -Identity $Group.Id -Member $AADUser.ObjectId -BypassSecurityGroupManagerCheck -Confirm:$false }
catch { "$($Group.DisplayName) is not a distribution group" }
$groupCount +=1
}
}
Write-Output "$AADUser is in $groupCount groups"
}
See, this should be more efficient than bringing all existing Azure AD Groups.
First, search for the user provided in the CSV on Azure AD
If the user exist, get it's membership. Else, write a warning
Loop over the AADuser's membership removing it from all of them
$ErrorActionPreference = 'Stop'
#Connect to AzureAD
Connect-AzureAD -Credential $Cred
foreach ($member in $csv) #loop through csv for users
{
$AADUser = Get-AzureADUser -SearchString $member.userName
if($AADUser)
{
$membership = Get-AzureADUserMembership -ObjectId $AADUser.ObjectID
foreach($group in $membership)
{
try
{
Remove-AzureADGroupMember -ObjectId $group.ObjectID -MemberId $AADUser.ObjectID
Write-Output "Successfully removed {0} from {1}" -f $AADUser.userPrincipalName,$group.displayName
}
catch
{
Write-Warning "Failed to remove {0} from {1} with the following error:`n$_" -f $AADUser.userPrincipalName,$group.DisplayName
}
}
}
else
{
Write-Warning "{0} could not be found on Azure AD" -f $member.userName
}
}

script tuning for include all computers in domain

I have a script which scans given computers in domain for identifying and disables mobile hotspot function in windows 10. Script works properly , but i want to scan all my domain comupters, not only specified.. can anyone help me for adjusting this script?
$username = "domain\administrator"
$password = "Your password"
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $password
$computers = #("nr1", "nr2", "nr3")
foreach($computer in $computers){
$hotspot = Invoke-Command -ComputerName $computer -credential $credential -scriptblock {
$hotspot = Get-Service "icssvc"
if($hotspot.Status -eq "Running"){
Write-Host "Hotspot is turned on on $computer" -ForegroundColor Red
try{
Stop-Service "icssvc"
Write-Host "Successfully stopped service on $computer" -ForegroundColor Green
}catch{
Write-Host "Unable to stop service on $computer" -ForegroundColor Red
}
}else{
Write-Host "No Hotspot running on $computer" -ForegroundColor Green
}
}
If you replace $computers = #("nr1", "nr2", "nr3") with something like:
Import-Module ActiveDirectory
$computers = Get-ADComputer -Properties DNSHostName
That should return an array of hostnames. You may need to provide credentials via -Credential, and you can -Filter the results if you need to exclude any machines.
See docs and examples of Get-ADComputer here.

PowerShell Script Runs Locally, but Errors on Remote

I have a PowerShell script I am writing to create new users in our domain, as well as email address. The script works when I run it directly on Exchange. However, if I try to do it from my local PC either with Enter-PSSession or Invoke-Command I get the error:
The term 'Get-ADUser' is not recognized as the name of a cmdlet...
Running that same command from the local machine does work. And running that command on the remote machine works, just not if I run the script remotely.
Here is my script:
$cred = Get-Credential
$first_name = Read-Host -Prompt "What is the new user's first name?"
$last_name = Read-Host -Prompt "What is the new user's last name?"
$copy_from = Read-Host -Prompt "Copy from other user (leave blank if not)?"
$password = Read-Host -Prompt "New user's password?"
$ss_password = ConvertTo-SecureString -String $password -AsPlainText -Force
$new_user_name = $last_name.Substring(0,3) + $first_name.Substring(0,2)
$new_user_name = $new_user_name.ToLower()
Write-Host "Creating user $new_user_name..." -ForegroundColor Green
if ([string]::IsNullOrEmpty($copy_from))
{
Write-Host "Setting up new user (not copying...)" -ForegroundColor Yellow
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -SamAccountName $new_user_name -PassThru | Enable-ADAccount
}
else
{
$copy_from_user = Get-ADUser -Identity $copy_from
Write-Host "Copying user from: " $copy_from_user.Name -ForegroundColor Yellow
$ou = $copy_from_user.DistinguishedName -replace '^cn=.+?(?<!\\),'
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -Path $ou -SamAccountName $new_user_name -PassThru | Enable-ADAccount
$new_user = Get-ADUser -Identity $new_user_name
#Time to copy their group memberships
Get-ADUser -Identity $copy_from -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $new_user_name
}
$pn = $new_user_name + "#INDY"
Set-ADUser -Identity $new_user_name -GivenName $first_name -Surname $last_name -UserPrincipalName $pn
#Now create email
$email_select = Read-Host -Prompt "Select email domain (1. Woodmizer; 2. Lastec; 3. Brightstone)"
if ($email_select -eq 2)
{
$domain = "#lastec.com"
}
elseif ($email_select -eq 3)
{
$domain = "#brightstoneabrasives.com"
}
else
{
$domain = "#woodmizer.com"
}
$email_address1 = $first_name.Substring(0,1) + $last_name + $domain
Write-Host "Creating mailbox $email_address1..." -ForegroundColor Green
Enable-Mailbox -Identity $new_user_name -Database "Mailbox Database 1188513962"
Start-Sleep -s 10
Get-Mailbox -Identity $new_user_name | Set-Mailbox -EmailAddresses #{add="$email_address1"} -EMailAddressPolicyEnabled $false
Get-Mailbox -Identity $new_user_name | Set-Mailbox -PrimarySmtpAddress $email_address1 -EmailAddressPolicyEnabled $false
Write-Host "Finished." -ForegroundColor Green
If you want this script to run on machines that don't have the Active Directory module, you can simply add this to the top of your script to import the cmdlets via session..
$cred = Get-Credential "DOMAIN\adminuser"
$ADsession = New-PSSession -ComputerName DOMAINCONTROLLERNAME -Credential $cred
Import-Module -PSSession $ADsession ActiveDirectory
I also notice you're trying to run Exchange cmdlets..
$exchSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://EXCHANGESERVER/PowerShell/" -Authentication Kerberos
Import-PSSession $exchSession
It looks like the ActiveDirectory module is not installed on that machine, you can install the MSFT RSAT tools to get it.
Try the following, It works!! {I tried after giving the Authentication type}
$pass = ConvertTo-SecureString -AsPlainText 'PASSWORD' -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'USERNAME',$pass
$s=New-PSSession SERVERNAME -Credential $MySecureCreds -Authentication Credssp
Invoke-Command -Session $s -scriptblock {
Get-CsUser User
}