Adding users to AD with powershell - powershell

I have a question about how to add users to AD using powershell, ive written a small script but i always get an error when i try to create a user.
$connection= "LDAP://ou=Users, dc="domain", dc="com"
$OU = [adsi] $Connection
$User = $OU.Create("user", "Test Person")
$User.Put("Firstname", "Test")
$User.Put("Surname", Person)
$User.Put("Email", "email#e.com")
$User.SetInfo()
I think my connection string is wrong, but i tried different ways already and still no success. This im trying locally. Need to get it working but then normally my AD is on different server, how to do it then?
Thanks in advance.

Give this a try:
$container = [ADSI] "LDAP://dc.sopragroup.lan/cn=Users,dc=sopragroup,dc=lan"
$UserName = "user"
$User = $container.Create("User", "cn=" + $UserName)
$User.Put("sAMAccountName", $UserName)
$User.Put("givenName", "Test")
$User.Put("sn", "Person")
$User.Put("mail", "email#e.com")
$User.SetInfo()
$User.psbase.InvokeSet('AccountDisabled', $false)
$User.SetInfo()
$User.SetPassword("P#55w0rd")

Here is another example (#Andy Arismendi was first) with some other details:
If you want to give a user and a password (log onto the server with a different user than the current one), you can use the DirectoryEntry constructor
An error that is commonly done is that when you create an object in a directory, the name that represent this object in the directory tree is built with the construction : attribute=value. In Active-Directory you can't choose the the attribute it's imposed by the schema. For a user or an inetOrgPerson it's CN for an organizationalUnit it's OU. In your case the name of the object is CN=Test Person.
You'll find here under the creation of an OU and a user.
Clear-Host
$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://192.168.234.200:389/dc=dom,dc=fr","administrateur#dom.fr","admin")
# Create an OU
$Monou = $dn.create("OrganizationalUnit", "ou=Monou")
#$Monou.Description = "Une description"
$Monou.put("Description", "Une description")
$Res = $Monou.Setinfo()
# Create a user
$objUtilisateur = $Monou.create("inetOrgPerson", "cn=Marc Assin")
$objUtilisateur.setinfo()
$objUtilisateur.samaccountname = "Massin"
$objUtilisateur.givenName = "Marc"
$objUtilisateur.sn = "Assin"
#$objUtilisateur.displayName = $objUtilisateur.givenName + " " + $objUtilisateur.sn
$objUtilisateur.userPrincipalName = "Massin#dom.fr"
# Pu the state of the account#$objUtilisateur.SetPassword("test.2010")
$objUtilisateur.pwdLastSet = 0
$objUtilisateur.userAccountControl = 544
# Write the datas of the user
$objUtilisateur.SetInfo()

Related

New-OktaApp in OktaAPI Module will not error out but only seems to freeze

I am attempting to use New-OktaApp to make a new okta application. It runs without errors, however once it runs powershell fails to run any further and must be forced closed.
Has anyone experienced this before?
If you have used this in the past can you show me an example of how would got it to run and produce an app?
Import-Module "pathtomodule\OktaAPI"
Connect-Okta "MyAPIToken" "MyOrg"
New-OktaApp #{
name = "name";
label = "label";
}
There are many examples in the GH site, for example
https://github.com/gabrielsroka/OktaAPI.psm1/blob/master/CallOktaAPI.ps1#L12-L33
function Add-SwaApp() {
$user = Get-OktaUser "me"
# see https://developer.okta.com/docs/api/resources/apps#add-custom-swa-application
$app = #{
label = "AAA Test App"
settings = #{
signOn = #{loginUrl = "https://aaatest.oktapreview.com"}
}
signOnMode = "AUTO_LOGIN"
visibility = #{autoSubmitToolbar = $false}
}
$app = New-OktaApp $app
# see https://developer.okta.com/docs/api/resources/apps#assign-user-to-application-for-sso
$appuser = #{id = $user.id; scope = "USER"}
Add-OktaAppUser $app.id $appuser
}

How to add a certificate to a local Outlook contact using Powershell?

I am trying to sort out current contacts in Outlook to replace encryption certificates. But it is not clear how to prepare the object?
# В var $contactList collect contacts from Outlook
foreach ( $name in $contactList ) {
$PR_x509_Certificate = ('http://schemas.microsoft.com/mapi/proptag/0x3A701102');
# Create new contact
$NewContact = $Outlook.CreateItem('olContactItem');
# Get email, name, fullname from old contact
$NewContact.Email1Address = $name.Email1Address;
$NewContact.FullName = $name.FullName;
$NewContact.FirstName = $name.FirstName;
# Import certificate from из .cer file
$NewCertUser = New-Object system.security.cryptography.x509certificates.x509certificate2;
$NewCertUser.Import($PathToCerFile);
# Try add sertificate, but no success :(
$result = $NewCertUser.RawData;
$o = New-Object BuildProperty($result);
$NewContact.PropertyAccessor.SetProperty($PR_x509_Certificate, $o);
# Save new contact
$NewContact.Save();
# Delete old
$name.Delete();
}
I'm trying to update this:
It should be possible to do that on the users certificate store certmgr.msc without even touching Outlook:

How to log "new pnp devices" events to console on Windows?

