Filtering AD property from get-ADUser - powershell

so i am writing a script,
in our company we store users home-directory on network drives,
and when they leave we rename the directory by adding .left to the folder name,
example: "name.left"
and we actually used to do so by finding the user in AD
copying the content of the home directory property and renaming it.
so i got this so far :
$name = Read-Host 'User Name: '
$path = Get-ADUser $name -Properties homedirectory
Rename-Item $path {$name+".left"}
problem is when i get the home-directorys path in get-aduser it gives it with the standart get-aduser output, it just adds it to the output so i tried using filter :
$path = Get-ADUser $name -Properties homedirectory -Filter homedirectory
and it gave me an error, but not for the filter, now it doesn't recognize the user name i gave it.
now, I'm sure that there is a way to filter the string in the property.
and i get a feeling that the third line i wrote might be wrong as-well,
but that's my python brain trying to work with powershell :) so if enyone could help me with that one, i would really appreciate it,
and if anyone can point me to good powershell guides that would be really nice.
EDIT:
so i fixed it to look like that :
$name = Read-Host 'User Name: '
$date = Read-Host 'Date Please: '
do { $path = Get-ADUser $name -Properties homedirectory | select -Expand HomeDirectory $newname = {$name + "LFT" + $date}
Rename-Item $path $newname
Write-Host $name + 'changed' }
while ($name -ne 'exit')
and i get an error that the new name is a script and not a string so it cant run, you know a way to fix it?
Rename-Item : Cannot evaluate parameter 'NewName' because its argument is specified as a script block and there is no
input. A script block cannot be evaluated without input.
At line:6 char:19
+ Rename-Item $path $newname
+ ~~~~~~~~
+ CategoryInfo : MetadataError: (:) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.RenameItemCommand
EDIT2
a fellow employee helped me out and this is the result:
it does exactly what i needed :)
$name = Read-Host 'User Name '
$homefolder = (Get-ADUser $name -Properties HomeDirectory).homedirectory
$date = Get-Date -UFormat "%d.%m.%Y"
ren $homefolder -newname ($homefolder + "_lft_" + $date)

With select-object you can filter out unwanted properties. It will still return an object tho. It has a handy argument named expand that will return single properties value:
$path = Get-ADUser $name -Properties homedirectory | select -Expand HomeDirectory

Related

Change Active Directory titles for all csv users

I would like to change 150 employees their job title.
I have a csvfile called Titletest.csv with columns UserPrincipalName [the user.name under it] and Title [job title under it]
The PowerShell script:
Import-Module ActiveDirectory
$users = Import-Csv -Path c:\scripts\Titlestest.csv | Foreach-Object {
$user = $_.user
$title = $_.title
#Selects the specified user and sets Job Title
Get-ADUser -Filter {(UserPrincipalName -eq $user)} | Set-ADUser -Title $title
}
I get errors saying:
Get-ADUser : Variable: 'user' found in expression: $user is not defined.
At line:14 char:1
+ Get-ADUser -Filter {(UserPrincipalName -eq $user)} | Set-ADUser -Titl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Can someone please advise?
Thank you.
The reason for your error is because $user has no assignment. You are attempting to assign $user the value of a property that does not exist. The header user apparently does not exist in your CSV file. See below for how to convert a csv into PowerShell objects and access their properties.
# Sample CSV TitleTest.csv
UserPrincipalName,Title
covid19#domain.com,Usurper
jsmith#domain.com,CEO
bossman#domain.com,CFO
Import-Csv -Path c:\scripts\TitleTest.csv | Foreach-Object {
$user = $_.UserPrincipalName
$title = $_.Title
Get-ADUser -Filter 'UserPrincipalName -eq $user' | Set-ADUser -Title $title
}
Explanation:
When using Import-Csv on a proper CSV file, the first row of delimited data will be converted to the properties of all input objects. All succeeding rows will be converted to individual objects with the header properties and output as a collection (array) of those objects. If the -Header parameter is used, then values passed into the parameter will become the properties of the objects. It is important to have the same number of delimited items on each row to ensure proper mapping.
Once you are dealing with objects, you can access their property values using the member access operator .. The syntax is object.property. So since you have headers UserPrincipalName and Title, you will need to use $_.UserPrincipalName and $_.Title to access the associated values.
$_ is the current pipeline object within your Foreach-Object {} script block.
Note that you don't technically need to define $user and $title here. You can just access the properties directly from the current object:
Import-Csv -Path c:\scripts\TitleTest.csv | Foreach-Object {
Get-ADUser -Filter "UserPrincipalName -eq '$($_.UserPrincipalName)'" |
Set-ADUser -Title $_.Title
}

