Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Help Creating New AD User in Powershell from Existing User

$
0
0

So I do this: 

 

PS C:\Users\Administrator>$userinstance= Get-ADUser -Identity testuser

and make sure it's the right user by doing 

PS > $userinstance

Then, I try and create a new user based on that user in the same OU 

PS C:\Users\Administrator> New-ADUser -SamAccountName "garyooo" -name "garyo" -Instance $userinsance
New-ADUser : The password does not meet the length, complexity, or history requirement of the domain.
At line:1 char:11+ New-ADUser <<<< -SamAccountName "garyooo" -name "garyo" -Instance $userinsance+ CategoryInfo     : InvalidData: (CN=garyo,CN=Users,DC=gary,DC=local:String) [New-ADUser], ADPasswordComplex
  ityException+ FullyQualifiedErrorId : The password does not meet the length, complexity, or history requirement of the domain.
  ,Microsoft.ActiveDirectory.Management.Commands.NewADUser

ok, ok, so I do this: 

PS C:\Users\Administrator> New-ADUser -SamAccountName "garyoj" -Instance $userinsance -PasswordNotRequired $true

cmdlet New-ADUser at command pipeline position 1
Supply values for the following parameters:
Name:

Hmm, ok, it's asking for me for a name. ok. 

PS C:\Users\Administrator> New-ADUser -SamAccountName "garyoj" -name "garyoj" -Instance $userinstance -PasswordNotRequire
d $true
PS C:\Users\Administrator>

Oh goodie! It worked! 

....except the user isn't in the same container as $userinstance

 

WHy isn't the new user in the same OU as $userinstance? 


Assistance with proper syntax for copying Distinguishing Name from user to user.

$
0
0

Hello I am trying to create a script that would not only add the corresponding groups from an a Template but add them to the correct OU's this has become a bit challenging for me as a newbie when when it comes to Powershell. I keep getting an error that reads as followed:

+ Set-ADUser -SamAccountName $UserToAdd -Instance $DN -Path "$OUDN"
    + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser

I feel as it has something to do with the Set-ADUser cmdlet but New-ADUser doesn't make sense to me as the AD user would of had already been created from another point and invoked by a separate script. 

Here is the script, can someone assist me on proper syntax as I am having a rough time getting this to work and it's the only piece that is not working properly.

Thank You.

# Import the AD powershell module
Import-Module activedirectory

# Prompt the user for the account to associate.
$SamAccountName = $UserToAdd
$UserToAdd = Read-Host -Prompt "`n`nEnter the SamAccount to be Associated"
$user = $(try{Get-ADUser $UserToAdd} catch {$null})
# If we could not find a user (null returned) then output to the user we did not find anything
if ($user -eq $null) {Write-Host "Username " $UserToAdd " not found."}

# Prompt the user for the account to copy
$UserToCopyInput = Read-Host -Prompt "`nUser to copy: "
$UserToCopy = $(try {Get-ADUser $UserToCopyInput} catch {$null})

# This block grabs the group membership of the user to copy and adds the new user to those groups
Get-ADUser -Identity $UserToCopy -Properties memberof |
Select-Object -ExpandProperty memberof |
Add-ADGroupMember -Members $UserToAdd

# If we could not get anything keep looping until we do
while($UserToCopy -eq $null) {
	Write-Host "Could not find $UserToCopyInput, try again."
	$UserToCopyInput = Read-Host -Prompt "User to copy"
	$UserToCopy = $(try {Get-ADUser $UserToCopyInput} catch {$null})
}

# Set the path for our user object from the user to copy
$userinstance = Get-ADUser -Identity $UserToCopyInput
$DN = $userinstance.distinguishedName
$OldUser = [ADSI]"LDAP://$DN"
$Parent = $OldUser.Parent
$OU = [ADSI]$Parent
$OUDN = $OU.distinguishedName
Set-ADUser -SamAccountName $UserToAdd -Instance $DN -Path "$OUDN"

