How to discard errors of PowerShell ActiveDirectory cmdlets? - powershell

I am writing a PowerShell script (in a PowerShell 5.1 environnement) and I need to list all users from groups set in a folder's permissions. But some groups are not relevant so when I try to Get-ADGroupMember on it, I've got an expected error.
To discard this error, I tried the following :
Get-ADGroupMember Fake_Group -Server ad.example.com 2>&1 $null
Get-ADGroupMember Fake_Group -Server ad.example.com 2>&1 | Out-Null
But in both cases, the result is the same : error is displayed.
get-aduser : Cannot find an object with identity: 'Fake_Group' under 'DC=example.com'.
At line:1 char:1
+ Get-ADGroupMember Fake_Group -Server ad.example.com 2>&1 | ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Fake_Group:ADGroup) [Get-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
So my question is : why is this error still displayed ?
And then, how could I discard this error or is there a better way to list users from groups set in a folder's permissions than just try to Get-ADGroupMember on the whole result of Get-Acl even on no relevant object ?

Because Out-Null does nothing in this regard, you would need to use try/catch statements and might even need to add -ErrorAction Stop as not all errors in AD commands are terminating errors:
Try{
Get-ADGroupMember $GROUPNAME -Server $SEVRER -ErrorAction Stop
#The group is found, do whatever you want here
}Catch{
Write-Host "Some error occured"
}

Related

Issue for import-csv and foreach

I want to import a csv, then delete from AD several objects
$ImportComputer = "C:\Users\deng\Desktop\ComputerLastlogondateformatBis.csv"
Import-Module ActiveDirectory
foreach ($Computer in(Import-Csv -Path C:\Users\deng\Desktop\ComputerLastlogondateformatBis.csv))
{
Remove-ADObject -Identity $Computer.'Computer'
these two object exist in AD, but I cannot seem to find out why it is not working.
see below error message:
Remove-ADObject : Cannot find an object with identity: 'fr-borr-mac' under: 'DC=PII,DC=net'.
At C:\Users\deng\OneDrive - Aptus Health\Script\Export.ps1:7 char:1
+ Remove-ADObject -Identity $Computer.'Computer'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (fr-borr-mac:ADObject) [Remove-ADObject], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.RemoveADObject
Remove-ADObject : Cannot find an object with identity: 'jlinmacfr' under: 'DC=PII,DC=net'.
At C:\Users\deng\OneDrive - Aptus Health\Script\Export.ps1:7 char:1
+ Remove-ADObject -Identity $Computer.'Computer'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Content of the CSV below:
Computer
--------
fr-borr-mac
jlinmacfr
Could anyone give input on this?
The -Identity parameter on the *-ADObject commands expect either a DistinguishedName or Guid value. If you are wanting to work with SamAccountName or some other attribute, you should consider using the *-ADComputer or using -Filter to find your objects.
# Using Remove-ADObject
Remove-ADObject -Filter "SamAccountName -eq '$($Computer.Computer)'"
# Using Remove-ADComputer
Remove-ADComputer -Identity $Computer.Computer
Alternatively, you can use Get-ADComputer or Get-ADObject to retrieve your object first and then pipe that into Remove-ADObject.
Get-ADObject -Filter "SamAccountName -eq '$($Computer.Computer)'" | Remove-ADObject
See the Remove-ADObject documentation for the following excerpt regarding explicitly binding to -Identity:
Specifies an Active Directory object by providing one of the following
property values. The identifier in parentheses is the Lightweight
Directory Access Protocol (LDAP) display name for the attribute. The
acceptable values for this parameter are:
A distinguished name
A GUID (objectGUID)
For piping an object into Remove-ADObject, the following excerpt applies, which is why you can use a Get-AD* command and pipe the result into the Remove-ADObject:
This parameter can also get this object through the pipeline or you
can set this parameter to an object instance.
Derived types, such as the following, are also accepted:
Microsoft.ActiveDirectory.Management.ADGroup
Microsoft.ActiveDirectory.Management.ADUser
Microsoft.ActiveDirectory.Management.ADComputer
Microsoft.ActiveDirectory.Management.ADServiceAccount
Microsoft.ActiveDirectory.Management.ADFineGrainedPasswordPolicy
Microsoft.ActiveDirectory.Management.ADDomain

PowerShell remote event log parsing

I wrote a small script to grab event log entries from a remote machine and write it to a .csv file. The script works when targeting a single machine, but when I try to implement a for loop and loop it over all machines in Active Directory, I get this error:
Method invocation failed because [Microsoft.ActiveDirectory.Management.ADComputer]
does not contain a method named 'op_Addition'.
At Y:\srp.ps1:7 char:143
+ ... | Export-Csv $($computer + ".csv")
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Export-Csv : Cannot validate argument on parameter 'Path'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At Y:\srp.ps1:7 char:141
+ ... 0 | Export-Csv $($computer + ".csv")
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Export-Csv],
ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,
Microsoft.PowerShell.Commands.ExportCsvCommand
The error indicates there's a problem with the Export-Csv command, but running the command by itself creates the log files needed. Here is the full script, for reference:
# Gets SRP event log entries from remote machine and writes them to a .csv file
# of the same name.
Write-Output "Running..."
$computers = Get-ADComputer -filter {(Name -like "PC*") -or (Name -like "LT*")}
foreach ($computer in $computers) {
Get-EventLog -LogName Application -Source Microsoft-Windows-SoftwareRestrictionPolicies
-ComputerName $computer -Newest 10 | Export-Csv $($computer + ".csv")
} #end foreach
Write-Host "Done."
Any ideas as to why this error appears when I try to loop over computers in AD?
It looks like Get-ADComputer returns ADComputer objects, but you're passing it to Get-EventLog's ComputerName parameter, which takes a string, as-is. I'm assuming you'll need to grab the name property from the Microsoft.ActiveDirectory.Management.ADComputer object.

How to return the users in a domain local group in Powershell

When I run the following command on a domain local group:
Get-ADGroupMember "Name of Group"
I get the following output:
Get-ADGroupMember : The operation completed successfully
At line:1 char:1
+ Get-ADGroupMember "Name of Group"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Name of Group:ADGroup) [Get-ADGroupMember], ADException
+ FullyQualifiedErrorId : The operation completed successfully,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMember
When I run the command on a global group, I get the output of the users in the group. Is there a way to get the users from a domain local group?
If this doesn't work:
Get-ADGroup "Name of Group" | Get-ADGroupMember
Try the following:
$s = "LDAP://" + (Get-ADGroup "Name of Group").DistinguishedName
([ADSI]$s).member
if you want to export the users from a domain local group use this code:
$s = "LDAP://" + (Get-ADGroup "Name of Group").DistinguishedName
([ADSI]$s) | select -ExpandProperty member| select #{Name=’members‘;Expression={[string]::join(“;”, ($_))}} | export-csv C:\Path\File.csv -NoTypeInformation
Warning: if you have users from another domain in the domain local group they will appear as SIDs.
I ran into this error when looking at distribution groups. - I got no error, but the 4 members of the group were not listed. I was convinced it was because it was a domain local group.
I had set the recipient scope to the entire forest (Set-AdServerSettings -ViewEntireForest $true). For whatever reason, if you do that, you should use the DN (rather than alias or name) to get the members, and also include the switch -ReadFromDomainController. So, I had to use
Get-DistributionGroupMember -Identity DistinguishedName -ReadFromDomainController