Unlocking account from powershell ISE pre made script

I was busy making a script where a variable is declared containing the information of the user that you can enter in a prompt.
I thought of this way when I saw that unlock account can't be done with an e-mail address (Logon name after 2000).
But I can't figure out what I am doing wrong.
This is the code i am running right now.
Import-Module ActiveDirectory
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter your name", "Name", "$env:username")
$Test = Get-ADUser -Filter { EmailAddress -eq $name } | Select SamAccountName
Unlock-ADAccount -Identity $Test
The error i'm getting is
Unlock-ADAccount : Object reference not set to an instance of an object.
At C:\Users\Admcbl\Documents\Powershell.ps1:5 char:1
+ Unlock-ADAccount -Identity $Test
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Microsoft.Activ...ement.ADAccount:ADAccount) [Unlock-ADAccount], NullReferenceException
+ FullyQualifiedErrorId : Object reference not set to an instance of an object.,Microsoft.ActiveDirectory.Management.Commands.UnlockADAccount
You should refer to the SamAccountName property of $Test:
Unlock-ADAccount -Identity $Test.SamAccountName
But why not just pipe the account to the Unlock-ADAccount? Like this:
Get-ADUser -Filter { EmailAddress -eq $name } | Unlock-ADAccount
Here might be a simpler solution for you. Notice I switched the filter so #domain.com isn't needed
Import-Module ActiveDirectory
$name = Read-Host -Prompt "Enter Username "
Get-ADUser -Filter {SamAccountName -eq $name} |
Unlock-ADAccount

PowerShell Active Directory Compare with Text file