# Output results to the screen
Get-ADUser $UserToAdd -Properties DistinguishedName, GivenName, Name, Enabled, SamAccountName


Powershell GUI Form Full Screen

$
0
0

Trying to create a simple form with the screen full size, but so far could not get the desired result. Can someone please help

Add-Type -AssemblyName System.Windows.Forms

[System.Windows.Forms.Application]::EnableVisualStyles()

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '814,593'
$Form.text                       = ""
$Form.BackColor                  = "#ffffff"
$Form.TopMost                    = $false
$form.ControlBox = $false

Would like the form to be displayed in full screen when launched.

Powershell: Reparse different area of a Security event after a successful filter

$
0
0

Greetings,

I have been able to setup a script to retrieve the following information from security event 4728 when someone is added to an AD group:

'Group', 'User Added', 'Added By'

I'd like to limit the returns to include only Administrator groups, but still include the fields above.

I was able to successfully perform the filter on the events, so that it will only return events that pertained to Admin groups, but was then unable to then get the previous output of the 'Group', 'UserAdded' and 'Added By', fields.

Here is the script that returns the info for all of the AD groups.

$event = Get-WinEvent -FilterHashtable @{Logname='Security'; ID = 4728}

Foreach ($events in $event) {
    $PCName = $env:COMPUTERNAME
    $EmailBody = $event | select @{Name='AddedBy    ';Expression={([xml]$_.ToXml()).Event.EventData.Data[6].'#text'}}, 
                      @{Name='Group           ';Expression={([xml]$_.ToXml()).Event.EventData.Data[2].'#text'}},@{Name='UserAdded               ';Expression={([xml]$_.ToXml()).Event.EventData.Data[0].'#text'}} | out-string 
    $EmailFrom = "noreply@domain.ext"
    $EmailTo = "DistList@domain.ext" 
    $EmailSubject = "User added to Security Group on $PCName"
    $SMTPServer = "smtpserver"
    Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -body $EmailBody -SmtpServer $SMTPServer
}

I know that by performing the filter I am removing the fields from the conversation, I just don't know how to get them back

without bypassing the filter.

Any help would be appreciated.

Thanks,

Flynn


VB Script Output - Need to be displayed for all users logged into a desktop

$
0
0

Hi Team,

I need to post a message to logged on user via VB script.

Currently, I use an desktop admin account to push this script to desktop and executing the same. This works without any issues!

However, results are NOT being displayed to an end user. Looks like, it works within Administrator's profile.

Requesting your help to improve our script to display message to ALL LOGGED IN USERS of a desktop/system.

Script Info -

msgbox"Dear User, You have raised an incident to fix Outlook profile issues, where our automations will invoke remediation scripts at backend. In the meantime, please leverage https://www.mail.xxx.com/owa to check your emails accordingly!"

Script For Active Directroy Custom Reports

$
0
0

Hi Team,

We have one requirement to setup a server where IT team member can extract Custom Active Directory report ( like users count, other attributes).  Is there any  powershell script we can use to create this AD custom report server?

Regards,

Nirmal Singh


Nirmal Singh IT Administrator

Power shell script error

$
0
0

Hey Everyone,

I am using a batch file to launch a power shell script and the script fails with the error below. 

Missing ')' in method call.
At C:\Installed Software\RestartMicros.ps1:12 char:13
+ $msg.To.Add( <<<< â?oposadmin@wgresorts.comâ??)
    + CategoryInfo          : ParserError: (CloseParenToken:TokenId) [], Paren
   tContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

But when I run the same commands in power shell it works fine. This is the line in my batch file where I call it.

PowerShell -NoProfile -ExecutionPolicy Bypass -File RestartMicros.ps1

And this is the power shell script. 

$comp =$env:COMPUTERNAME
$filepath ="C:\Installed Software\Reports\"
$filename =$filepath+=$comp+="RestartMicros.err"
$smtpServer = “smtp.company.com”

