My script to import AD contacts to a new domain fails because some values are Null & Empty. I exported the contacts as an XML. How do I fix this with an IF statement to create the AD Object and skip if Null & Empty, but fill it in if there is a value?
Import Script
Import-Module ActiveDirectory
$import = Import-Clixml "C:\Users\Downloads\contacts.xml"
foreach($contact in $import){
$newContact=#{
path = "OU=Test,OU=domain,OU=B"
type = "Contact"
Name = $contact.name
otherAttributes = #{
givenname = $contact.givenName
sn = $contact.sn
mail = $contact.mail
displayName = $contact.displayName
cn = $contact.cn
co = $contact.co
company = $contact.company
l = $contact.l
mailNickname = $contact.mailNickname
telephoneNumber = $contact.telephoneNumber
st = $contact.st
streetAddress = $contact.streetAddress
postalcode = $contact.postalcode
physicalDeliveryOfficeName = $contact.physicalDeliveryOfficeName
mobile = $contact.mobile
}
}
New-ADObject #newContact
}
Error
New-ADObject : Cannot validate argument on parameter 'OtherAttributes'. The argument is null or an element of the argument collection contains a null value.
At C:\Users\Documents\Scripts\contacts-import.ps1:26 char:18
+ New-ADObject #newContact
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-ADObject], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADObject
New-ADObject : Cannot validate argument on parameter 'OtherAttributes'. The argument is null or an element of the argument collection contains a null value.
At C:\Users\Documents\Scripts\contacts-import.ps1:26 char:18
+ New-ADObject #newContact
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-ADObject], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirecto
Build the OtherAttributes dictionary one entry at a time, and test if a corresponding value actually exists:
# ...
Import-Module ActiveDirectory
$import = Import-Clixml "C:\Users\Downloads\contacts.xml"
$potentialAttributes = #(
'givenName'
'sn'
'mail'
'displayName'
'cn'
'co'
'company'
'l'
'mailNickname'
'telephoneNumber'
'st'
'streetAddress'
'postalcode'
'physicalDeliveryOfficeName'
'mobile'
)
foreach($contact in $import){
$newContact=#{
path = "OU=Test,OU=domain,OU=B"
type = "Contact"
Name = $contact.name
OtherAttributes = #{}
}
foreach($attributeName in $potentialAttributes){
if(-not [string]::IsNullOrEmpty($contact.$attributeName)){
$newContact['OtherAttributes'][$attributeName] = $contact.$attributeName
}
}
New-ADObject #newContact
}
Related
Have created a script to export usermailbox statistics in office 365, the script accepts a txt file that has the list of specific users who i want to export that data from their accounts.
When i run the script, i get errors below:
Cannot process argument transformation on parameter 'Identity'. Cannot convert the "System.Collections.ArrayList" value of type "System.Collections.ArrayList" to type
"Microsoft.Exchange.Configuration.Tasks.MailboxIdParameter".
+ CategoryInfo : InvalidData: (:) [Get-Mailbox], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-Mailbox
+ PSComputerName : outlook.office365.com
The property '' cannot be found on this object. Verify that the property exists and can be set.
At line:3 char:16
+ $mailbox = $_.
+ ~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Cannot process argument transformation on parameter 'Identity'. Cannot convert the "System.Collections.ArrayList" value of type "System.Collections.ArrayList" to type
"Microsoft.Exchange.Configuration.Tasks.GeneralMailboxOrMailUserIdParameter".
+ CategoryInfo : InvalidData: (:) [Get-MailboxStatistics], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-MailboxStatistics
+ PSComputerName : outlook.office365.com
Cannot process argument transformation on parameter 'Identity'. Cannot convert the "System.Collections.ArrayList" value of type "System.Collections.ArrayList" to type
"Microsoft.Exchange.Configuration.Tasks.GeneralMailboxOrMailUserIdParameter".
+ CategoryInfo : InvalidData: (:) [Get-MailboxFolderStatistics], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-MailboxFolderStatistics
+ PSComputerName : outlook.office365.com
My script
$All = [collections.arraylist]#(get-content "C:\Users.txt")
$All | ForEach-Object {
$mailbox = $_.
$quota = Get-Mailbox -identity $mailbox | select ProhibitSendQuota, ProhibitSendReceiveQuota, RecoverableItemsQuota, ArchiveQuota, ArchiveWarningQuota
$CurrentMailboxUsedSize = Get-MailboxStatistics -identity $mailbox | select TotalItemSize
$recoverableitem = Get-MailboxFolderStatistics -identity $mailbox | ? {$_.Name -eq "Recoverable Items"}
New-Object -TypeName PSObject -Property #{
UserPrincipalName = $mailbox
CurrentMailboxUsedSize = $CurrentMailboxUsedSize.TotalItemSize
ProhibitSendQuota = $quota.ProhibitSendQuota
MailboxTotalSize = $quota.ProhibitSendReceiveQuota
CurrentRecoverableItemsSize = $recoverableitem.FolderAndSubfolderSize
RecoverableItemsQuota = $quota.RecoverableItemsQuota
ArchiveMailboxQuota = $quota.ArchiveQuota
ArchiveWarningQuota = $quota.ArchiveWarningQuota
}
} | Sort-Object 'UserPrincipalName', 'CurrentMailboxUsedSize', 'CurrentRecoverableItemsSize', 'ProhibitSendQuota', 'MailboxTotalSize', 'RecoverableItemsQuota', 'ArchiveMailboxQuota', 'ArchiveWarningQuota' | Export-CSV "C:\results.csv" -NoTypeInformation -Encoding UTF8
My text file
Where am i getting it wrong?
Hi I am trying to run a script to get information from all the datastores.
The code script I am running is giving an error:
At C:\Users\Administrator\Desktop\Scripts\test.ps1:125 char:2
+ $allstoreinfo += $storeinfo
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
The script is a simple for loop:
$datastores = Get-Datastore
$allstoreinfo = #()
foreach($store in $datastores){
$storeinfo = "" | Select Name, FileSystem, Type, CapacityGB, FreeSpaceGB
$datastoreview = get-datastore -Name $store.Name | Get-View | select -ExpandProperty summary
$CapacityGB = [math]::round($datastoreview.Capacity/1GB,2)
$FreeSpaceGB = [math]::round($datastoreview.FreeSpace/1GB,2)
$ProvisionedGB = [math]::round(($datastoreview.Capacity - $datastoreview.FreeSpace + $datastoreview.Uncommitted)/1GB,2)
$storeinfo.Name = $store.Name
$storeinfo.FileSystem = $store.FilesystemVersion
$storeinfo.Type = $store.Type
$storeinfo.CapacityGB = $CapacityGB
$storeinfo.FreeSpaceGB = $FreeSpaceGB
$allstoreinfo += $storeinfo
}
Write-Host "---------------------------------"
$allstoreinfo | Select Name, FileSystem, Type, CapacityGB, FreeSpaceGB
Write-Host "---------------------------------"
I am creating a PowerShell script at work to copy user accounts. The script works perfectly on my test Server 2016 VM. It also works in our work environment on a coworkers Windows 10 PC, however I cannot run it on my local machine. It returns the following error:
New-ADUser : The object name has bad syntax
At line:155 char:1
+ New-ADUser -Name $New_DisplayName #params
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=cnelson test...ctions,DC=local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Add-ADGroupMember : Cannot find an object with identity: 'cnelsontest1' under:
'DC=,DC=local'.
At line:159 char:29
+ Add-ADGroupMember -Members $Username.Text
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (cnelsontest1:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
$params = #{'SamAccountName' = $Username.Text;
'Instance' = $AD_Account_To_Copy;
'DisplayName' = $New_DisplayName;
'GivenName' = $FirstName.Text;
'Path' = $New_Path;
'SurName' = $LastName.Text;
'ChangePasswordAtLogon' = $true;
'Enabled' = $true;
'UserPrincipalName' = $Username.Text;
'AccountPassword' = $New_Pass;
'EmailAddress' = $Username.Text + '#azcorrections.gov';
'HomePage' = $HomePage.HomePage;
'Description' = $NewDescription.Description;
'Office' = $NewOffice.Office;
'StreetAddress' = $NewStreet.StreetAddress;
'City' = $NewCity.City;
'State' = $NewState.State;
'PostalCode' = $NewPostalCode.PostalCode;
'Title' = $NewTitle.Title;
'Department' = $NewDepartment.Department;
'Company' = $NewCompany.Company;
'ScriptPath' = $NewScript.ScriptPath;
'OfficePhone' = $PhoneNumber.text;
}
New-ADUser -Name $New_DisplayName #params
Full Script link
I'm running PSVersion 5.1.150
Any ideas as to what i'm missing and why i'm coming across this error? I have no idea what it is referring to, nor why it works on one coworkers computer but not my own.
Edit: Value of $params at the time of the error:
Name Value
---- -----
AccountPassword System.Security.SecureString
Description Chris Nelson Test Account
UserPrincipalName cnelsontest1
HomePage http://...
DisplayName cnelson test1
SamAccountName cnelsontest1
ScriptPath
EmailAddress cnelsontest1#example.com
Office test
GivenName cnelson
Title SYSTEMS/LAN ADMR
Company
OfficePhone 555-1234
StreetAddress Sesame Street
PostalCode 54321
SurName test1
State candid
Department IT
ChangePasswordAtLogon True
Path cnelson,OU=IT_TECHSRVS,OU=Information Technology,OU=ADMIN,OU=CENT_OFF,DC=example,DC=com
City
Enabled True
Instance CN=test\, cnelson,OU=IT_TECHSRVS,OU=Information Technology,OU=ADMIN,OU=CENT_OFF,DC=example,DC=com
I'm calculating $New_Path like this:
$New_Path = (Get-ADUser ($UsernameCopy.Text)).DistinguishedName -replace '^.*?,', ''
The way you remove the common name portion from the value of $AD_Account_To_Copy is flawed. -replace '^.*?,', '' will remove everything up to the first comma in the string. If the common name itself contains a comma (like in CN=test\, cnelson,OU=...) the replacement won't remove cnelson,. Amend your regular expression with a positive lookahead assertion, so that everything before the first OU= is removed:
$New_Path = $AD_Account_To_Copy -replace '^.*?,\s*(?=ou=)', ''
I'm having issues feeding variables into the New-MsolUser cmdlet. I'm getting the following error.
New-MsolUser : A positional parameter cannot be found that accepts argument 'â?UserPrincipalName ausertest#test.ie â?UsageLocation'.
At C:\users\test\Documents\test.ps1:148 char:1
+ New-MsolUser -DisplayName $TargetFullname â?"UserPrincipalName $TargetEmail â?" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-MsolUser], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.Online.Administration.Automation.NewUser
The code I am using is:
$Source = "AnotherADUser"
$TargetFname = "New"
$TargetLname = "User"
$Target = "ausertest"
$TargetFullname = [string]::Concat($TargetFname ," ", $TargetLname)
$SourceEmail = (Get-ADUser $source -Property EmailAddress).EmailAddress
$SourceDomain = $SourceEmail.split("#")[1]
$TargetEmail = ([string]::Concat($Target , "#" , $SourceDomain))
New-MsolUser -DisplayName $TargetFullname –UserPrincipalName $TargetEmail –UsageLocation "IE" | Set-MsolUserLicense -AddLicenses "TESTINSTALL:EXCHANGESTANDARD"
This command works when I hardcode the details..
–UserPrincipalName and –UsageLocation use not the minus character but the
character with code 8211. Maybe it's fine but try to use the standard minus
instead, just to be sure.
I am creating a new object for export values to CSV:
New-Object -TypeName PSObject -Property #{
host_name = ($server.name).ToLower()
address = $IPAddress
host_is_collector = "no"
host-preset = "windows-server"
} | Select-Object host_name,address,host-preset | Export-Csv -Path $nConf_import_host_file
The problem is that one of the lines contains a dash (host-preset). I would ofcourse simply change it to an underscore, but my CSV needs this value to be a dash. I could also do a -replace on the entire csv after it has been created but that seems dirty.
Is there a way I can use dash here?
My error msg is:
Missing '=' operator after key in hash literal.
At Z:\Scripts\Testscripts\ScanServers_and_check_nagiosV7.ps1:336 char:16
+ host-preset <<<< = "windows-server"
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : MissingEqualsInHashLiteral
You simply need to treat the host-preset property name as a string by enclosing it in quotes:
New-Object -TypeName PSObject -Property #{ "host-preset" = "windows-server" }