I am trying to make a script that compares a list of asset tags in a text file with the computer names in AD, and generate the Description. Exporting it to CSV will come later. As of now though, while the code does work, it gives the following error message. Our computers in AD starts with either L or D, which states whether it's a laptop or desktop, but the list we receive does not contain the L or D in it, which is why you see me putting the "L" + "D" at the front. Is there a better way of doing this?
Code:
Import-Module ActiveDirectory
foreach ($line in Get-Content ComputerNames.txt) {
if($line -match $regex) {
$laptop = "L" + $line
$desktop = "D" + $line
get-ADComputer $laptop -Properties * |select Description
#get-ADComputer $desktop -Properties * |select Description -ErrorAction Ignore }
}
Error:
get-ADComputer : Cannot find an object with identity: 'LD7MWQ12' under: 'DC=ap,DC=o-i,DC=intra'.
At line:9 char:9
+ get-ADComputer $laptop -Properties * |select Description
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (LD7MWQ12:ADComputer) [Get-ADComputer], ADIdentityNotFoundException
+ FullyQualifiedErrorId : Cannot find an object with identity: 'LD7MWQ12' under: 'DC=ap,DC=o-i,DC=intra'.,Microsoft.ActiveDirectory.Management.Com
mands.GetADComputer
Probably a more efficient way to do this But the below works:
Import-Module ActiveDirectory
foreach ($line in Get-Content ComputerNames.txt) {
Get-ADComputer -Filter * -Property Description | Where {$_.samaccountname -Like "*$line"} | select Description
}
For every line in the computernames.txt object it will go and find the AD Object that is like the $line variable and then select the Description for that object
The slow bit is going to be the network link to AD, you really only want to do that once if possible. Unless you have huge numbers of computers in AD, it would be better to pull down all the computers and then compare them locally against the text file.
Also if you're pulling information from AD, don't bring any more than you need, the network traffic and memory overhead is wasted, so instead of Properties *, just add in the description
Import-Module ActiveDirectory
# AD query which will get all computers with names starting D or L
$ADFilter = "Name -like 'D*' -or Name -like 'L*'"
$ADComputers = Get-ADComputer -filter $ADFilter -Properties Description | Select Name, Description
$NamesFromFile = Get-Content ComputerNames.Txt
# Filter the AD Computers where the name without the first character is
# mentioned in the file
$ADComputers | Where-Object { $_.Name.SubString(1) -in $NamesFromFile } | Export-Csv -NoTypeInformation out.csv

Using PowerShell to update AD users from CSV file

I'm using a PowerShell script to add some information to all users in AD. For some reason, I keep getting an error message if the user has a apostrophe in their name (e.g Tim O'Reilly).
How can I format the script so it will include names with apostrophe ?
My script:
# Import AD Module
Import-Module ActiveDirectory
write-Host 'Starting to update AD Attributes.......' -NoNewline -ForegroundColor Yellow
# Import CSV into variable $users
$users = Import-Csv -Path C:\Scripts\users.csv
# Loop through CSV and update users if the exist in CVS file
foreach ($user in $users) {
#Search in specified OU and Update existing attributes
Get-ADUser -Filter "displayName -eq '$($user.Name)'" -Properties * -SearchBase "DC=My,DC=domain,DC=com" |
Set-ADUser -Company $($user.Email)
}
Write-Host 'done!' -ForegroundColor Green
And this is the error message I'm getting:
Get-ADUser : Error parsing query: 'displayName -eq 'Tim O'Reilly''
Error Message: 'syntax error' at position: '29'. At
C:\Scripts\Update-information\Update-Users-2.ps1:13 char:1
+ Get-ADUser -Filter "displayName -eq '$($user.Name)'" -Properties * -S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Micr
osoft.ActiveDirectory.Management.Commands.GetADUser
I'd really appreciate any help I can get here.
Thank you,
You can use some custom delimiter in your csv file instead of modifying your script. Just divide your data with custom char like ":" (Tim : O'Reilly), and add delimiter switch for import-csv cmdlet, like
$users = Import-Csv -Path C:\Scripts\users.csv -Delimiter :

powershell, Variable: '_' found in expression: $_

I am fairly new to powershell and I am currently employing it to work around a few administration tasks for the Helpdesk.
I have a problem with trying to move an AD object (forgive me if the following terminology is used incorrectly) based on the property of on object from an imported CSV.
The CSV is:
UserPrincipalname,UserToAccess,DaysToLive
joe#company.com,dave#company.com,90
and so on...
I then pass the array through a ForEach loop to move the AD account:
foreach ($line in $import) {Get-ADUser -filter {userPrincipalName -eq $_.UserToAccess} -SearchBase "DistinguishedName of OU" | Move-ADObject -TargetPath 'DistinguishedName of OU'}
Subsequently I am getting the following error:
Get-ADUser : Variable: '' found in expression: $.UserToAccess is not
defined. At D:\jason\EnableArchiveAccess.ps1:17 char:29
+ foreach ($line in $import) {Get-ADUser -filter {userPrincipalName -eq $.UserToA ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : Variable: '' found in expression: $_.UserToAccess is not defined.,Microsoft.ActiveDirec
tory.Management.Commands.GetADUser
I have been able to use the above logic to unhide users from the GAL and I have checked the array and the properties are there as noteproperties.
I assume it's because I am using not AD variables in the command but any help would be much appreciated but if I find the answer sooner I will post back.
Just looking at that, I think you need to change
$_.UserToAccess
to
$line.UserToAccess
The other alternative would be:
$import | foreach{
Get-ADUser -filter {userPrincipalName -eq $_.UserToAccess} `
-SearchBase "DistinguishedName of OU" `
| Move-ADObject -TargetPath 'DistinguishedName of OU'}
This is one of the common mixups in PowerShell. There are in fact two foreach "keywords". One is alias of the Foreach-Object cmdlet and is used as such:
$Items = 1,2,3
$Items | foreach { $_ }
The $_ in the example means the current object. That is 1 on first pass, 2 on second pass and 3 on the third.
The second foreach is keyword and is used as such
$Items = 1,2,3
foreach ($item in $items) {
$item
}
In this example the $item represents the current object.
So in your example you have to use $list instead of $_.