I want to write something like nestat (that log new tcp connections to console) but for pnp devices with powershell.
Is there an API method "to subscribe to some kind of events bus" specific to PnP and get "connected" and "disconnected" events?
Or only one way to achive this is looping with Get-PnpDevice and "manually" seacrh for the differences?
You can use WMI events to do this. For example, here is one way to do it (seems over-complicated, so maybe someone can improve on it):
$addIdentifier = "WMI.PnpAddEvent"
$removeIdentifier = "WMI.PnpRemoveEvent"
$addAction = { $pnpEntity = $EventArgs.NewEvent.TargetInstance; Write-Host "`nPNPEvent: Plugged In`nCaption: $($pnpEntity.Caption)`nPNPDeviceID: $($pnpEntity.PNPDeviceID)`n" }
$addQuery = "SELECT * FROM __instancecreationevent WITHIN 5 WHERE targetinstance isa 'Win32_PnPEntity'"
$removeAction = { $pnpEntity = $EventArgs.NewEvent.TargetInstance; Write-Host "`nPNPEvent: Unplugged`nCaption: $($pnpEntity.Caption)`nPNPDeviceID: $($pnpEntity.PNPDeviceID)`n" }
$removeQuery = "SELECT * FROM __instancedeletionevent WITHIN 5 WHERE targetinstance isa 'Win32_PnPEntity'"
$addEventArgs = #{
Query = $addQuery
SourceIdentifier = $addIdentifier
SupportEvent = $true
Action = $addAction
}
$removeEventArgs = #{
Query = $removeQuery
SourceIdentifier = $removeIdentifier
SupportEvent = $true
Action = $removeAction
}
Register-WmiEvent #addEventArgs
Register-WmiEvent #removeEventArgs
Now, when you add/remove a device, you'll get output like this in the console:
PNPEvent: Unplugged
Caption: Apple iPhone
PNPDeviceID: USB\VID_05AC&PID_12A8&MI_00\E&2491F388&0&0000
PNPEvent: Plugged In
Caption: Apple iPhone
PNPDeviceID: USB\VID_05AC&PID_12A8&MI_00\E&2491F388&0&0000
A couple of things to keep in mind:
The event registrations last for the current session only
You need to run this from an elevated prompt
As mentioned, the registrations should be cancelled when your session ends, but if you want to do it manually, you can do it like this:
$addIdentifier, $removeIdentifier | ForEach-Object { Unregister-Event -Force -SourceIdentifier $_ }

Trying to use PowerShell to add a Parent Link to a TFS Task

I am trying to add a parent link when I create TFS task via powershell. However, I am only able to add a related link:
function Create-New-WorkItem($projName, $taskType, $title, $state, $assignedTo, $iterationPath, $activity, $BLItem)
{
$tfs = Get-TfsServer
$ws = $tfs.GetService([type]"Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore")
$proj = $ws.projects[$projName]
$workitem = $proj.workitemtypes[$taskType].newworkitem()
$workitem.open()
$workitem.title = $title
$workitem.state = $state
$workitem.fields["Assigned To"].value = $assignedTo
$workitem.iterationpath = $iterationPath
$workitem.fields["Activity"].value = $activity
$id = Get-Parent-Link $BLItem
$workitem.links.add($id.ID)
$workitem.close()
$workitem.save()
}
function Get-Parent-Link($backLogItemName)
{
$tfs = Get-TfsServer
$WIQL = #"
SELECT [System.Id]
FROM WorkItems
where [System.Title] = '$backLogItemName'
"#
return $tfs.wit.query($WIQL)
}
How can I add the link as a parent instead of a related?
After some trial and error I finally found a way to accomplish linking a new work item as a child to a parent item i.e. backlog item.
$ws = $tfs.GetService([type]"Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore")
$linkType = $ws.WorkItemLinkTypes[[Microsoft.TeamFoundation.WorkItemTracking.Client.CoreLinkTypeReferenceNames]::Hierarchy]
Add the workitem id of the parent you want to link the new child workitem to and create a workitemlink object:
$link = new-object Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemLink($linkType.ReverseEnd, 1234)
You can then add the link to a workitem:
$workitem.WorkItemLinks.Add($link)
$workitem.save()
You need to create a different link type object. A good exercise of the API can be found on Shai's blog.
http://blogs.microsoft.co.il/shair/2010/02/27/tfs-api-part-22-create-link-between-work-item-parent-child-etc/
The PowerShell for this is almost identical.

Function Returned Data Type

I've written a function that will create an Active Directory user based on the supplied parameters. The user creates fine; however the problem that I'm running into is the returned data from the function. I'm merely looking to return a boolean response based on if the user was created or not. Instead, it's passing back an array.
A sample of the function:
Function CreateUser () {
param([string]$ParentDN,
[string]$FirstName,
[string]$LastName,
[string]$Username,
[string]$EmailAddress,
[string]$Password);
Try {
$UserOU = [ADSI] "LDAP://$LDAPServer/$ParentDN";
$NewUser = $UserOU.Create("user","cn=$Username");
$NewUser.Put("sAMAccountName","$Username");
$NewUser.Put("givenName","$FirstName");
$NewUser.Put("sn","$LastName");
$NewUser.Put("UserPrincipalName","$Username#$NetworkFQDN");
$NewUser.Put("mail","$EmailAddress");
$NewUser.SetInfo();
$NewUser.SetPassword("$Password");
$NewUser.SetInfo();
$flag = $NewUser.userAccountControl.Value -bxor 65536; #Password Never Expires flag
$NewUser.userAccountControl = $flag;
$NewUser.InvokeSet("AccountDisabled","False") #Enables Account
$NewUser.SetInfo();
return $true;
}
Catch {
return $false;
}
}
And I'm calling it using the following syntax:
$CreateUserResults = CreateUser -FirstName $User_FirstName -LastName $User_LastName -EmailAddress $User_EmailAddress -ParentDN $User_ParentOU -Password $User_Password -Username $User_SamAccountName
Any advise or direction would be appreciated.
Thanks,
Ryan
I'm not where I can test, but I suspect those setinfo() methods are returning data that needs to be redirected to $null to prevent it from being returned by the function.