I currently have the below script that will create a contact with certain attributes I require.
New-ADObject -name SGTContacttest5 -Type Contact -path "OU=SGTestOU,OU=Contacts,DC=DC,DC=Company,DC=local" -OtherAttributes #{
'department'="America";
'givenName'="SG";
'sn'="Test";
'displayname'="SG Test";
'title'="Job Title";
'telephoneNumber'="020";
'mobile'="075";
'mail'="SGTest888#example.com";
'physicalDeliveryOfficeName'="Office Name";
'company'="Company Name";
'proxyAddresses'="smtp:SGTest888#example.com";
'targetaddress'="smtp:SGTest888#example.com"
}
This works perfectly but now I am required to input about 100 of these contacts from a CSV file.
I get that at the top I would put:
$users = Import-Csv -Path C:\temp\users.csv
Then I would then use this somehow:
foreach ($user in $users) {
My CSV starts the same as my code the columns are shown as below:
First
Surname
Full Name
Job Title
Office Number
Mobile Number
E-mail
Location
Well its a fairly open ended question, but $user in this example is a simple place holder variable, so could be anything, $i or $temp, it represents one interation of the parent, in this case $users.
This will be a good start to see what your given back:
$users = import-csv -Path C:\temp\users.csv
foreach ($user in $users)
{
$user
}
use:
foreach ($user in $users)
{
$user | get-member
}
to see what you have to work with.
Then you can access properties of the $user like so:
foreach ($user in $users)
{
New-ADObject -name SGTContacttest5 -Type Contact -path "OU=SGTestOU,OU=Contacts,DC=DC,DC=Company,DC=local" -OtherAttributes #{
'department' = $user.department
'Surname' = $user.Surname
}
}
You can access the variables like $user.Job within the foreach loop. Notice that you should omit the quotes. Here an example with one property, you should be able to do the rest yourself:
$users = Import-Csv -Path C:\temp\users.csv
foreach ($user in $users)
{
New-ADObject -name SGTContacttest5 -Type Contact -path "OU=SGTestOU,OU=Contacts,DC=DC,DC=Company,DC=local" -OtherAttributes #{
'department'=$user.Job;
# ....
}
}
Related
Hi Stackoverflow community, this is my first time posting a question.
I'm also new to powershell but I was able to put together a small script based on other scripts I found and it kind of works.
My goal is to query all mailboxes and output a column with the user and one with the entry for their trustedsendersanddomains.
I would like it to repeat the user when the user has multiple entries and display none in case they don't have any. It would look something like this:
csv
This is what I have. (for testing purposes I'm setting 3 actual users but the commented part works)
$Users = ("user1", "user2", "user3")
#$Users = Get-Mailbox | select -ExpandProperty Alias
$objfull = #()
Foreach ($User in $Users)
{
$Junk = Get-MailboxJunkEmailConfiguration $User
$Emails = Get-MailboxJunkEmailConfiguration $User | select -ExpandProperty TrustedSendersAndDomains
$obj = New-Object System.Object
Foreach ($Email in $Emails)
{
$obj | Add-Member NoteProperty User $User
$obj | Add-Member NoteProperty Trusted_Senders $Junk.TrustedSendersAndDomains
$objfull += $obj
}
}
$objfull | Export-Csv C:\Users\Leo\export.csv -NoTypeInformation
While it will throw error for users without entries this works in repeating the user, but the trusted sender output is the whole array and it's space separated, not comma.
This other one I was testing with will write to terminal the way I want the csv to be.
$Users = ("user1", "user2", "user3")
#$Users = Get-Mailbox | select -ExpandProperty Alias
$objfull = #()
Foreach ($User in $Users)
{
$Junk = Get-MailboxJunkEmailConfiguration $User
$Emails = Get-MailboxJunkEmailConfiguration $User | select -ExpandProperty TrustedSendersAndDomains
$obj = New-Object System.Object
Foreach ($Email in $Emails)
{
Write-Host $Email, $User
}
}
#$objfull | Export-Csv C:\Users\Leo\export.csv -NoTypeInformation
I appreciate the help in advance!
I got a small issue. I have a CSV with some names. I needed to get the email addresses of those users, so I created a small script that will find users with that firstname and lastname in AD.
After that, I wanted to export it to a new CSV file, but keep the phone-numbers from the first CSV file so its also available in the new CSV export.
That last part don't seem to work. In the output that expression is shown as {}.
Can someone help me?
$csv = import-csv -path C:\users\da6\desktop\UsersZonderEmail.csv
$output = #()
foreach ($i in $csv) {
$givenname = $i.Voornaam
$lastname = $i.Achternaam
$number = $i.IpPhone
$output += try {Get-ADUser -Filter {givenname -eq $givenname -and surname -eq $lastname} | select Name, UserPrincipalName, #{ name="ipphone"; expression=$number}} catch {}
}
Basically what is wrong with your code is that you forgot the opening bracket { in the expression oart of the calculated property.
Also note that -Filter should be a string, not a scriptblock.
Lastly, adding to an array with += is a bad habit, as the entire array needs to be rebuilt in memory on every addition.
Better let PowerShell collect the values from the loop:
$csv = Import-Csv -Path 'C:\users\da6\desktop\UsersZonderEmail.csv'
$output = foreach ($item in $csv) {
Get-ADUser -Filter "GivenName -eq '$($item.Voornaam)' -and Surname -eq '$($item.Achternaam)'" -Properties EmailAddress |
Select-Object Name, UserPrincipalName, #{ Name="ipphone"; Expression = {$item.IpPhone}}, EmailAddress
}
# output to new CSV file
$output | Export-Csv -Path 'C:\users\da6\desktop\UsersMetEmail.csv' -NoTypeInformation
I am unable to access my object using .PropertyName.
I have tried using $val.Options.$propertyName but it yields no result.
$propertyName is a value input from a file
`$val.$propertyName` results in "Cannot index into null array"
$result = New-Object -TypeName 'System.Collections.ArrayList';
foreach ($user in $users) {
$val = Get-LocalUser $user | Select *
$val = $val.$propertyName
$result.Add($val)
}
In your context $val.$propertyName does't mean anything can you try :
$result = New-Object -TypeName 'System.Collections.ArrayList';
foreach ($user in $users) {
$val = Get-LocalUser $user
$result.Add($val)
}
$result will be an array of "Localuser".
You don't need an arraylist at all. Just let PowerShell do the collecting by capturing the output inside the loop
$result = foreach ($user in $users) {
(Get-LocalUser $user).$propertyName
}
This is assuming your variable `$propertyName` contains a valid attribute name
While the above code does what you've asked for, I don't think the result would be very helpful, because it just lists whatever is in the property stored in $propertyName, and you cannot see which user has what values in there.
A better approach would be to output objects with the properties you want returned.
Something like
# just an example..
$propertyName = 'Description'
$users = 'WDAGUtilityAccount', 'Administrator'
$result = foreach ($user in $users) {
output an object with the name of the user, and also the property you are after
Get-LocalUser $user | Select-Object Name, $propertyName
}
$result
Since parameter -Name (the first positional parameter) can take an array of usernames, this can be shortened to:
$result = Get-LocalUser $users | Select-Object Name, $propertyName
I want to move multiple users from input file to multiple OU's. But the code below keeps giving me error:
$i=0
$tempOUsArray = #{}
$tempOUsArray = Import-CSV -path "c:\temp\OUs.txt" #this file contains Full DN of OUs
$UsersToBeMoved = Import-CSV -path "c:\temp\Users.txt #this file contain SamAccountName field of users
$UsersToBeMoved | ForEach-Object{
$tempUsers = (get-aduser -identity $_.Name).distinguishedName
#assign each OU to temp holder
$TempOU = $tempOUsArray[$i]
Move-ADObject -Identity $tempUsers -TargetPath $TempOU
$i++ #inclement position of array
}
(See edits for previous answer attempts, clearing to reduce answer size)
See the below. I've tested this on a setup I have and this successfully moved the objects without an issue.
Users.txt (CSV format, matching what I believe yours is)
samaccountname,name
tst-user1,user1
tst-user2,user2
tst-user3,user3
tst-user4,user4
# (From OP: My users input file is)
# john.doe
# ann.bill
# jose.love
OUs.txt (no quotation marks in txt file, though may need if there's any spaces in the DN)
OU=test,OU=Accounts,DC=domain,DC=int
OU=test,OU=Accounts,DC=domain,DC=int
OU=test,OU=Accounts,DC=domain,DC=int
OU=test,OU=Accounts,DC=domain,DC=int
PS script
$i = 0
$OUs = #()
$OUs = Get-Content -Path C:\temp\OUs.txt
$Users = Import-Csv -Path C:\temp\Users.txt
$users | ForEach-Object {
$tempUser = (Get-ADUser -Identity $($_.samaccountname)).DistinguishedName
$tempOU = $OUs[$i]
Write-Host "Moving User: [$tempUser]"
Write-Host " to OU: [$tempOU]"
Move-ADObject -Identity $tempUser -TargetPath $tempOU
$i++
}
Output
Moving User: [CN=user1,OU=source,OU=test,OU=Accounts,DC=domain,DC=int]
to OU: [OU=test,OU=Accounts,DC=domain,DC=int]
Moving User: [CN=user2,OU=source,OU=test,OU=Accounts,DC=domain,DC=int]
to OU: [OU=test,OU=Accounts,DC=domain,DC=int]
Moving User: [CN=user3,OU=source,OU=test,OU=Accounts,DC=domain,DC=int]
to OU: [OU=test,OU=Accounts,DC=domain,DC=int]
Moving User: [CN=user4,OU=source,OU=test,OU=Accounts,DC=domain,DC=int]
to OU: [OU=test,OU=Accounts,DC=domain,DC=int]
And all worked properly, no errors. Can you try the above code, and ensure your source files are in a similar format?
Final edit
With the provided edit / update to the "users.txt" file, the below script should work as expected.
New users.txt file (note: no column header)
john.doe
ann.bill
jose.love
PS script
$i = 0
$OUs = #() # May as well clear, in case old data exists
$Users = #() # May as well clear, in case old data exists
$OUs = Get-Content -Path C:\temp\OUs.txt
$Users = Get-Content -Path C:\temp\Users.txt
$users | ForEach-Object {
$tempUser = (Get-ADUser -Identity $($_)).DistinguishedName
$tempOU = $OUs[$i]
Write-Host "Moving User: [$tempUser]"
Write-Host " to OU: [$tempOU]"
Move-ADObject -Identity $tempUser -TargetPath $tempOU
$i++
}
It is with the Move-ADObject. This function will NOT work with moving parts like multiple OUs assignment. My revised code is as below:
$i=0
$tempOUsArray = #{}
$tempOUsArray = get-content -path "c:\temp\OUs.txt" #this file contains Full DN of
OUs
$UsersToBeMoved = get-content -path "c:\temp\Users.txt" #this file contain
SamAccountName field of users
ForEach ($tuser in $UsersToBeMoved){
$tempUser = dsquery user -samid $tuser
#assign each OU to temp holder
$TempOU = $tempOUsArray[$i]
dsmove $tempUser -newparent $TempOU
$i++ #inclement position of array
}
$tempOUArray.Clear()
$TempOU=''
$tempUser=''
$tuser=''
Note: Remove All Header from input files. OUs.txt with full DN in double-quotes. Users.txt file contains only the SamAccountName without quotes.
I'm trying to delete the assigned roles for a set of users that I've in csv file:
$Users = Import-Csv 'C:\Users.csv' | select -ExpandProperty SignInName
Then, I wanted to retrieve all the object Ids of these users so I run the following:
foreach ($user in $Users)
{
$Users = (Get-AzureRmADUser -UserPrincipalName $User).Id
}
Unfortunately, it only retrieves the id of 1 user not all the users in the sheet.
Finally, when I try to delete the role assignment for the generated result using the following Cmdlet:
Remove-AzureRmRoleAssignment -ObjectId $Users -RoleDefinitionName "*Owner*"
I get the following error:
Remove-AzureRmRoleAssignment : The provided information does not map to a role assignment
Please advise why I only get one user after the loop and also, why I get that error.
UPDATE
In order to make sure that the script would delete the users from different subscriptions, I changed the script a little bit
$Users = Import-Csv 'C:\Users.csv' | select -ExpandProperty SignInName
$Subs = (Import-Csv 'C:\Users.csv').SubscriptionId
foreach ($sub in $Subs)
{
Select-AzureRmSubscription -Subscription $sub
foreach ($user in $Users)
{
$OID = (Get-AzureRmADUser -UserPrincipalName $User).Id
Remove-AzureRmRoleAssignment -ObjectId $OID.Guid -RoleDefinitionName Owner -Scope /subscriptions/$sub -Verbose
}
}
Unfortunately, I get the following error:
Remove-AzureRmRoleAssignment : The provided information does not map to a role assignment.
EDIT: So from your edits I don't think you get the idea of the ForEach. I will try to explain your ForEach edit for you at the end. But right now, this should work based on your info.
$Users = Import-Csv 'C:\Users.csv'
foreach ($user in $Users){
Remove-AzureRmRoleAssignment -RoleDefinitionName Owner -SignInName $_.SignInName -Scope /subscriptions/$_.SubscriptionId -Verbose
}
Now, the problem with your edited code.
# The CSVs can be combined down to one and specific data pulled from them when needed.
$Users = Import-Csv 'C:\Users.csv' | select -ExpandProperty SignInName
$Subs = (Import-Csv 'C:\Users.csv').SubscriptionId
# This says for each object in variable $subs...
foreach ($sub in $Subs)
{
# Select the subscription - But do nothing with it cuz herp.
Select-AzureRmSubscription -Subscription $sub
foreach ($user in $Users)
{
# Searches for the ObjectID of a User based on their SignInName (Email) and assigns to variable
$OID = (Get-AzureRmADUser -UserPrincipalName $User).Id
Remove-AzureRmRoleAssignment -ObjectId $OID.Guid -RoleDefinitionName Owner -Scope /subscriptions/$sub -Verbose
}
}