update/modify ldap user attribute powershell - powershell

My powershell script will update the ldap user attribute for non-Microsoft technology(Active Directory) and i faced some issue on it. This is my reference link for how to update non-Microsoft technology(Active Directory)
This is part of my powershell script
if($time -ne $null)
{
$eD = $time.AddDays(7)
write-host "The date after : "$eD
Set-ADUser xxxxx -AccountExpirationDate $eD
$a = New-Object "System.DirectoryServices.Protocols.DirectoryAttributeModification"
write-host $a
$a.Name = "String1"
write-host $a
$a.Operation = [System.DirectoryServices.Protocols.DirectoryAttributeOperation]::Add
write-host $a
#add values of the attribute
$a.Add("set")
write-host $a
$r.Modifications.Add($a)
$re = $ldapserver.SendRequest($r);
if ($re.ResultCode -ne [System.directoryServices.Protocols.ResultCode]::Success)
{
write-host "Failed!"
write-host ("ResultCode: " + $re.ResultCode)
write-host ("Message: " + $re.ErrorMessage)
}
}
Here are my script output
The date after 7 days : 14/1/2020 11:40:03 AM
0
set
You cannot call a method on a null-valued expression.
At D:\deployment\test_ck.ps1:94 char:25
+ $r.Modifications.Add($a)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
i cant figure out why $a is having a null value
This is what assigned to $r
$Domain='ou=test,ou=tes1,o=test2'
$fDomain ='(objectClass=User)'
$sDomain = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $Domain,$fDomain,
$r = (new-object "System.DirectoryServices.Protocols.ModifyRequest")
$r = $sDomain

The simple PowerShell script below uses the Get-ADUser cmdlet from the ActiveDirectory PowerShell module to retrieve all the users in one OU and then iterate the users to set a couple of AD properties.
# Get all users in the Finance OU.
$FinanceUsers = Get-ADUser -Filter * -SearchBase "OU=Finance,OU=UserAccounts,DC=FABRIKAM,DC=COM"
# Iterate the users and update the department and title attributes in AD.
The example uses the Instance parameter of Set-ADUser to update each user in the OU. The parameter allows any modifications made to the ADUser object to go to the corresponding Active Directory object while only updating object properties that have changed.

Related

Null troubles with PowerShell AD script for creating new users

Been smooth sailing with creating users for my domain, now I'm trying to set the uidNumber based on what the last 4 digits of the generated objectSid. Might be a simple solution but hoping for some help.
The rest of the code runs fine until we get to the '$last4' variable so I snipped to make it shorter, but if putting the whole script helps, happy to do so.
Import-Module ActiveDirectory
$firstname = Read-Host -Prompt "Please enter the first name"
$lastname = Read-Host -Prompt "Please enter the last name"
$location = Read-Host -Prompt "Please enter user location (LA/NY)"
$path = "OU=Users,OU=$location,OU=GS,DC=random,DC=com"
New-ADUser `
-snip
Add-ADGroupMember `
-Identity "$snip" -Members $username
$user = Get-ADUser -Identity $username
$objectSid = $user.objectSid
$last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length - 4)
$newUidNumber = "71$last4DigitsOfObjectSid"
Set-ADUser -Identity $username -Replace #{'uidNumber'=$newUidNumber}
Error
You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Desktop\newtry.ps1:31 char:1
$last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length - 4)
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull
objectSid is not an attribute that Get-ADUser returns by default, the attribute you're looking for is just SID. $objectSid in your snippet is actually null, hence the error you're having.
Also, Substring is a String method and SID and objectSid are instances of SecurityIdentifier. This class does not have a Substring method. You would need to refer to the .Value property:
$sid = $user.SID
$last4DigitsOfObjectSid = $sid.Value.Substring($sid.Value.Length - 4)
A much easier way of getting the last 4 digits would be with -replace which will coerce the SecurityIdentifier to a string before replacing:
$sid = $user.SID
$last4DigitsOfObjectSid = $sid -replace '.+(?=.{4}$)'
Or using -split which would also work for SIDs having less than 4 digits:
$last4DigitsOfObjectSid = ($sid -split '-')[-1]