PowerShell Newb - Cannot convert

I'm learning Powershell and I'm trying to understand why this isn't working. I verified that -Identity accepts pipeline so I'm guessing its the type of value its passing but I don't understand why this doesn't work
Get-ADUser -Identity (Import-Csv .\GROUP.csv)
GROUP.csv is a file on my desktop which contains a list of SIDs. I can read it with no issues when just doing an Import-Csv .\GROUP.csv. Here is the result
S-1-5-21-583907252-1979792683-725345543-112088
S-1-5-21-583907252-1979792683-725345543-48881
S-1-5-21-583907252-1979792683-725345543-48880
S-1-5-21-583907252-1979792683-725345543-53776
S-1-5-21-583907252-1979792683-725345543-125569
S-1-5-21-583907252-1979792683-725345543-120374
S-1-5-21-583907252-1979792683-725345543-48882
S-1-5-21-583907252-1979792683-725345543-183175
S-1-5-21-583907252-1979792683-725345543-183136
S-1-5-21-583907252-1979792683-725345543-183130
S-1-5-21-583907252-1979792683-725345543-183112
S-1-5-21-583907252-1979792683-725345543-176034
S-1-5-21-583907252-1979792683-725345543-176023
S-1-5-21-583907252-1979792683-725345543-176022
S-1-5-21-583907252-1979792683-725345543-176002
S-1-5-21-583907252-1979792683-725345543-175974
S-1-5-21-583907252-1979792683-725345543-175931
S-1-5-21-583907252-1979792683-725345543-175889
S-1-5-21-583907252-1979792683-725345543-175836
S-1-5-21-583907252-1979792683-725345543-175804
S-1-5-21-583907252-1979792683-725345543-183195
S-1-5-21-583907252-1979792683-725345543-183180
S-1-5-21-583907252-1979792683-725345543-31219
S-1-5-21-583907252-1979792683-725345543-176037
S-1-5-21-583907252-1979792683-725345543-82576
S-1-5-21-583907252-1979792683-725345543-175905
S-1-5-21-583907252-1979792683-725345543-175777
S-1-5-21-583907252-1979792683-725345543-175765
On top of that I can use the Get-ADUser -Identity and that works fine.
Why do I get the following when trying piping the one to the other?
Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADUser' required by parameter 'Identity'.
Specified method is not supported.
At line:1 char:22
+ Get-ADUser -Identity (Get-Content .\group.txt)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The -identity parameter doesn't accept array as input but it accept pipeline input by value than you can do:
Import-Csv .\GROUP.csv | Get-ADUser
If the name of the first column in .csv file is sid then you can try this option too
(Import-CSV .\Group.csv) | foreach-object { get-aduser -Identity $_.sid }