$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)


$msg.From = “Micros_Reports@company.com”
$msg.To.Add(“posadmin@company.com”)
$msg.Subject = “Restart Micros Error”
$msg.Body = “This restaurant had a problem stopping the Micros DB and was not restarted”
$msg.Attachments.Add($att)

$smtp.Send($msg)

I literally copied this from another script that runs every night and changed the file name and path, report name and the outlook address and now it fails. 

Add the same header again at end of a script

$
0
0
$getcsv = import-csv $filepath -Delimiter ";" -Header "$Enhet" ,"$Ledigt", "$Totalt" ,"$Nyttjat ", "$ram","Script startat vid","$Vem" |export-csv v:\logg.csv -NoTypeInformation
If i run this part a second time it wont add the headers to the bottom row, how can i fix this


How to set errorlevel 1

$
0
0

Hi guys,

I have following script. I need to generate errorlevel 1 when a file in a specific folder is older than 24h

Have no clue how to do it, everything i try gives me the result: ECHO off!

@echo off &setlocal

REM folder to be checked
set "Folder=D:\test\test"

REM accepted maximum age in minutes
set "MaxAge=1141"

pushd "%Folder%" ||goto :eof
call :GetInternationalSettings DateOrder DateSeparator TimeSeparator
call :GetNumberOfMinutes %DateOrder% "%DateSeparator%" "%TimeSeparator%" "%date%" "%time%" CurrentMinutes
for /f "delims=" %%a in ('dir /a-d /b') do (
  set "filename=%%a                                       "
  setlocal enabledelayedexpansion
  call :GetNumberOfMinutes %DateOrder% "%DateSeparator%" "%TimeSeparator%" %%~ta FileMinutes
  set /a age=CurrentMinutes - FileMinutes
  if !age! gtr %MaxAge% (
    set /a age/=1441
    echo %ErrorLevel%

  )
  endlocal
)
popd
pause
goto :eof

:GetInternationalSettings
setlocal
for /f "tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v iDate') do set "iDate=%%a"
for /f "tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sDate') do set "sDate=%%a"
for /f "tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sTime') do set "sTime=%%a"
endlocal &set "%~1=%iDate%" &set "%~2=%sDate%" &set "%~3=%sTime%"
goto :eof

:GetNumberOfMinutes
setlocal
set "iDate=%~1" &set "sDate=%~2" &set "sTime=%~3" &set "strDate=%~4" &set "strTime=%~5"
for /f "tokens=2" %%i in ("%strDate%") do set "strDate=%%i"
for /f "tokens=1-4 delims=%sDate%" %%a in ("%strDate%") do (
  if %iDate%==0 set /a mm=100%%a %% 100,dd=100%%b %% 100,yy=10000%%c %% 10000
  if %iDate%==1 set /a dd=100%%a %% 100,mm=100%%b %% 100,yy=10000%%c %% 10000
  if %iDate%==2 set /a yy=10000%%a %% 10000,mm=100%%b %% 100,dd=100%%c %% 100
)
for /f "tokens=1,2 delims=%sTime% " %%a in ("%strTime%") do (set /a hh=100%%a %% 100 &set "nn=%%b")
if "%nn:~-1%" equ "p" if "%hh%" neq "12" set /a hh+=12
if "%nn:~-1%" equ "a" if "%hh%" equ "12" set /a hh=0
for /f "delims=ap" %%a in ("%nn%") do set /a nn=100%%a %% 100
set /a z=(14-mm)/12,y=yy+4800-z,x=mm+12*z-3,d=153*x+2,d=d/5+dd+y*365+y/4-y/100+y/400-2472633,n=d*1440+hh*60+nn
endlocal &set "%~6=%n%"
goto :eof

 

Selecting Users in a Particular AD Group Only