unable to export from powershell to CSV [duplicate]

This question already has answers here:
Writing console output to a file - file is unexpectedly empty
(2 answers)
Closed 3 years ago.
Pls help a poor newby over here...below is my script with the errors at the bottom of the script. The main issue is that i am unable to export to CSV
PS C:\Users\LUPUWANA> $logs = get-eventlog system -ComputerName cafeserver -source Microsoft-Windows-Winlogon -After (Get-Date).AddDays(-7);
$res = #(); ForEach ($log in $logs) {if($log.instanceid -eq 7001) {$type = "Logon"} Elseif ($log.instanceid -eq 7002){$type="Logoff"} Else {Continue} $res += New-Object PSObject -Property #{Time = $log.TimeWritten; "Event" = $type; User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}};
Export-Csv -Path C:\users\lupuwana\desktop\events.csv
oss get-help -detailed
Supply values for the following parameters:
InputObject:
oss : Cannot process argument transformation on parameter 'Width'. Cannot convert value "get-help" to type "System.Int32". Error: "Input string was not in a
correct format."
At line:4 char:5
+ oss get-help -detailed
+ CategoryInfo : InvalidData: (:) [oss], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,oss
Your loop builds an object called $res, so assuming that's the object you wish to export to CSV, you need to supply that object to the Export-Csv Cmdlet:
Export-Csv -InputObject $res -Path C:\users\lupuwana\desktop\events.csv
You may also wish to add the -NoTypeInformation option too otherwise your file will contain an extra header row describing the object type.

Powershell LDAP Filter with DirectorySearcher

I am using the DirectorySearcher class to find a single user. The criteria should be that the objectCategory is a user, and that his password is not set to never expires.
After some searching, I have come up with this:
$searcher = New-Object System.DirectoryServices.DirectorySearcher
$searcher.Filter = "(&(objectCategory=User)(samAccountName=$env:username)(!(userAccountControl:1.2.840.113556.1.4.803:=65536)))"
where userAccountControl:1.2.840.113556.1.4.803:=65536 should be for users whose password never expires.
Finally I do:
$user = $searcher.FindOne().GetDirectoryEntry()
But it says that I cannot call a method on a null-valued expression. I think I am using the parentheses correctly. So then could it be that I can't use the ! operator for this?
Also note that I could use the get-aduser command, like so:
get-aduser -filter * -properties samAccountName, PasswordNeverExpires | where { $_.passwordNeverExpires -eq "true" } | where {$_.enabled -eq "true"} | where {$_.samAccountName -eq $env:username}
but in this instance it would be preferable to use the DirectorySearcher instead like shown above.
In fact your code is working, but when the $searcher.FindOne() return nothing, that is to say, when the filter return nothing, the GetDirectoryEntry() method give :
> You cannot call a method on a null-valued expression. At line:1 char:1
> + $searcher.FindOne().GetDirectoryEntry()
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidOperation: (:) [], RuntimeException
> + FullyQualifiedErrorId : InvokeMethodOnNull
Try :
$user = $searcher.FindOne()
if($user -ne $null) {$user.GetDirectoryEntry()} else {write-host "Niet"}

New-ADGroup - Using -join and Variable in a PS cmdlet?

