I'm writing a PowerShell script to create a new Active Directory group and automatically put it in the correct OU, depending on what department the user is in. The script gets the department from the user in Active Directory and then needs to use that as the name of the OU in active directory. When I don't use the variable in the AD path, this script works.
[string]$department = Get-ADUser -identity johndoe -properties department | Select department
New-ADGroup -Name NewADGroup -GroupScope Global -path “OU=($department),OU=SubDepartment,OU=MainDepartment,DC=OrgName”
However, when I try to use the variable $department as above, I get the following error:
New-ADGroup : The object name has bad syntax
At C:\Users\JohnDoe\Desktop\CreateNewGroup.ps1:7 char:1
+ New-ADGroup -Name NewADGroup -GroupScope Global -path
"OU=($department ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=NewADGroup,DC=OrgName
:String) [New-ADGroup], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirec
tory.Management.Commands.NewADGroup
How can I call that variable inside the Active Directory path?
You actually have 2 issues here that are common pitfalls.
$department is not a string per se but a string representation of an object with a deparment property. You need to break the string out. That is what -ExpandProperty was for. If you looked at your department now you would see something like #{Department="IT"}
You are also having issues with variable expansion in strings.
[string]$department = Get-ADUser -identity johndoe -properties department | Select -Expandproperty department
New-ADGroup -Name NewADGroup -GroupScope Global -path "OU=$department,OU=SubDepartment,OU=MainDepartment,DC=OrgName"
If you are not calling properties or complex object then removing the brackets is sufficient. Else you can just use a sub expression "OU=$($department),OU=SubDepartment,OU=MainDepartment,DC=OrgName". Without the $ sign the brackets were considered part of the string.
try a dollar sign in front of the opening parenthesis like this:
"OU=$($department)..."
Related
I would need your help with the use of New-AdGroup command.
The goal of my script is to verify if an Active Directory group exists and if it doesn't exist the script create the group and add the member of the group in a specific OU.
But my problem is when I use the script with a combination of OU and one of them contains some spaces in its name (ex : "OU=Servers of Files"), the script returns an error.
Example: I need to add the group in "OU=Fileserver1" which is a sub OU of "OU=Servers of Files" which is a sub OU of "OU=Groupes".
When I call New-AdGroup with a path's value : "Ou=ServerFile1,OU=Servers of Files,OU=Groupes,DC=Contoso,DC=lan", I get the following error.
New-ADGroup : Objet de l’annuaire non trouvé At line:29 char:5
+ New-ADGroup -Name "$DLGroupName" -Path "$Orga" -GroupCategory "Se ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (CN=G_GROUP1...ONTOSO,DC=lan:String) [New-ADGroup],
ADIdentityNotFoundException
+ FullyQualifiedErrorId : Objet de l’annuaire non trouvé,Microsoft.ActiveDirectory.Management.Commands.NewADGroup
The problem is caused by "OU=Servers of Files" because I tried with an OU without spaces and it was working.
Please find a part of the script below, let me know how I can manage spaces under a path :
#Variable
$CurrentDomain = Get-ADDomain | Select -Property DistinguishedName
$TargetOU = "OU=FileServer1,OU=Servers of Files,OU=Groupes" #
$OrganizationalUnitDN = $TargetOU+","+ $CurrentDomain.DistinguishedName
$Orga = $OrganizationalUnitDN
$DLGroupName = "DL_FileServer1_TEST"
$Description = "\\FileServer1\Share\Test"
New-ADGroup -Name "$DLGroupName" -Path "$Orga" -GroupCategory "Security" -GroupScope "Global" -Description "$Description" -PassThru
Note : $Orga = Ou=ServerFile1,OU=Servers of Files,OU=Groupes,DC=Contoso,DC=lan
When we encounter weird bugs like this, a good first test is to manually run the command with no variables to find the root cause of the error. Doing this shows us that we don't need to escape spaces with a \ or \20 sequence and that route won't help us.
Because I can run your command with no errors when I manually expand the variables like so:
New-ADGroup -Name "DL_FileServer1_TEST" -Path "OU=Servers Of Files,DC=FoxDeploy,DC=local" `
-GroupCategory "Security" -GroupScope "Global" -Description "Test" -PassThru
DistinguishedName : CN=DL_FileServer1_TEST1,OU=Servers Of Files,DC=FoxDeploy,DC=local
GroupCategory : Security
GroupScope : Global
Name : DL_FileServer1_TEST1
ObjectClass : group
ObjectGUID : 5889f8ea-9d80-4609-ad47-92e50a574088
SamAccountName : DL_FileServer1_TEST1
SID : S-1-5-21-3818945699-900446794-3716848007-32100
Now that I know this works, I know I can then store the values in variables to make it cleaner to read, like this:
$params = #{
Name = "DL_FileServer1_TEST1";
Path = "OU=Servers Of Files,DC=FoxDeploy,DC=local";
GroupCategory = "Security";
GroupScope = "Global";
Description = "My Test Group"
PassThru = $true
}
New-ADGroup #params
If I had to guess, I bet that you need to run the entire script to populate all of the variables, and instead you are rerunning the last command over and over but one of the variables is $null.
If that doesn't work...
If not that, then are we sure the container of Ou=ServerFile1 actually exists too?
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
When we create a public folder and mail enable in Exchange Online, the default email address is #domain.onmicrosoft.com
Our folder names are "NNNNN_Folder name" where NNNNN is a 5 digit number.
I would like to set the primary email address of the public folder to NNNNN#domain.com
I have tried many variations of this:
Get-PublicFolder -Recurse -Identity "\X\Y\Z"|
Sort-Object Identity –Descending|
Select-Object -first 4|
Set-MailPublicFolder -PrimarySmtpAddress {$_.name.substring(0,5)+"#domain.com"}
and receive errors about interpreting the resulting email address:
Cannot process argument transformation on parameter 'PrimarySmtpAddress'. Cannot convert value
"$_.name.substring(0,5)+"#domain.com"" to type "Microsoft.Exchange.Data.SmtpAddress". Error: "The email
address "$_.name.substring(0,5)+"#domain.com"" isn't correct. Please use this format: user name, the # sign,
followed by the domain name. For example, tonysmith#contoso.com or tony.smith#contoso.com."
+ CategoryInfo : InvalidData: (:) [Set-MailPublicFolder], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-MailPublicFolder
+ PSComputerName : outlook.office365.com
I also tried setting the EmailAddress of the PublicFolder to NNNNN#domain.com in the same operation.
-EmailAddresses #{$_.name.substring(0,5)+"#domain.com"}
It doesn't seem to be evaluating the argument or I'm missing something else?
If I change Set-MailPublicFolder ... with
% {$_.name.substring(0,5) + "#domain.com"}
I do see the email addresses I am expecting.
Thanks,
Craig.
See this version.
From Microsoft command documentation, the identity parameter is required (see this)
I am also not sure it can take the array and process each individual without specifying a foreach.
See this modified versions.
$PublicFolders = Get-PublicFolder -Recurse -Identity "\X\Y\Z"| Sort-Object Identity –Descending | Select-Object -first 4
$PublicFolders | foreach {
$NewEmail = "$($_.name.substring(0,5))#domain.com"
Write-Host "Settings MailPublicFolder with name $($_.Identity) to $NewEmail" -ForegroundColor Cyan
Set-MailPublicFolder -Identity $_.Identity -PrimarySmtpAddress $NewEmail
}
I am attempting to pull a users first and last name from AD using PowerShell.
The commands:
$GivenName = Get-ADUser -Identity $User | select GivenName
Write-Host $GivenName
returns a value of: #{GivenName=Bruce}
I then tried to reduce the string down to just the part i need with the following commands:
$First = $GivenName.Replace("#{GivenName=","")
$First = $First.Replace("}","")
This should strip away all except for the string 'Bruce'
Instead I get this following error:
Method invocation failed because [Selected.Microsoft.ActiveDirectory.Management.ADUser] does not contain a method named 'Replace'.
At C:\Users\john.ring\Documents\Scripts\UpdateADUsers.ps1:10 char:5
+ $First = $GivenName.Replace("#{GivenName=","")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Replace:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
My Google-fu has failed to find a solution. Any suggestion on how to correct the error or a better way to pull the users first name would be greatly appreciated.
When you pipe objects to Select-Object [propertyname(s)], the Select-Object cmdlet creates a new object for you, with the properties from the input object that you specified. This object in turn ends up being rendered as #{PropertyName1=PropertyValue1[;PropertyNameN=PropertyValue2]} when converted to a string.
To grab the value of a single property, and nothing else, use the -ExpandProperty parameter:
$GivenName = Get-ADUser -Identity $user |Select-Object -ExpandProperty GivenName
Since you need multiple properties from the same user, better store the the user in a variable and use the . dereference operator to access the GivenName and Surname properties:
$UserObject = Get-ADUser -Identity $user
$GivenName = $UserObject.GivenName
$Surname = $UserObject.Surname
GivenName is a user object attribute in Active Directory. You're storing the results of your query in a PowerShell object called $GivenName, however the two are not the same. To reference the user's given name, you need to reference the GivenName property of the PowerShell object. $GivenName.GivenName is what you are looking for.
It might be less confusing if you store the results of your AD query in an object named $User instead, so $User.GivenName is how you would reference the given name property.
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