$
0
0
We use Service Now to automatically create new users where I work.  However, it only adds the user to the Domain Users group then we manually add them to the additional groups based on their role.  Sometimes managers will submit a new user form when the staff member only needs access to a 3rd party system.  We end up with AD User accounts that are only in the Domain Users group in this scenario.  I am trying to write a script that will list users that are ONLY in the Domain Users group.

Invoke-Command vs Get-WBJob

$
0
0

Hi guys,

So I've been slamming my head against this wall all day. I've got 4 servers that for some unknown reason are using Windows Server Backups and I'm trying to pull the info out of them to create a CSV to feed into a monitoring program we use.

One of the servers that I need to get info from is the one that the script is running on and it's pulling all the data out no problem.

Then I start remotely checking the other servers and I'm missing data.

ForEach ($computer in $computers) {
    $backup = New-Object PSObject
        $backup | Add-Member -NotePropertyName Computer -NotePropertyValue $null
        $backup | Add-Member -NotePropertyName WBSummary -NotePropertyValue $null
        $backup | Add-Member -NotePropertyName WBLastJob -NotePropertyValue $null

    if($computer -eq "localhost")
    {
		$backup.WBSummary = Get-WBSummary
		$backup.WBLastJob = Get-WBJob -Previous 1
                $backup.Computer = $computer
    }
    else
    {	
		# Create PSRemoting Connection
		$PSSesh = New-PSSession -ComputerName $computer
		# Run Remote PowerShell Commands - 2008 requires snapin
        if($computer -eq "remotehost2008"){Invoke-Command -Session $PSSesh -ScriptBlock {Add-PSSnapin Windows.ServerBackup}}
		$backup.WBSummary = Invoke-Command -Session $PSSesh -ScriptBlock {Get-WBSummary}
		$backup.WBLastJob = Invoke-Command -Session $PSSesh -ScriptBlock {Get-WBJob -Previous 1}
                $backup.Computer = $computer
    	# Remove PSRemoting Connection
	    Remove-PSSession -Session $PSSesh
	}

	$results += $backup
}

For $WBLastJob.JobItems for the local host, I get:

Name             : VolumeList
Type             : VolumeList
State            : Completed
HResult          : 0
DetailedHResult  : 0
ErrorDescription : 
BytesProcessed   : 97463435264
TotalBytes       : 97463435264
CurrentItem      : 
SubItemProcessed : 2
SubItemFailed    : 0
TotalSubItem     : 2
SubItemList      : {System Reserved, C:}

Name             : SystemState
Type             : SystemState
State            : Completed
HResult          : 0
DetailedHResult  : 0
ErrorDescription : 
BytesProcessed   : 0
TotalBytes       : 0
CurrentItem      : 
SubItemProcessed : 0
SubItemFailed    : 0
TotalSubItem     : 0
SubItemList      : 

Name             : BareMetalRecovery
Type             : BareMetalRecovery
State            : Completed
HResult          : 0
DetailedHResult  : 0
ErrorDescription : 
BytesProcessed   : 0
TotalBytes       : 0
CurrentItem      : 
SubItemProcessed : 2
SubItemFailed    : 0
TotalSubItem     : 2
SubItemList      : 

For the remote hosts:

VolumeList
SystemState
BareMetalRecovery
Is there any way of fixing this?


(Names have been changed)

I need to dump out the executable versions of certain apps and browsers - output formatting dilemma help please

$
0
0

Hi,