I've been delving into PS scripting over the last few months and I was attempting to script out AD group creations. Right now, I'm asking the following:
$GroupNameRO = Read-Host -Prompt 'What Read Only AD group name do you want to use'
$GroupNameRW = Read-Host -Prompt 'What Read Write AD group name do you want to use'
$RequestNum = Read-Host -Prompt 'Input the request number for this share'
Then putting it all together here:
New-ADGroup -name $GRPnameRW -path 'OU=Security,OU=Groups,DC=test,DC=local' -groupscope 'global' -Description -join('Request #',$RequestNum)
and finally receiving this error:
New-ADGroup : A positional parameter cannot be found that accepts argument 'System.Object[]'.
At line:1 char:1
+ New-ADGroup -name $GRPnameRW -path 'OU=Security,OU=Groups,DC=test,DC=local' -g ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-ADGroup], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.NewADGroup
Has anyone used the -join within a parameter / am I formatting everything correctly?
... -Description (('Request #',$RequestNum) -join 'something')
You need to do it like this. Think of it this way:
-Description (expression)
because Description has to be a result of an expression we need to enclose the expression in (), everything inside () gets executed first.
And for -join to work we need to feed values into it, so:
(values) -join 'what_are_we_joining_with'
ps. you don't really need () around values you are passing to join in some cases: 'a','b' -join "" works. But I thinks its nicer this way and more intuitive with ().
Your value for the -Description parameter is incorrect. This should get you the result you're looking for:
New-ADGroup -name $GRPnameRW -path 'OU=Security,OU=Groups,DC=test,DC=local' -groupscope 'global' -Description "Request #$RequestNum"

how to add data from a file to an open variable in powershell

I am trying to add an open varible to this command so when the data pulls from line 24 it adds it to the variable and makes it executable.
$data = Get-Content "C:\Users\bgriffiths\Documents\test.dat"
$data[24]
I have tried adding different formats to do this and nothing seems to work.
one command i tried was
invoke-command sql -query = $data
I get an error telling me
Invoke-Command : A parameter cannot be found that matches parameter name 'query'.
At line:4 char:26
+ invoke-command sql -query <<<< = $data
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
another command I have been trying to run is
$Command.CommandType.text = $data
the only error I get from this is
Property 'text' cannot be found on this object; make sure it exists and is settable.
At line:10 char:30
+ $Command.CommandType. <<<< text = $data
+ CategoryInfo : InvalidOperation: (text:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
I am at a lost on how to import file data into the script and have it run it.
I figured out how to run commands for sql through my powershell I had to actaully import the assembly list for the sql ps and then I was able to run the Invoke-SqlCmd
the script to add the information for sqlps to your windows ps is -
$ErrorActionPreference = "Stop"
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
throw "SQL Server Powershell is not installed."
}
else
{
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}
#
# Preload the assemblies. Note that most assemblies will be loaded when the provider
# is used. if you work only within the provider this may not be needed. It will reduce
# the shell's footprint if you leave these out.
#
$assemblylist =
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.Dmf ",
"Microsoft.SqlServer.SqlWmiManagement ",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.SmoExtended ",
"Microsoft.SqlServer.Management.RegisteredServers ",
"Microsoft.SqlServer.Management.Sdk.Sfc ",
"Microsoft.SqlServer.SqlEnum ",
"Microsoft.SqlServer.RegSvrEnum ",
"Microsoft.SqlServer.WmiEnum ",
"Microsoft.SqlServer.ServiceBrokerEnum ",
"Microsoft.SqlServer.ConnectionInfoExtended ",
"Microsoft.SqlServer.Management.Collector ",
"Microsoft.SqlServer.Management.CollectorEnum"
foreach ($asm in $assemblylist)
{
$asm = [Reflection.Assembly]::LoadWithPartialName($asm)
}
#
# Set variables that the provider expects (mandatory for the SQL provider)
#
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
#
# Load the snapins, type data, format data
#
Push-Location
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location
Write-Host -ForegroundColor Yellow 'SQL Server Powershell extensions are loaded.'
Write-Host
Write-Host -ForegroundColor Yellow 'Type "cd SQLSERVER:\" to step into the provider.'
Write-Host
Write-Host -ForegroundColor Yellow 'For more information, type "help SQLServer".'
the link where I found this is http://blogs.msdn.com/b/mwories/archive/2008/06/14/sql2008_5f00_powershell.aspx