Add bulk computer membership

Im trying to add multiple compuers (from a txt file) to be part of a certain security group.
sample from input.txt
COL7DM2CP1
COLC5RNDP1
using the following powershell input:
Get-Content C:\Scripts\input.txt | Add-ADPrincipalGroupMembership -MemberOf 'AMATU.SCCM.Office2010.Std'
however im getting the following outpout error:
Add-ADPrincipalGroupMembership : Cannot find an object with identity: 'COL7DM2CP1' under: 'DC=actuant,DC=pri'.
At C:\Scripts\Add bulk ADcomputer to group.ps1:1 char:36
+ Get-Content C:\Scripts\input.txt | Add-ADPrincipalGroupMembership -MemberOf 'AMA ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (COL7DM2CP1:ADPrincipal) [Add-ADPrincipalGroupMembership], ADIdentityN
otFoundException
+ FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Manageme
nt.Commands.AddADPrincipalGroupMembership
The issue is that the Add-PrinicpalGroupMembership does not know what object you are looking for. It does not query AD for the simple computername, it assumes the FQDN. If you wanted to pass it just a name, you'll need to give it's full AD Distinguished Name.
An easy way around this is to use Get-ADcomputer and pass that to Add-PrinicpalGroupMembership
Get-Content C:\Scripts\input.txt | Get-ADComputer | Add-ADPrincipalGroupMembership -MemberOf 'AMATU.SCCM.Office2010.Std'