I have thrown this code together to output the versions of executables on a local machine ( I know I could use registry but I know of machines with multiple instances and some standalone exe's later on in the project ). 

The output to the screen is fine and that's in the format I want to capture, but when I append the string that I want so I could email it or stuff it in a csv later it obviously outputs the headers repeatedly and line feeds. I know this will be simple to you guys so please show me where I need to bend the code to do what I want.

Thanks

Darren 

$results= ''
$filestocheck = "Chrome.exe","iexplore.exe","MicrosoftEdge.exe","Firefox.exe"
$dirstocheck = "C:\Windows\SystemApps\","c:\Program Files (x86)\","c:\program files\"
foreach ($dirtocheck in $dirstocheck)
{
foreach ($filetocheck in $filestocheck)
{
get-childitem -path $dirtocheck -filter $filetocheck -Recurse | %{$_.VersionInfo} |Select-Object @{N='MachineName';E={$env:COMPUTERNAME}},FileDescription, FileVersion, FileName  

$results += get-childitem -path $dirtocheck -filter $filetocheck -Recurse | %{$_.VersionInfo} |Select-Object @{N='MachineName';E={$env:COMPUTERNAME}},FileDescription, FileVersion, FileName  |Out-String

#Write-host -NoNewline "`rChecking for versions of $filetocheck in $dirtocheck"
Write-Progress -Activity "$filetocheck in $dirtocheck"
                
}
}

$results

Change RemovableStoreage Write Access Polocies from Script

$
0
0

I am working on a script that i can quickly deploy to multiple windows 10 computers for the initial setup. Part of this setup is to change some Group Polocies, these are:

Administrative Templates/System/Removable Storage Access ->

- CD and DVD: Deny wire access

- Floppy Drives: Deny write access

- Removable Disks: Deny write access

- Tape Drives: Deny write access

- WPD Devices: Deny write access

Windows Components/Windows Update ->

- Configure Automaic Updates (Enabled, Notify for download and install)

I have been looking for any scripts that do these automatically but the only one i can find only edits the registry and does not edit Registry.pol, so as far as i can tell it only works if the polocies has arealy been enabled (https://gallery.technet.microsoft.com/scriptcenter/EnableDisable-access-to-334043ae)

Looking for another method that will work on a cean Windows 10 computer.


[C#] Apply Share Permission for multi-computers

$
0
0

Hello

I would like to add many computers into a share permission. But my function allow only one computer or account. I would like to know if there are properties or somethings else to allow many computers into share permission ?

If I play again my function, the first computer will be removed and the new one added, but I would like both.

Thanks for your help :)

public void GrantShare(string domain, string computername) { using (DirectoryEntry entry = new DirectoryEntry("LDAP://"+domain)) { using (DirectorySearcher mySearcher = new DirectorySearcher(entry)) { mySearcher.Filter = "(&(objectClass=computer)(cn="+ computername+"))"; mySearcher.SizeLimit = 0; mySearcher.PageSize = 250; mySearcher.PropertiesToLoad.Add("objectSid"); foreach (SearchResult resEnt in mySearcher.FindAll()) { si = new SecurityIdentifier((byte[])resEnt.Properties["objectSid"][0], 0); } } } ManagementObject userTrustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null); userTrustee["Name"] = computername; byte[] utenteSIDArray = new byte[si.BinaryLength]; si.GetBinaryForm(utenteSIDArray, 0); userTrustee["SID"] = utenteSIDArray; ManagementObject userACE = new ManagementClass(new ManagementPath("Win32_Ace"), null); userACE["AccessMask"] = 2032127; userACE["AceFlags"] = AceFlags.ObjectInherit | AceFlags.ContainerInherit; userACE["AceType"] = AceType.AccessAllowed; userACE["Trustee"] = userTrustee; ManagementObject userSecurityDescriptor = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null); userSecurityDescriptor["ControlFlags"] = 4; userSecurityDescriptor["DACL"] = new object[] { userACE }; ManagementClass mc = new ManagementClass("Win32_Share"); ManagementObject share = new ManagementObject(mc.Path + ".Name='MyShare'"); share.InvokeMethod("SetShareInfo", new object[] {null, "Share For ", userSecurityDescriptor }); }




Extract Data from XML

$
0
0

Hi,

I have an XML with this structure (the <Entry> parameters are much more):

<?xml version="1.0" encoding="utf-8" standalone="yes"?><KeePassFile><Root><Group><UUID>/VdBmHZszkOtUrNEclLTWA==</UUID><Name>Test</Name><Notes></Notes><IconID>49</IconID><Times><CreationTime>2019-01-16T07:38:08Z</CreationTime></Times><Group><UUID>+MXh9LS3DEaMFJtGn9vEsA==</UUID><Name>General</Name><Notes></Notes><IconID>48</IconID><Times><CreationTime>2019-01-16T07:38:16Z</CreationTime></Times><Entry><UUID>kkB8TmQ36Ua00yvkDW7X7A==</UUID><Times><CreationTime>2019-01-16T09:22:10Z</CreationTime><LastModificationTime>2019-01-16T09:38:40Z</LastModificationTime><LastAccessTime>2019-01-16T09:38:40Z</LastAccessTime><ExpiryTime>2019-01-19T00:00:00Z</ExpiryTime><Expires>True</Expires><UsageCount>2</UsageCount><LocationChanged>2019-01-16T09:22:10Z</LocationChanged></Times><String><Key>Notes</Key><Value></Value></String><String><Key>Password</Key><Value ProtectInMemory="True">ihrc4hsOormHChu1mLLi</Value></String><String><Key>Title</Key><Value>test</Value></String><String><Key>URL</Key><Value></Value></String><String><Key>UserName</Key><Value>testtesttest</Value></String><AutoType><Enabled>True</Enabled><DataTransferObfuscation>0</DataTransferObfuscation></AutoType></Entry><Entry><UUID>kkB8TmQ36Ua00yvkDW7X7A==</UUID><Times><CreationTime>2019-01-16T09:22:10Z</CreationTime><LastModificationTime>2019-01-16T09:38:40Z</LastModificationTime><LastAccessTime>2019-01-16T09:38:40Z</LastAccessTime><ExpiryTime>2019-01-20T00:00:00Z</ExpiryTime><Expires>True</Expires><UsageCount>2</UsageCount><LocationChanged>2019-01-16T09:22:10Z</LocationChanged></Times><String><Key>Notes</Key><Value></Value></String><String><Key>Password</Key><Value ProtectInMemory="True">ihrc4hsOormHChu1mLLi</Value></String><String><Key>Title</Key><Value>test2</Value></String><String><Key>URL</Key><Value></Value></String><String><Key>UserName</Key><Value>testtesttest</Value></String><AutoType><Enabled>True</Enabled><DataTransferObfuscation>0</DataTransferObfuscation></AutoType></Entry></Group></Root></KeePassFile>

I'd like to extract for each <Entry> where <Expires> is True, the <Value> of <Key> Title, and the <ExpiryTime>

I'm starting my script just extracting the <Value> for now but I can't understand why I get also the Value where Expires is not True:

if($xml.KeePassFile.Root.Group.Group.Entry.Times.Expires -eq $True) {

    if($xml.KeePassFile.Root.Group.Group.Entry | Where-Object {$_.UUID -ne $null})  {

    
    $xml.KeePassFile.Root.Group.Group.Entry.String | Where-Object {$_.Key -eq "Title"} | Select-Object Value
    }
}

A little help would be much appreciated



Export users groups to text file

$
0
0

Can anyone please help me?

I'm wanting a script to run and prompt me for the users username.

When i then enter the username i want it to export all the users groups to a text file that i can easily just copy and paste.

This is for example when i have a user who needs to be in the same groups as another user.

I can then run the script, enter the user name of the person with the needed groups.

Go to the text file, copy the groups and paste to the other persons memberships.

Thanks in advance :)!

Error on .bat script

$
0
0

Hi all,

We have 3 folders on a Shared folder that contains some files. There're 3 GPO, each one contain a folder. To change mounthly the content between folders, we created a Schedule process that run this .bat:

**********************************************************

@echo off

goto 1

:1
ren \\folder\Grupo1 Grupo0

timeout /t 5

goto 2

:2
ren \\folder\Grupo2 Grupo1

timeout /t 5

goto 3

:3
ren \\folder\Grupo3 Grupo2

timeout /t 5

goto 4

:4
ren \\folder\Grupo0 Grupo3

timeout /t 5

goto end

:end

************************************************

The problem is that sometimes, this proces when rename folders, make some (random) folder empty.

Some idea of what is the error? Running manually also delete some folder content random.

Thanks and regards,


Gerardo,

Script question

$
0
0

Hello

I have a simple script to monitor a serverlog and with this script,  the pc speaks the complete useragent string.

I want it  to filter  out just the name after "compatible"  and speak only that word,

Is that possible?

Thank you

Get-Content useragent.log -Tail 1 -wait | % {if ($_ -match "Compatible")
{Add-Type -AssemblyName System.speech
$Location = "$env:useragent.log"
$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
$Contents = Get-Content $Location -Tail 1 | where {$_ -match "Compatible"}
$speak.Speak($Contents)}}

PS Script for Emailing List, Including FindTime

$
0
0

I have a script to send emails to a list of users in a csv, what I'd like to know is if anyone has any ideas on how to include a FindTime invite using PS. Thanks!


New-ADUser : The object name has bad syntax

$
0
0

I am trying to pull information from a .CSV file to create AD Users in this same script I am trying to pull the OU from the parent user listed on the CSV file. However for the life of me I can not get this thing to run without giving me the same error each time. i have checked for blank spaces and I don' see anything that would suggest that it's wrong can someone lend me their knowledge on the matter?

# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv C:\PScripts\UsersToCreate.csv

#Loop through each row containing user details in the CSV file 
foreach ($User in $ADUsers)
{
    #Read user data from each field in each row and assign the data to a variable as below
    $Username = $User.SamAccountName 
    $SamAccountName = $Firstname.Substring(0,1) + $Lastname
    $Password = $User.Password
    $Firstname = $User.FirstName
    $Lastname = $User.LastName
    $email = $User.Email
    $OfficePhone = $User.Office
    $Mobile = $User.Mobile
    $jobtitle = $User.Title
    $company = $User.Company
    $department = $User.Department
    $Password = $User.Password
    $Manager = $User.Manager
    $DisplayName = $User.Displayname
    $UserToCopy = $User.UserToCopy
    $DN = $User.distinguishedName
    $OldUser = [ADSI]"LDAP://$DN"
    $Parent = $OldUser.Parent
    $OU = [ADSI]$Parent
    $OUDN = $OU.distinguishedName

	#Check to see if the user already exists in AD
	if (Get-ADUser -F {SamAccountName -eq $Username})
	{
		 #If user does exist, give a warning
		 Write-Warning "A user account with username $Username already exist in Active Directory."
         # Loop until we get a sam account that is not in the domain
         while ($Username -ne $null) {Write-Host "$SamAccountName is already in AD, please enter Username manually."
	     $SamAccountName = Read-Host -Prompt "UserName"
	     $Username = $(try {Get-ADUser $SamAccountName} catch {$null})
}
    }
	else
	{
        #User does not exist then proceed to create the new user account with the following CSV criteria.
         New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$Username@domain.net" `
            -Name "$Firstname, $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Lastname, $Firstname" `
            -Path $OldUser `
            -Manager $Manager `
            -Company $company `
            -Mobile $Mobile `
            -OfficePhone $OfficePhone `
            -EmailAddress $email `
            -Title $jobtitle `
            -Department $department `
            -AccountPassword (ConvertTo-SecureString "$Password" -AsPlainText -force) `        
	}
}

CSV Headers:

-UserToCopy

-FirstName

-LastNameSam

-AccountName

-DisplayName

-Department

-Title-Manager

-Office

-Phone

-Company

-Password

-MobilePhone   

-Email


Viewing all 15028 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>